package com.liquidnet.client.admin.zhengzai.goblin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.liquidnet.client.admin.zhengzai.goblin.dto.SqbPerfGoodsBindItemParam;
import com.liquidnet.client.admin.zhengzai.goblin.service.ISqbPerformanceGoodsService;
import com.liquidnet.client.admin.zhengzai.goblin.utils.GoblinRedisUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.vo.GoblinSqbPerfGoodsVo;
import com.liquidnet.service.goblin.entity.GoblinGoodsSku;
import com.liquidnet.service.goblin.entity.GoblinSqbPerformanceGoods;
import com.liquidnet.service.goblin.mapper.GoblinGoodsMapper;
import com.liquidnet.service.goblin.mapper.GoblinGoodsSkuMapper;
import com.liquidnet.service.goblin.mapper.GoblinSqbPerformanceGoodsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 演出-收钱吧商品关联 服务实现
 * 直连 MySQL，写入/删除时同步删除 Redis 缓存
 */
@Slf4j
@Service
public class SqbPerformanceGoodsServiceImpl implements ISqbPerformanceGoodsService {

    /** skuType=33 代表收钱吧商品 */
    private static final int SQB_SKU_TYPE = 33;

    @Autowired
    private GoblinSqbPerformanceGoodsMapper performanceGoodsMapper;

    @Autowired
    private GoblinGoodsMapper goblinGoodsMapper;

    @Autowired
    private GoblinGoodsSkuMapper goblinGoodsSkuMapper;

    @Autowired
    private GoblinRedisUtils goblinRedisUtils;

