package com.liquidnet.service.goblin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.GoblinGoodsSpecDto;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsAddParam;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsEditSkuParam;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsInfoVo;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSkuInfoVo;
import com.liquidnet.service.goblin.dto.vo.GoblinSqbPerfGoodsVo;
import com.liquidnet.service.goblin.config.properties.ShouqianbaProperties;
import com.liquidnet.service.goblin.entity.GoblinGoods;
import com.liquidnet.service.goblin.entity.GoblinGoodsSku;
import com.liquidnet.service.goblin.entity.GoblinSqbGoodsExt;
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.GoblinSqbGoodsExtMapper;
import com.liquidnet.service.goblin.mapper.GoblinSqbPerformanceGoodsMapper;
import com.liquidnet.service.goblin.mapper.GoblinSqbPerformanceConfigMapper;
import com.liquidnet.service.goblin.entity.GoblinSqbPerformanceConfig;
import com.liquidnet.service.goblin.param.shouqianba.request.CommonRequest;
import com.liquidnet.service.goblin.param.shouqianba.request.MallListQueryRequest;
import com.liquidnet.service.goblin.param.shouqianba.request.MallProductsQueryRequest;
import com.liquidnet.service.goblin.param.shouqianba.response.data.MallListQueryData;
import com.liquidnet.service.goblin.param.shouqianba.response.data.MallProductsQueryData;
import com.liquidnet.service.goblin.service.IGoblinShouQianBaService;
import com.liquidnet.service.goblin.service.IGoblinSqbGoodsService;
import com.liquidnet.service.goblin.util.GoblinMongoUtils;
import com.liquidnet.service.goblin.dto.vo.GoblinSelfMarketingVo;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.GoblinSqbRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsSpecVo;
import com.liquidnet.service.goblin.service.manage.IGoblinstoreMgtGoodsService;
import com.liquidnet.service.goblin.dto.manage.*;
import com.liquidnet.service.goblin.util.ObjectUtil;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 收钱吧商品同步服务实现
 */
@Slf4j
@Service
public class GoblinSqbGoodsServiceImpl implements IGoblinSqbGoodsService {

    @Autowired
    private ShouqianbaProperties shouqianbaProperties;

    @Autowired
    private GoblinGoodsMapper goblinGoodsMapper;

    @Autowired
    private GoblinGoodsSkuMapper goblinGoodsSkuMapper;

    @Autowired
    private GoblinSqbGoodsExtMapper goblinSqbGoodsExtMapper;

    @Autowired
    private GoblinSqbPerformanceGoodsMapper goblinSqbPerformanceGoodsMapper;

    @Autowired
    private IGoblinShouQianBaService goblinShouQianBaService;

    @Autowired
    private GoblinSqbRedisUtils goblinSqbRedisUtils;

    @Autowired
    private GoblinRedisUtils goblinRedisUtils;

    @Autowired
    private GoblinSqbPerformanceConfigMapper goblinSqbPerformanceConfigMapper;

    @Autowired
    private GoblinMongoUtils goblinMongoUtils;

    @Autowired
    private IGoblinstoreMgtGoodsService goblinstoreMgtGoodsService;

