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.service.ISqbPerformanceGoodsService;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.vo.GoblinSqbPerfGoodsVo;
import com.liquidnet.service.goblin.entity.GoblinGoods;
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 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 {

    /** Redis key 前缀，与 goblin C端接口保持一致 */
    private static final String PERF_GOODS_CACHE_KEY_PREFIX = "goblin:sqb:perf:goods:";

    @Autowired
    private GoblinSqbPerformanceGoodsMapper performanceGoodsMapper;

    @Autowired
    private GoblinGoodsMapper goblinGoodsMapper;

    @Autowired
    private GoblinGoodsSkuMapper goblinGoodsSkuMapper;

    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;

    @Override
    public ResponseDto<Boolean> bind(String performancesId, List<String> skuIds, Integer sort) {
        if (performancesId == null || performancesId.isEmpty()) {
            return ResponseDto.failure("演出ID不能为空");
        }
        if (skuIds == null || skuIds.isEmpty()) {
            return ResponseDto.failure("SKU列表不能为空");
        }

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        int sortVal = (sort != null) ? sort : 0;

        try {
            for (String skuId : skuIds) {
                if (skuId == null || skuId.isEmpty()) {
                    continue;
                }

                // 查询 SKU 获取 spuId
                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;
                }

                // 检查是否已存在关联
                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) {
                    // 已存在则更新 sort 和 status
                    LambdaUpdateWrapper<GoblinSqbPerformanceGoods> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                            .eq(GoblinSqbPerformanceGoods::getSkuId, skuId)
                            .set(GoblinSqbPerformanceGoods::getSort, sortVal)
                            .set(GoblinSqbPerformanceGoods::getStatus, 1)
                            .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.setCreatedAt(now);
                    entity.setUpdatedAt(now);
                    performanceGoodsMapper.insert(entity);
                }
            }

            // 删除 Redis 缓存，由 C端接口下次请求时重建
            delPerfGoodsCache(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 (performancesId == null || performancesId.isEmpty()) {
            return ResponseDto.failure("演出ID不能为空");
        }
        if (skuId == null || skuId.isEmpty()) {
            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("关联记录不存在");
            }

            // 删除 Redis 缓存
            delPerfGoodsCache(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 (performancesId == null || performancesId.isEmpty()) {
            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<>());
            }

            // 收集 skuId 和 spuId
            List<String> skuIds = relations.stream()
                    .map(GoblinSqbPerformanceGoods::getSkuId)
                    .collect(Collectors.toList());
            List<String> spuIds = relations.stream()
                    .map(GoblinSqbPerformanceGoods::getSpuId)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询 SKU 信息
            LambdaQueryWrapper<GoblinGoodsSku> skuQuery = new LambdaQueryWrapper<>();
            skuQuery.in(GoblinGoodsSku::getSkuId, skuIds);
            List<GoblinGoodsSku> skuList = goblinGoodsSkuMapper.selectList(skuQuery);
            Map<String, GoblinGoodsSku> skuMap = skuList.stream()
                    .collect(Collectors.toMap(GoblinGoodsSku::getSkuId, Function.identity(), (a, b) -> a));

            // 批量查询 SPU 信息
            LambdaQueryWrapper<GoblinGoods> spuQuery = new LambdaQueryWrapper<>();
            spuQuery.in(GoblinGoods::getSpuId, spuIds);
            List<GoblinGoods> spuList = goblinGoodsMapper.selectList(spuQuery);
            Map<String, GoblinGoods> spuMap = spuList.stream()
                    .collect(Collectors.toMap(GoblinGoods::getSpuId, Function.identity(), (a, b) -> a));

            // 组装 VO
            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());

                GoblinGoodsSku sku = skuMap.get(rel.getSkuId());
                if (sku != null) {
                    vo.setSkuName(sku.getName());
                    vo.setPrice(sku.getPrice() != null ? sku.getPrice().longValue() : null);
                }

                GoblinGoods spu = spuMap.get(rel.getSpuId());
                if (spu != null) {
                    vo.setSpuName(spu.getName());
                    vo.setCoverPic(spu.getCoverPic());
                }

                result.add(vo);
            }

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

    /**
     * 删除演出关联商品的 Redis 缓存
     */
    private void delPerfGoodsCache(String performancesId) {
        try {
            String cacheKey = PERF_GOODS_CACHE_KEY_PREFIX + performancesId;
            redisDataSourceUtil.getRedisGoblinUtil().del(cacheKey);
            log.info("[演出商品关联] 已删除 Redis 缓存，key={}", cacheKey);
        } catch (Exception e) {
            log.warn("[演出商品关联] 删除 Redis 缓存失败，performancesId={}", performancesId, e);
        }
    }
}
