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.dto.vo.GoblinSqbPerfListRespVo;
import com.liquidnet.service.goblin.entity.GoblinGoodsSku;
import com.liquidnet.service.goblin.entity.GoblinSqbPerformanceConfig;
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.GoblinSqbPerformanceConfigMapper;
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 GoblinSqbPerformanceConfigMapper performanceConfigMapper;

    @Autowired
    private GoblinGoodsMapper goblinGoodsMapper;

    @Autowired
    private GoblinGoodsSkuMapper goblinGoodsSkuMapper;

    @Autowired
    private GoblinRedisUtils goblinRedisUtils;

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

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

        try {
            // 1. 保存全局配置
            GoblinSqbPerformanceConfig config = performanceConfigMapper.selectById(performancesId);
            if (config == null) {
                config = new GoblinSqbPerformanceConfig();
                config.setPerformancesId(performancesId);
                config.setAutoOffline(autoOffline != null ? autoOffline : 0);
                config.setCreatedAt(nowStr);
                config.setUpdatedAt(nowStr);
                performanceConfigMapper.insert(config);
            } else {
                config.setAutoOffline(autoOffline != null ? autoOffline : 0);
                config.setUpdatedAt(nowStr);
                performanceConfigMapper.updateById(config);
            }

            // 2. 批量处理商品绑定
            for (SqbPerfGoodsBindItemParam item : items) {
                String skuId = item.getSkuId();
                if (!StringUtils.hasText(skuId)) {
                    continue;
                }

                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;
                }

                int sortVal = item.getSort() != null ? item.getSort() : 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::getUpdatedAt, nowStr);
                    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.setCreatedAt(nowStr);
                    entity.setUpdatedAt(nowStr);
                    performanceGoodsMapper.insert(entity);
                }
            }

            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<GoblinSqbPerfListRespVo> list(String performancesId) {
        if (!StringUtils.hasText(performancesId)) {
            return ResponseDto.failure("演出ID不能为空");
        }

        try {
            GoblinSqbPerfListRespVo resp = new GoblinSqbPerfListRespVo();
            
            // 1. 查询全局配置
            GoblinSqbPerformanceConfig config = performanceConfigMapper.selectById(performancesId);
            resp.setAutoOffline(config != null ? config.getAutoOffline() : 0);

            // 2. 查询关联商品
            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()) {
                resp.setGoodsList(new ArrayList<>());
                return ResponseDto.success(resp);
            }

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

            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> goodsList = 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.setStatus(rel.getStatus());

                GoblinGoodsSku sku = skuMap.get(rel.getSkuId());
                if (sku != null) {
                    vo.setSkuName(sku.getName());
                    vo.setSpuName(sku.getName());
                    vo.setCoverPic(sku.getSkuPic());
                    vo.setPrice(sku.getPrice() != null ? sku.getPrice().longValue() : null);
                    vo.setStock(sku.getSkuStock());
                }
                goodsList.add(vo);
            }
            resp.setGoodsList(goodsList);

            return ResponseDto.success(resp);
        } 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());
        }
    }

}