    @Override
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> getProductList() {
        try {
            List<GoblinSqbPerfGoodsVo> result = new ArrayList<>();
            List<MallListQueryData> mallList = fetchAllMalls();
            if (CollectionUtils.isEmpty(mallList)) {
                return ResponseDto.success(new ArrayList<>());
            }

            // 获取本地已同步的商品 SPU 映射，用于标记同步状态
            List<String> mallSns = mallList.stream().map(MallListQueryData::getMallSn).distinct()
                    .collect(Collectors.toList());
            List<GoblinSqbGoodsExt> syncedGoods = goblinSqbGoodsExtMapper.selectList(
                    new LambdaQueryWrapper<GoblinSqbGoodsExt>()
                            .in(GoblinSqbGoodsExt::getMallSn, mallSns)
                            .eq(GoblinSqbGoodsExt::getDelFlg, "0"));
            Set<String> syncedSqbSpuKeySet = syncedGoods.stream()
                    .map(g -> g.getMallSn() + ":" + g.getSqbSpuId())
                    .collect(Collectors.toSet());

            for (MallListQueryData mall : mallList) {
                List<MallProductsQueryData> products = fetchAllProducts(mall);
                if (!CollectionUtils.isEmpty(products)) {
                    for (MallProductsQueryData product : products) {
                        GoblinSqbPerfGoodsVo goblinSqbPerfGoodsVo = getGoblinSqbPerfGoodsVo(mall, product);
                        goblinSqbPerfGoodsVo
                                .setSynced(syncedSqbSpuKeySet.contains(mall.getMallSn() + ":" + product.getSpuId()));
                        result.add(goblinSqbPerfGoodsVo);
                    }
                }
            }

            return ResponseDto.success(result);
        } catch (Exception e) {
            log.error("search mall products error", e);
            return ResponseDto.failure("查询收钱吧商品失败: " + e.getMessage());
        }
    }

    private static GoblinSqbPerfGoodsVo getGoblinSqbPerfGoodsVo(MallListQueryData mall, MallProductsQueryData product) {
        GoblinSqbPerfGoodsVo goblinSqbPerfGoodsVo = new GoblinSqbPerfGoodsVo();
        goblinSqbPerfGoodsVo.setMallSn(mall.getMallSn());
        goblinSqbPerfGoodsVo.setMallName(mall.getMallName());
        goblinSqbPerfGoodsVo.setSignature(mall.getSignature());
        goblinSqbPerfGoodsVo.setSpuId(product.getSpuId());
        goblinSqbPerfGoodsVo.setTitle(product.getTitle());
        goblinSqbPerfGoodsVo.setProductIntroduction(product.getProductIntroduction());
        goblinSqbPerfGoodsVo.setConverImages(product.getConverImages());
        goblinSqbPerfGoodsVo.setSkuResults(product.getSkuResults());
        return goblinSqbPerfGoodsVo;
    }

    /**
     * 循环获取所有商城列表（支持游标分页）
     */
    private List<MallListQueryData> fetchAllMalls() {
        List<MallListQueryData> allMalls = new ArrayList<>();
        int count = 100;
        String lastMallSn = null;
        while (true) {
            MallListQueryRequest mallRequest = new MallListQueryRequest();
            mallRequest.setAppid(shouqianbaProperties.getAppId());
            MallListQueryRequest.Filter filter = new MallListQueryRequest.Filter();
            filter.setSeller(buildSeller());
            mallRequest.setFilter(filter);

            MallListQueryRequest.Cursor cursor = new MallListQueryRequest.Cursor();
            cursor.setCursorField("id");
            cursor.setCount(count); // 最大支持1000
            cursor.setEndCursor(lastMallSn);
            mallRequest.setCursor(cursor);

            MallListQueryRequest.Sort sort = new MallListQueryRequest.Sort();
            sort.setSortField("id");
            sort.setSort("DESC");
            mallRequest.setSort(sort);

            List<MallListQueryData> batch = goblinShouQianBaService.queryMallList(mallRequest);
            if (CollectionUtils.isEmpty(batch)) {
                break;
            }
            allMalls.addAll(batch);
            lastMallSn = batch.get(batch.size() - 1).getMallSn();
            // 如果拉取数量小于 count，说明是最后一页
            if (batch.size() != count) {
                break;
            }
        }
        return allMalls;
    }