    @Override
    public ResponseDto<Boolean> bind(String performancesId, List<SqbPerfGoodsBindItemParam> items) {
        if (!StringUtils.hasText(performancesId)) {
            return ResponseDto.failure("演出ID不能为空");
        }
        if (items == null || items.isEmpty()) {
            return ResponseDto.failure("商品列表不能为空");
        }

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        try {
            for (SqbPerfGoodsBindItemParam item : items) {
                String skuId = item.getSkuId();
                if (!StringUtils.hasText(skuId)) {
                    continue;
                }

                // 查询 SKU 获取 spuId，并校验 skuType=33
                LambdaQueryWrapper<GoblinGoodsSku> skuQuery = new LambdaQueryWrapper<>();
                skuQuery.eq(GoblinGoodsSku::getSkuId, skuId).last("LIMIT 1");
                GoblinGoodsSku sku = goblinGoodsSkuMapper.selectOne(skuQuery);
                if (sku == null) {
                    log.warn("[演出商品关联] SKU不存在，skuId={}", skuId);
                    continue;
                }
                if (sku.getSkuType() == null || sku.getSkuType() != SQB_SKU_TYPE) {
                    log.warn("[演出商品关联] 非收钱吧商品（skuType!=33），skuId={}", skuId);
                    continue;
                }

                int sortVal = item.getSort() != null ? item.getSort() : 0;
                int autoOfflineVal = item.getAutoOffline() != null ? item.getAutoOffline() : 0;

                // 检查是否已存在关联
                LambdaQueryWrapper<GoblinSqbPerformanceGoods> existQuery = new LambdaQueryWrapper<>();
                existQuery.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                        .eq(GoblinSqbPerformanceGoods::getSkuId, skuId)
                        .last("LIMIT 1");
                GoblinSqbPerformanceGoods existing = performanceGoodsMapper.selectOne(existQuery);

                if (existing != null) {
                    // 已存在则更新配置
                    LambdaUpdateWrapper<GoblinSqbPerformanceGoods> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                            .eq(GoblinSqbPerformanceGoods::getSkuId, skuId)
                            .set(GoblinSqbPerformanceGoods::getSort, sortVal)
                            .set(GoblinSqbPerformanceGoods::getStatus, 1)
                            .set(GoblinSqbPerformanceGoods::getSettlementPrice, item.getSettlementPrice())
                            .set(GoblinSqbPerformanceGoods::getAutoOffline, autoOfflineVal)
                            .set(GoblinSqbPerformanceGoods::getUpdatedAt, now);
                    performanceGoodsMapper.update(null, updateWrapper);
                } else {
                    // 新增关联记录
                    GoblinSqbPerformanceGoods entity = new GoblinSqbPerformanceGoods();
                    entity.setPerformancesId(performancesId);
                    entity.setSpuId(sku.getSpuId());
                    entity.setSkuId(skuId);
                    entity.setSort(sortVal);
                    entity.setStatus(1);
                    entity.setSettlementPrice(item.getSettlementPrice());
                    entity.setAutoOffline(autoOfflineVal);
                    entity.setCreatedAt(now);
                    entity.setUpdatedAt(now);
                    performanceGoodsMapper.insert(entity);
                }
            }

            // 删除 Redis 缓存，由 C端接口下次请求时重建
            goblinRedisUtils.delPerformanceGoodsCache(performancesId);

            return ResponseDto.success(Boolean.TRUE);
        } catch (Exception e) {
            log.error("[演出商品关联] bind 异常，performancesId={}", performancesId, e);
            return ResponseDto.failure("关联操作失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseDto<Boolean> unbind(String performancesId, String skuId) {
        if (!StringUtils.hasText(performancesId)) {
            return ResponseDto.failure("演出ID不能为空");
        }
        if (!StringUtils.hasText(skuId)) {
            return ResponseDto.failure("SKU ID不能为空");
        }

        try {
            LambdaUpdateWrapper<GoblinSqbPerformanceGoods> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                    .eq(GoblinSqbPerformanceGoods::getSkuId, skuId)
                    .set(GoblinSqbPerformanceGoods::getStatus, 0)
                    .set(GoblinSqbPerformanceGoods::getUpdatedAt,
                            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            int rows = performanceGoodsMapper.update(null, updateWrapper);

            if (rows == 0) {
                return ResponseDto.failure("关联记录不存在");
            }

            goblinRedisUtils.delPerformanceGoodsCache(performancesId);
            return ResponseDto.success(Boolean.TRUE);
        } catch (Exception e) {
            log.error("[演出商品关联] unbind 异常，performancesId={}, skuId={}", performancesId, skuId, e);
            return ResponseDto.failure("解除关联失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> list(String performancesId) {
        if (!StringUtils.hasText(performancesId)) {
            return ResponseDto.failure("演出ID不能为空");
        }

        try {
            LambdaQueryWrapper<GoblinSqbPerformanceGoods> query = new LambdaQueryWrapper<>();
            query.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                    .eq(GoblinSqbPerformanceGoods::getStatus, 1)
                    .orderByAsc(GoblinSqbPerformanceGoods::getSort);
            List<GoblinSqbPerformanceGoods> relations = performanceGoodsMapper.selectList(query);

            if (relations == null || relations.isEmpty()) {
                return ResponseDto.success(new ArrayList<>());
            }

            List<String> skuIds = relations.stream()
                    .map(GoblinSqbPerformanceGoods::getSkuId).collect(Collectors.toList());

            // 因为收钱吧商品 SKU 已经包含了名称和图片等全部信息，无需再去关联查询 SPU 表
            LambdaQueryWrapper<GoblinGoodsSku> skuQuery = new LambdaQueryWrapper<>();
            skuQuery.in(GoblinGoodsSku::getSkuId, skuIds);
            Map<String, GoblinGoodsSku> skuMap = goblinGoodsSkuMapper.selectList(skuQuery)
                    .stream().collect(Collectors.toMap(GoblinGoodsSku::getSkuId, Function.identity(), (a, b) -> a));

            List<GoblinSqbPerfGoodsVo> result = new ArrayList<>();
            for (GoblinSqbPerformanceGoods rel : relations) {
                GoblinSqbPerfGoodsVo vo = new GoblinSqbPerfGoodsVo();
                vo.setSkuId(rel.getSkuId());
                vo.setSpuId(rel.getSpuId());
                vo.setSort(rel.getSort());
                vo.setSettlementPrice(rel.getSettlementPrice());
                vo.setAutoOffline(rel.getAutoOffline());
                vo.setStatus(rel.getStatus());

                GoblinGoodsSku sku = skuMap.get(rel.getSkuId());
                if (sku != null) {
                    vo.setSkuName(sku.getName());
                    vo.setSpuName(sku.getName()); // 取代原本从 SPU 获取名称，直接用 SKU 名称
                    vo.setCoverPic(sku.getSkuPic()); // 统一使用 SKU 上的默认图片（即原 SPU coverPic）
                    vo.setPrice(sku.getPrice() != null ? sku.getPrice().longValue() : null);
                    vo.setStock(sku.getSkuStock());
                }

                result.add(vo);
            }

            return ResponseDto.success(result);
        } catch (Exception e) {
            log.error("[演出商品关联] list 异常，performancesId={}", performancesId, e);
            return ResponseDto.failure("查询失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> searchGoods(String keyword) {
        try {
            // 收钱吧商品的所有核心展示信息均已同步到 SKU（Type=33）表中，直接一次查询避免二次查 SPU
            LambdaQueryWrapper<GoblinGoodsSku> skuQuery = new LambdaQueryWrapper<>();
            skuQuery.eq(GoblinGoodsSku::getSkuType, SQB_SKU_TYPE);
            if (StringUtils.hasText(keyword)) {
                skuQuery.like(GoblinGoodsSku::getName, keyword);
            }
            skuQuery.last("LIMIT 50");
            List<GoblinGoodsSku> skuList = goblinGoodsSkuMapper.selectList(skuQuery);

            if (skuList.isEmpty()) {
                return ResponseDto.success(new ArrayList<>());
            }

            List<GoblinSqbPerfGoodsVo> result = new ArrayList<>();
            for (GoblinGoodsSku sku : skuList) {
                GoblinSqbPerfGoodsVo vo = new GoblinSqbPerfGoodsVo();
                vo.setSkuId(sku.getSkuId());
                vo.setSpuId(sku.getSpuId());
                vo.setSkuName(sku.getName());
                vo.setSpuName(sku.getName()); // 前端显示需要，统一赋值为 sku 名称
                vo.setCoverPic(sku.getSkuPic()); // 同步阶段已将图片存入了 skuPic
                vo.setPrice(sku.getPrice() != null ? sku.getPrice().longValue() : null);
                vo.setStock(sku.getSkuStock());
                result.add(vo);
            }
            return ResponseDto.success(result);
        } catch (Exception e) {
            log.error("[演出商品关联] searchGoods 异常，keyword={}", keyword, e);
            return ResponseDto.failure("搜索失败：" + e.getMessage());
        }
    }

}