    /**
     * 循环获取某个商城下的所有商品列表（支持搜索和游标分页）
     */
    private List<MallProductsQueryData> fetchAllProducts(MallListQueryData mall) {
        MallProductsQueryRequest productRequest = new MallProductsQueryRequest();
        productRequest.setAppid(shouqianbaProperties.getAppId());
        productRequest.setSeller(buildSeller());
        CommonRequest.Mall mallId = new CommonRequest.Mall();
        mallId.setMallSn(mall.getMallSn());
        mallId.setSignature(mall.getSignature());
        productRequest.setMallID(mallId);

        return goblinShouQianBaService.queryMallProducts(productRequest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> addGoods(String storeId, List<GoblinSqbPerfGoodsVo> items) {
        if (CollectionUtils.isEmpty(items))
            return ResponseDto.failure("新增商品列表不能为空");
        int newCount = 0, existCount = 0, failCount = 0;
        String currentUid = "system";

        for (GoblinSqbPerfGoodsVo item : items) {
            String sqbSpuid = item.getSpuId(),
                    mallSn = item.getMallSn(), mallSignature = item.getSignature();
            if (StringUtils.isEmpty(sqbSpuid)) {
                failCount++;
                continue;
            }
            try {
                LambdaQueryWrapper<GoblinSqbGoodsExt> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(GoblinSqbGoodsExt::getSqbSpuId, sqbSpuid)
                        .eq(GoblinSqbGoodsExt::getMallSn, mallSn)
                        .eq(GoblinSqbGoodsExt::getDelFlg, "0");
                if (goblinSqbGoodsExtMapper.selectCount(queryWrapper) > 0) {
                    existCount++;
                    continue;
                }

                // 1. 组装 AddParam
                GoblinStoreMgtGoodsAddParam addParam = buildMgtGoodsAddParam(storeId, item);

                // 2. 初始化 VOs
                LocalDateTime now = LocalDateTime.now();
                GoblinGoodsInfoVo goodsInfoVo = addParam.initGoodsInfoVo();
                goodsInfoVo.setCreatedBy(currentUid);
                goodsInfoVo.setCreatedAt(now);
                goodsInfoVo.setSpuType(33);
                goodsInfoVo.setVirtualFlg("1");

                ArrayList<GoblinGoodsSpecVo> goodsSpecVoList = ObjectUtil.getGoblinGoodsSpecVoArrayList();
                List<GoblinGoodsSkuInfoVo> goodsSkuInfoVoList = ObjectUtil.getGoblinGoodsSkuInfoVoArrayList();
                List<GoblinSqbGoodsExt> goblinSqbGoodsExtsList = ObjectUtil.getGoblinSqbGoodsExtArrayList();
                addParam.initGoodsSkuInfoVo(goodsInfoVo, goodsSkuInfoVoList, goodsSpecVoList);

                // 3. 建立并保存映射关系
                for (GoblinGoodsSkuInfoVo skuVo : goodsSkuInfoVoList) {
                    skuVo.setSkuType(33);
                    skuVo.setVirtualFlg("1");
                    skuVo.setCreatedBy(currentUid);
                    skuVo.setCreatedAt(now);
                    // 使用 skuNo 暂存的 sqbSkuId 建立映射
                    String sqbSkuId = skuVo.getSkuNo();
                    goblinSqbGoodsExtsList.add(buildExt(goodsInfoVo.getSpuId(), skuVo.getSkuId(),
                            mallSn, mallSignature, sqbSpuid, sqbSkuId, now));
                }

                // 4. 调用管理端 Service 加
                goblinstoreMgtGoodsService.goodsAdd(goodsInfoVo, goodsSkuInfoVoList);

                // 5. 建立映射
                for (GoblinSqbGoodsExt goblinSqbGoodsExt : goblinSqbGoodsExtsList) {
                    goblinSqbGoodsExtMapper.insert(goblinSqbGoodsExt);
                }
                newCount++;
            } catch (Exception e) {
                log.error("[收钱吧新增商品同步] 异常, sqbProductId={}", sqbSpuid, e);
                failCount++;
            }
        }
        return ResponseDto.success(String.format("新增完成：同步 %d, 已存在 %d, 失败 %d", newCount, existCount, failCount));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> updateGoods(String storeId, List<GoblinSqbPerfGoodsVo> items) {
        if (CollectionUtils.isEmpty(items))
            return ResponseDto.failure("更新商品列表不能为空");
        int updateCount = 0, notFoundCount = 0, failCount = 0;
        String currentUid = "system";

        for (GoblinSqbPerfGoodsVo item : items) {
            String sqbSpuId = item.getSpuId(), mallSn = item.getMallSn();
            try {
                LambdaQueryWrapper<GoblinSqbGoodsExt> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(GoblinSqbGoodsExt::getSqbSpuId, sqbSpuId)
                        .eq(GoblinSqbGoodsExt::getMallSn, mallSn)
                        .eq(GoblinSqbGoodsExt::getDelFlg, "0");
                List<GoblinSqbGoodsExt> existingExts = goblinSqbGoodsExtMapper.selectList(queryWrapper);
                if (CollectionUtils.isEmpty(existingExts)) {
                    notFoundCount++;
                    continue;
                }

                String spuId = existingExts.get(0).getSpuId();
                GoblinGoodsInfoVo mgtGoodsInfoVo = goblinRedisUtils.getGoodsInfoVo(spuId);
                if (null == mgtGoodsInfoVo) {
                    notFoundCount++;
                    continue;
                }

                // 2. 编辑 SPU
                // 注意：这里需要根据 MallProductsQueryData 构建参数，建议增加一个重载方法或做转换
                GoblinSqbPerfGoodsVo perfGoodsVo = new GoblinSqbPerfGoodsVo();
                perfGoodsVo.setTitle(item.getTitle());
                perfGoodsVo.setProductIntroduction(item.getProductIntroduction());
                perfGoodsVo.setConverImages(item.getConverImages());
                perfGoodsVo.setSkuResults(item.getSkuResults());

                GoblinStoreMgtGoodsAddParam addParam = buildMgtGoodsAddParam(storeId, perfGoodsVo);
                addParam.setSpuId(spuId);
                goblinstoreMgtGoodsService.goodsEditSpu(currentUid, addParam, mgtGoodsInfoVo);

                // 3. 编辑 SKU
                Map<String, String> sqbToSysSkuMap = new HashMap<>();
                for (GoblinSqbGoodsExt ext : existingExts) {
                    sqbToSysSkuMap.put(ext.getSqbSkuId() != null ? ext.getSqbSkuId() : "PLACEHOLDER", ext.getSkuId());
                }

                List<MallProductsQueryData.Sku> sqbSkus = item.getSkuResults();
                Set<String> processedSqbSkuIds = new HashSet<>();
                if (CollectionUtils.isEmpty(sqbSkus)) {
                    String skuId = sqbToSysSkuMap.get("PLACEHOLDER");
                    if (skuId != null) {
                        processSkuUpdate(currentUid, storeId, skuId, item, null);
                        processedSqbSkuIds.add("PLACEHOLDER");
                    }
                } else {
                    for (MallProductsQueryData.Sku sqbSku : sqbSkus) {
                        String skuId = sqbToSysSkuMap.get(sqbSku.getSkuId());
                        if (skuId != null) {
                            // 已存在，执行更新
                            processSkuUpdate(currentUid, storeId, skuId, item, sqbSku);
                            processedSqbSkuIds.add(sqbSku.getSkuId());
                        } else {
                            // 新增 SKU
                            List<String> oldSkuIdList = new ArrayList<>(mgtGoodsInfoVo.getSkuIdList());
                            processSkuAddition(currentUid, storeId, mgtGoodsInfoVo, item, sqbSku);
                            List<String> newSkuIdList = mgtGoodsInfoVo.getSkuIdList();

                            // 找出新增的 skuId
                            String newSkuId = newSkuIdList.stream()
                                    .filter(id -> !oldSkuIdList.contains(id))
                                    .findFirst().orElse(null);

                            if (newSkuId != null) {
                                GoblinSqbGoodsExt newExt = new GoblinSqbGoodsExt();
                                newExt.setMallSn(mallSn);
                                newExt.setSqbSpuId(sqbSpuId);
                                newExt.setSqbSkuId(sqbSku.getSkuId());
                                newExt.setSpuId(spuId);
                                newExt.setSkuId(newSkuId);
                                newExt.setDelFlg("0");
                                newExt.setCreatedAt(LocalDateTime.now());
                                goblinSqbGoodsExtMapper.insert(newExt);
                                processedSqbSkuIds.add(sqbSku.getSkuId());
                            }
                        }
                    }
                }

                // 4. 处理被删除的 SKU
                LocalDateTime now = LocalDateTime.now();
                for (GoblinSqbGoodsExt ext : existingExts) {
                    String sqbSkuId = ext.getSqbSkuId() != null ? ext.getSqbSkuId() : "PLACEHOLDER";
                    if (!processedSqbSkuIds.contains(sqbSkuId)) {
                        processSkuDeletion(currentUid, ext, mgtGoodsInfoVo);
                        // 假删除
                        ext.setDelFlg("1");
                        ext.setDeletedBy(currentUid);
                        ext.setDeletedAt(now);
                        ext.setUpdatedAt(now);
                        goblinSqbGoodsExtMapper.updateById(ext);
                    }
                }
                updateCount++;
            } catch (Exception e) {
                log.error("[收钱吧更新商品同步] 异常, sqbSpuId={}", item.getSpuId(), e);
                failCount++;
            }
        }
        return ResponseDto.success(String.format("更新完成：更新 %d, 未找到 %d, 失败 %d", updateCount, notFoundCount, failCount));
    }

    private void processSkuUpdate(String currentUid, String storeId, String skuId, GoblinSqbPerfGoodsVo productsData,
            MallProductsQueryData.Sku sqbSku) {
        GoblinGoodsSkuInfoVo mgtGoodsSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(skuId);
        if (null == mgtGoodsSkuInfoVo)
            return;

        GoblinGoodsInfoVo mgtGoodsInfoVo = goblinRedisUtils.getGoodsInfoVo(mgtGoodsSkuInfoVo.getSpuId());
        if (null == mgtGoodsInfoVo)
            return;

        GoblinStoreMgtGoodsEditSkuParam editSkuParam = new GoblinStoreMgtGoodsEditSkuParam();
        editSkuParam.setStoreId(storeId);
        editSkuParam.setSpuId(mgtGoodsSkuInfoVo.getSpuId());
        editSkuParam.setSkuId(skuId);
        editSkuParam.setSkuPic(mgtGoodsSkuInfoVo.getSkuPic());
        if (!CollectionUtils.isEmpty(productsData.getConverImages())) {
            editSkuParam.setSkuPic(productsData.getConverImages().get(0));
        }

        if (sqbSku != null) {
            BigDecimal price = BigDecimal.valueOf(sqbSku.getPrice()).divide(BigDecimal.valueOf(100));
            editSkuParam.setPrice(price);
            editSkuParam.setSellPrice(price);
            editSkuParam.setPriceMember(price);
        } else {
            editSkuParam.setPrice(mgtGoodsSkuInfoVo.getPrice());
            editSkuParam.setSellPrice(mgtGoodsSkuInfoVo.getSellPrice());
            editSkuParam.setPriceMember(mgtGoodsSkuInfoVo.getPriceMember());
        }
        editSkuParam.setSkuSpecList(mgtGoodsSkuInfoVo.getSkuSpecList());
        editSkuParam.setSkuAppear("0");
        editSkuParam.setBuyFactor("0");
        editSkuParam.setSkuValidity(DateUtil.Formatter.yyyyMMddHHmmss.format(mgtGoodsSkuInfoVo.getSkuValidity()));

        // 库存增量逻辑
        /*
         * int newSqbTotal = (sqbSku != null && sqbSku.getQuantity() != null) ?
         * sqbSku.getQuantity().intValue() : 0;
         * int oldTotal = mgtGoodsSkuInfoVo.getStock() != null ?
         * mgtGoodsSkuInfoVo.getStock() : 0;
         * int operStock = newSqbTotal - oldTotal;
         * 
         * if (operStock != 0) {
         * int operStockVal = Math.abs(operStock);
         * int currentRedisSurplus = goblinRedisUtils.getSkuStock(null, skuId);
         * if (operStock < 0) {
         * if (currentRedisSurplus >= operStockVal) {
         * if (goblinRedisUtils.decrSkuStock(null, skuId, operStockVal) >= 0) {
         * editSkuParam.setStock(oldTotal - operStockVal);
         * editSkuParam.setSkuStock(mgtGoodsSkuInfoVo.getSkuStock() - operStockVal);
         * }
         * } else {
         * goblinRedisUtils.setSkuStock(null, skuId, newSqbTotal);
         * editSkuParam.setStock(newSqbTotal);
         * editSkuParam.setSkuStock(newSqbTotal);
         * }
         * } else {
         * goblinRedisUtils.incrSkuStock(null, skuId, operStockVal);
         * editSkuParam.setStock(oldTotal + operStockVal);
         * editSkuParam.setSkuStock(mgtGoodsSkuInfoVo.getSkuStock() + operStockVal);
         * }
         * } else {
         * editSkuParam.setStock(oldTotal);
         * editSkuParam.setSkuStock(mgtGoodsSkuInfoVo.getSkuStock());
         * }
         */

        goblinstoreMgtGoodsService.goodsEditSku(currentUid, editSkuParam, mgtGoodsSkuInfoVo, mgtGoodsInfoVo, Collections.emptyMap(),
                Collections.emptyMap());
    }

    private void processSkuAddition(String currentUid, String storeId, GoblinGoodsInfoVo mgtGoodsInfoVo,
            GoblinSqbPerfGoodsVo item, MallProductsQueryData.Sku sqbSku) {
        GoblinStoreMgtGoodsEditSkuParam addSkuParam = new GoblinStoreMgtGoodsEditSkuParam();
        addSkuParam.setStoreId(storeId);
        addSkuParam.setSpuId(mgtGoodsInfoVo.getSpuId());
        addSkuParam.setSkuPic(CollectionUtils.isEmpty(item.getConverImages()) ? "" : item.getConverImages().get(0));

        // 规格处理：收钱吧如果没有详细规格，使用默认规格
        List<GoblinGoodsSpecDto> specList = new ArrayList<>();
        GoblinGoodsSpecDto defaultSpec = new GoblinGoodsSpecDto();
        defaultSpec.setSpecName("默认");
        defaultSpec.setSpecVname(StringUtils.isNotBlank(sqbSku.getSkuName()) ? sqbSku.getSkuName() : "默认");
        specList.add(defaultSpec);
        addSkuParam.setSkuSpecList(specList);

        BigDecimal price = BigDecimal.valueOf(sqbSku.getPrice()).divide(BigDecimal.valueOf(100));
        addSkuParam.setPrice(price);
        addSkuParam.setSellPrice(price);
        addSkuParam.setPriceMember(price);
        addSkuParam.setStock(sqbSku.getQuantity() != null ? sqbSku.getQuantity().intValue() : 0);
        addSkuParam.setSkuStock(addSkuParam.getStock());
        addSkuParam.setSkuAppear("0");
        addSkuParam.setBuyFactor("0");
        addSkuParam.setSkuValidity(DateUtil.Formatter.yyyyMMddHHmmss.format(LocalDateTime.now().plusYears(10)));

        goblinstoreMgtGoodsService.goodsEditSkuAdd(currentUid, addSkuParam, mgtGoodsInfoVo);
    }

    private void processSkuDeletion(String currentUid, GoblinSqbGoodsExt ext, GoblinGoodsInfoVo mgtGoodsInfoVo) {
        GoblinGoodsSkuInfoVo delSkuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(ext.getSkuId());
        if (delSkuInfoVo != null) {
            goblinstoreMgtGoodsService.goodsEditSkuDel(currentUid, delSkuInfoVo, mgtGoodsInfoVo);
        }
    }

    private GoblinStoreMgtGoodsAddParam buildMgtGoodsAddParam(String storeId, GoblinSqbPerfGoodsVo productsData) {
        GoblinStoreMgtGoodsAddParam param = new GoblinStoreMgtGoodsAddParam();
        param.setStoreId(storeId);
        param.setName(productsData.getTitle());
        // param.setIntro(productsData.getProductIntroduction());
        param.setImageList(productsData.getConverImages());
        param.setDetails(productsData.getProductIntroduction());
        param.setSpecMode("1");
        param.setShelvesHandle("1");
        param.setVirtualFlg("1");
        // 设置默认分类
        param.setCateFid("22199125131096");
        param.setCateSid("22199125143778");
        param.setCateTid("22199125200983");

        List<GoblinStoreMgtGoodsAddSkuParam> skuParams = new ArrayList<>();
        List<MallProductsQueryData.Sku> sqbSkus = productsData.getSkuResults();
        if (!CollectionUtils.isEmpty(sqbSkus)) {
            for (MallProductsQueryData.Sku sqbSku : sqbSkus) {
                skuParams.add(buildMgtSkuParam(sqbSku, productsData.getConverImages()));
            }
        }
        param.setSkuParamList(skuParams);
        return param;
    }

    private GoblinStoreMgtGoodsAddSkuParam buildMgtSkuParam(MallProductsQueryData.Sku sqbSku,
            List<String> images) {
        GoblinStoreMgtGoodsAddSkuParam sku = new GoblinStoreMgtGoodsAddSkuParam();
        sku.setSkuPic(!CollectionUtils.isEmpty(images) ? images.get(0) : "");
        List<GoblinGoodsSpecDto> specList = new ArrayList<>();
        GoblinGoodsSpecDto defaultSpec = new GoblinGoodsSpecDto();
        defaultSpec.setSpecName("默认");
        defaultSpec.setSpecVname(StringUtils.isNotBlank(sqbSku.getSkuName()) ? sqbSku.getSkuName() : "默认");
        specList.add(defaultSpec);
        sku.setSkuSpecList(specList);
        BigDecimal price = BigDecimal.valueOf(sqbSku.getPrice()).divide(BigDecimal.valueOf(100));
        sku.setPrice(price);
        sku.setSellPrice(price);
        sku.setStock(sqbSku.getQuantity() != null ? sqbSku.getQuantity().intValue() : 999);
        sku.setSkuValidity(DateUtil.Formatter.yyyyMMddHHmmss.format(LocalDateTime.now().plusYears(1)));
        sku.setSkuAppear("0");
        sku.setBuyFactor("0");
        sku.setSkuNo(sqbSku.getSkuId());
        return sku;
    }

    @Override
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> getPerfGoods(String performancesId) {
        // 1. 获取演出级全局配置
        GoblinSqbPerformanceConfig config = goblinSqbPerformanceConfigMapper.selectOne(
                new LambdaQueryWrapper<GoblinSqbPerformanceConfig>()
                        .eq(GoblinSqbPerformanceConfig::getPerformancesId, performancesId));

        // 2. 如果开启了自动下架，检查演出状态
        if (config != null && Integer.valueOf(1).equals(config.getAutoOffline())) {
            // 通过 Mongo 营销活动或者 Redis 查询演出详情判断是否结束
            if (isPerformanceEnded(performancesId)) {
                log.info("[收钱吧] 演出已结束，且开启了自动下架，返回空列表, performancesId={}", performancesId);
                return ResponseDto.success(new ArrayList<>());
            }
        }

        List<GoblinSqbPerfGoodsVo> cached = goblinSqbRedisUtils.getPerfGoods(performancesId);
        if (cached != null)
            return ResponseDto.success(cached);
        try {
            LambdaQueryWrapper<GoblinSqbPerformanceGoods> query = new LambdaQueryWrapper<>();
            query.eq(GoblinSqbPerformanceGoods::getPerformancesId, performancesId)
                    .eq(GoblinSqbPerformanceGoods::getStatus, 1).orderByAsc(GoblinSqbPerformanceGoods::getSort);
            List<GoblinSqbPerformanceGoods> relations = goblinSqbPerformanceGoodsMapper.selectList(query);
            if (CollectionUtils.isEmpty(relations)) {
                List<GoblinSqbPerfGoodsVo> empty = new ArrayList<>();
                goblinSqbRedisUtils.setPerfGoods(performancesId, empty);
                return ResponseDto.success(empty);
            }
            List<String> skuIds = relations.stream().map(GoblinSqbPerformanceGoods::getSkuId)
                    .collect(Collectors.toList());
            List<String> spuIds = relations.stream().map(GoblinSqbPerformanceGoods::getSpuId).distinct()
                    .collect(Collectors.toList());
            List<GoblinGoodsSku> skuList = goblinGoodsSkuMapper
                    .selectList(new LambdaQueryWrapper<GoblinGoodsSku>().in(GoblinGoodsSku::getSkuId, skuIds));
            Map<String, GoblinGoodsSku> skuMap = skuList.stream()
                    .collect(Collectors.toMap(GoblinGoodsSku::getSkuId, Function.identity(), (a, b) -> a));
            List<GoblinGoods> spuList = goblinGoodsMapper
                    .selectList(new LambdaQueryWrapper<GoblinGoods>().in(GoblinGoods::getSpuId, spuIds));
            Map<String, GoblinGoods> spuMap = spuList.stream()
                    .collect(Collectors.toMap(GoblinGoods::getSpuId, 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());
                // 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);
            }
            goblinSqbRedisUtils.setPerfGoods(performancesId, result);
            return ResponseDto.success(result);
        } catch (Exception e) {
            log.error("[收钱吧] getPerfGoods 异常", e);
            return ResponseDto.failure("查询失败");
        }
    }

    private boolean isPerformanceEnded(String performancesId) {
        try {
            // 借鉴 GoblinMongoUtils 中的逻辑，通过关联的官方营销活动状态判断演出状态
            // status: 2 表示活动结束, 7 表示停用
            List<GoblinSelfMarketingVo> marketingList = goblinMongoUtils
                    .getSelfMarketingByPerformanceId(performancesId);
            if (!CollectionUtils.isEmpty(marketingList)) {
                GoblinSelfMarketingVo marketing = marketingList.get(0);
                if (Integer.valueOf(2).equals(marketing.getStatus())
                        || Integer.valueOf(7).equals(marketing.getStatus())) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("[收钱吧] 校验演出自动下架状态异常, performancesId={}", performancesId, e);
        }
        return false;
    }

    private CommonRequest.Seller buildSeller() {
        CommonRequest.Seller seller = new CommonRequest.Seller();
        seller.setMerchantId(shouqianbaProperties.getMerchantId());
        seller.setMerchantUserId(shouqianbaProperties.getMerchantUserId());
        seller.setRole(shouqianbaProperties.getRole());
        return seller;
    }

    private GoblinSqbGoodsExt buildExt(String spuId, String skuId, String mallSn, String mallSignature, String sqbSpuId,
            String sqbSkuId, LocalDateTime now) {
        GoblinSqbGoodsExt ext = new GoblinSqbGoodsExt();
        ext.setSpuId(spuId);
        ext.setSkuId(skuId);
        ext.setMallSn(mallSn);
        ext.setSignature(mallSignature);
        ext.setSqbSpuId(sqbSpuId);
        ext.setSqbSkuId(sqbSkuId);
        ext.setDelFlg("0");
        ext.setCreatedAt(now);
        ext.setUpdatedAt(now);
        return ext;
    }
}
