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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liquidnet.common.third.sqb.biz.SqbBiz;
import com.liquidnet.common.third.sqb.param.request.CommonRequest;
import com.liquidnet.common.third.sqb.param.request.MallListQueryRequest;
import com.liquidnet.common.third.sqb.param.request.MallProductsQueryRequest;
import com.liquidnet.common.third.sqb.util.SqbAmountUtils;
import com.liquidnet.common.third.sqb.param.response.data.MallListQueryData;
import com.liquidnet.common.third.sqb.param.response.data.MallProductsQueryData;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.goblin.dto.GoblinGoodsSpecDto;
import com.liquidnet.service.goblin.dto.manage.GoblinStoreMgtGoodsSqbAddParam;
import com.liquidnet.service.goblin.dto.manage.vo.GoblinMgtCategorySpecVo;
import com.liquidnet.service.goblin.dto.vo.*;
import com.liquidnet.service.goblin.entity.GoblinSqbGoodsExt;
import com.liquidnet.service.goblin.entity.GoblinSqbMallInfo;
import com.liquidnet.service.goblin.mapper.GoblinSqbGoodsExtMapper;
import com.liquidnet.service.goblin.mapper.GoblinSqbMallInfoMapper;
import com.liquidnet.service.goblin.service.manage.IGoblinStoreMgtSqbGoodsService;
import com.liquidnet.service.goblin.util.GoblinMongoUtils;
import com.liquidnet.service.goblin.util.GoblinRedisUtils;
import com.liquidnet.service.goblin.util.QueueUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 商品管理:收钱吧商品服务实现
 */
@Slf4j
@Service
public class GoblinStoreMgtSqbGoodsServiceImpl implements IGoblinStoreMgtSqbGoodsService {

    @Autowired
    QueueUtils queueUtils;
    @Autowired
    GoblinRedisUtils goblinRedisUtils;
    @Autowired
    GoblinMongoUtils goblinMongoUtils;
    @Autowired
    GoblinSqbGoodsExtMapper goblinSqbGoodsExtMapper;
    @Autowired
    private SqbBiz goblinShouQianBaService;
    @Autowired
    private GoblinSqbMallInfoMapper goblinSqbMallInfoMapper;


    @Override
    public ResponseDto<List<GoblinSqbPerfGoodsVo>> getProductList() {
        try {
            List<GoblinSqbPerfGoodsVo> result = new ArrayList<>();

            // 从mysql查询配置的店铺信息（收钱吧只有一个环境，所以通过数据库配置来获取店铺）
            List<GoblinSqbMallInfo> mallList = goblinSqbMallInfoMapper.selectList(new QueryWrapper<GoblinSqbMallInfo>()
                    .lambda()
                    .eq(GoblinSqbMallInfo::getStatus, 1));
//            List<MallListQueryData> mallList = fetchAllMalls();
            if (CollectionUtils.isEmpty(mallList)) {
                return ResponseDto.success(new ArrayList<>());
            }

            // 获取本地已同步的商品 SPU 映射，用于标记同步状态
            List<String> mallSns = mallList.stream().map(GoblinSqbMallInfo::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 (GoblinSqbMallInfo 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(GoblinSqbMallInfo 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(goblinShouQianBaService.getSqbConfig().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(GoblinSqbMallInfo mall) {
        MallProductsQueryRequest productRequest = new MallProductsQueryRequest();
        productRequest.setAppid(goblinShouQianBaService.getSqbConfig().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);
    }
    private CommonRequest.Seller buildSeller() {
        CommonRequest.Seller seller = new CommonRequest.Seller();
        seller.setMerchantId(goblinShouQianBaService.getSqbConfig().getMerchantId());
        seller.setMerchantUserId(goblinShouQianBaService.getSqbConfig().getMerchantUserId());
        seller.setRole(goblinShouQianBaService.getSqbConfig().getRole());
        return seller;
    }

    public void sqbGoodsAdd(GoblinGoodsInfoVo goodsInfoVo, List<GoblinGoodsSkuInfoVo> goodsSkuInfoVoList) {
        goblinMongoUtils.setGoodsInfoVo(goodsInfoVo);
        goblinMongoUtils.setGoodsSkuInfoVos(goodsSkuInfoVoList);

        String createdBy = goodsInfoVo.getCreatedBy();
        LocalDateTime createdAt = goodsInfoVo.getCreatedAt();
        String spuId = goodsInfoVo.getSpuId();

        LinkedList<Object[]> initGoodsSkuObjs = CollectionUtil.linkedListObjectArr();
        LinkedList<Object[]> initGoodsSkuSpecValueObjs = CollectionUtil.linkedListObjectArr();
        LinkedList<Object[]> initGoodsCategorySpecObjs = CollectionUtil.linkedListObjectArr();
        {// 分类规格记录
            String cateFid = goodsInfoVo.getCateFid(), cateSid = goodsInfoVo.getCateSid(),
                    cateTid = goodsInfoVo.getCateTid();
            String filterCateId = StringUtils.isBlank(cateTid) ? (StringUtils.isBlank(cateSid) ? cateFid : cateSid)
                    : cateTid;
            GoblinMgtCategorySpecVo mgtCategorySpecVoCache = goblinRedisUtils.getCategorySpec(filterCateId);// 分类绑定的规格信息
            List<String> addSpecNameList = goodsSkuInfoVoList.get(0).getSkuSpecList().stream()
                    .map(GoblinGoodsSpecDto::getSpecName).collect(Collectors.toList());
            if (null == mgtCategorySpecVoCache) {// 根据分类ID未查取到规格信息，则Cache、数据库新增
                GoblinMgtCategorySpecVo initMgtCategorySpecVo = GoblinMgtCategorySpecVo.getNew().setCateId(filterCateId)
                        .setSpecNameList(addSpecNameList);
                goblinMongoUtils.setCategorySpecVo(initMgtCategorySpecVo);
                goblinRedisUtils.setCategorySpec(filterCateId, initMgtCategorySpecVo);
                addSpecNameList.forEach(r -> initGoodsCategorySpecObjs.add(new Object[] { filterCateId, r }));
            } else {// 根据分类ID查取到规格信息，则进一步比对判断是否新增
                List<String> confirmAddSpecNameList = addSpecNameList.stream()
                        .filter(r -> !mgtCategorySpecVoCache.getSpecNameList().contains(r))
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(confirmAddSpecNameList)) {// 不存在于`mgtCategorySpecVoCache`的，则更新Cache，数据库新增
                    mgtCategorySpecVoCache.getSpecNameList().addAll(confirmAddSpecNameList);
                    goblinMongoUtils.updateCategorySpecVo(mgtCategorySpecVoCache);
                    goblinRedisUtils.setCategorySpec(filterCateId, mgtCategorySpecVoCache);
                    confirmAddSpecNameList
                            .forEach(r -> initGoodsCategorySpecObjs.add(new Object[] { filterCateId, r }));
                }
            }
        }

        int skuSize = goodsSkuInfoVoList.size();
        for (int i = 0; i < skuSize; i++) {
            GoblinGoodsSkuInfoVo skuInfoVo = goodsSkuInfoVoList.get(i);
            String skuId = skuInfoVo.getSkuId();
            String buyRoster = skuInfoVo.getBuyRoster();

            goblinRedisUtils.setSkuStock(null, skuId, skuInfoVo.getSkuStock());

            initGoodsSkuObjs.add(new Object[] {
                    skuId, skuInfoVo.getSpuId(), skuInfoVo.getSkuNo(), skuInfoVo.getSkuBarCode(),
                    skuInfoVo.getSkuErpCode(),
                    skuInfoVo.getErpType(), skuInfoVo.getErpHosting(), skuInfoVo.getErpWarehouseNo(),
                    skuInfoVo.getSkuType(), skuInfoVo.getName(),
                    skuInfoVo.getSubtitle(), skuInfoVo.getSellPrice(), skuInfoVo.getSkuPic(), skuInfoVo.getSkuIsbn(),
                    skuInfoVo.getStock(),
                    skuInfoVo.getSkuStock(), skuInfoVo.getWarningStock(), skuInfoVo.getPrice(),
                    skuInfoVo.getPriceMember(), skuInfoVo.getWeight(),
                    skuInfoVo.getBuyFactor(), buyRoster, skuInfoVo.getBuyLimit(), skuInfoVo.getStoreId(),
                    skuInfoVo.getSkuValidity(),
                    skuInfoVo.getVirtualFlg(), skuInfoVo.getStatus(), skuInfoVo.getShelvesStatus(),
                    skuInfoVo.getSkuAppear(), skuInfoVo.getShelvesAt(),
                    createdBy, createdAt, skuInfoVo.getLogisticsTemplate()
            });

            skuInfoVo.getSkuSpecList().forEach(skuSpecDto -> initGoodsSkuSpecValueObjs.add(new Object[] {
                    spuId, skuId, skuSpecDto.getSpecName(), skuSpecDto.getSpecVname()
            }));
        }

        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        toMqSqls.add(SqlMapping.get("goblin_goods.insert_for_coupon"));
        LinkedList<Object[]> initGoodsObjs = CollectionUtil.linkedListObjectArr();
        initGoodsObjs.add(new Object[] {
                spuId, goodsInfoVo.getSpuNo(), goodsInfoVo.getSpuBarCode(), goodsInfoVo.getSpuErpCode(),
                goodsInfoVo.getErpType(), goodsInfoVo.getSpuType(),
                goodsInfoVo.getName(), goodsInfoVo.getSubtitle(), goodsInfoVo.getSellPrice(), goodsInfoVo.getPriceGe(),
                goodsInfoVo.getPriceLe(),
                goodsInfoVo.getIntro(), goodsInfoVo.getDetails(), goodsInfoVo.getCoverPic(), goodsInfoVo.getVideo(),
                goodsInfoVo.getSpecMode(),
                goodsInfoVo.getStoreId(), goodsInfoVo.getCateFid(), goodsInfoVo.getCateSid(), goodsInfoVo.getCateTid(),
                goodsInfoVo.getStoreCateFid(),
                goodsInfoVo.getStoreCateSid(), goodsInfoVo.getStoreCateTid(), goodsInfoVo.getBrandId(),
                goodsInfoVo.getShelvesHandle(), goodsInfoVo.getShelvesTime(),
                goodsInfoVo.getSpuValidity(), goodsInfoVo.getVirtualFlg(), goodsInfoVo.getStatus(),
                goodsInfoVo.getShelvesStatus(), goodsInfoVo.getSpuAppear(),
                goodsInfoVo.getShelvesAt(), createdBy, createdAt, goodsInfoVo.getLogisticsTemplate()
        });
        toMqSqls.add(SqlMapping.get("goblin_goods_sku.insert_for_coupon"));
        toMqSqls.add(SqlMapping.get("goblin_goods_image.insert_byreplace"));
        LinkedList<Object[]> initGoodsImageObjs = CollectionUtil.linkedListObjectArr();
        if (!CollectionUtils.isEmpty(goodsInfoVo.getImageList())) {
            goodsInfoVo.getImageList().forEach(imageUrl -> initGoodsImageObjs.add(new Object[] { spuId, imageUrl }));
        }
        toMqSqls.add(SqlMapping.get("goblin_goods_tag.insert_byreplace"));
        LinkedList<Object[]> initGoodsTagObjs = CollectionUtil.linkedListObjectArr();
        if (!CollectionUtils.isEmpty(goodsInfoVo.getTagVoList())) {
            goodsInfoVo.getTagVoList().forEach(
                    tagVo -> initGoodsTagObjs.add(new Object[] { spuId, tagVo.getTagId(), tagVo.getSort(), "0" }));
        }
        if (!CollectionUtils.isEmpty(goodsInfoVo.getExtagVoList())) {
            goodsInfoVo.getExtagVoList().forEach(exTagVo -> initGoodsTagObjs
                    .add(new Object[] { spuId, exTagVo.getTagId(), exTagVo.getSort(), "1" }));
        }
        toMqSqls.add(SqlMapping.get("goblin_goods_artag.insert_byreplace"));
        LinkedList<Object[]> initGoodsArTagObjs = CollectionUtil.linkedListObjectArr();
        if (!CollectionUtils.isEmpty(goodsInfoVo.getArtagVoList())) {
            goodsInfoVo.getArtagVoList().forEach(arTagVo -> initGoodsArTagObjs
                    .add(new Object[] { spuId, arTagVo.getTagId(), arTagVo.getSort(), "1" }));
        }
        toMqSqls.add(SqlMapping.get("goblin_goods_service_support.insert_byreplace"));
        LinkedList<Object[]> initGoodsServiceSupportObjs = CollectionUtil.linkedListObjectArr();
        if (!CollectionUtils.isEmpty(goodsInfoVo.getServiceSupportVoList())) {
            goodsInfoVo.getServiceSupportVoList()
                    .forEach(ssvo -> initGoodsServiceSupportObjs.add(new Object[] { spuId, ssvo.getSsid() }));
        }
        toMqSqls.add(SqlMapping.get("goblin_goods_spec.insert_byreplace"));
        LinkedList<Object[]> initGoodsSpecObjs = CollectionUtil.linkedListObjectArr();
        toMqSqls.add(SqlMapping.get("goblin_goods_spec_value.insert_byreplace"));
        LinkedList<Object[]> initGoodsSpecValueObjs = CollectionUtil.linkedListObjectArr();
        toMqSqls.add(SqlMapping.get("goblin_goods_spu_spec_value.insert_byreplace"));// SPU规格信息
        LinkedList<Object[]> initGoodsSpuSpecValueObjs = CollectionUtil.linkedListObjectArr();
        toMqSqls.add(SqlMapping.get("goblin_goods_sku_spec_value.insert_byreplace"));// SKU规格信息
        {// 规格记录
            List<GoblinGoodsSpecVo> specVoList = goodsInfoVo.getSpecVoList();
            specVoList.forEach(s -> {
                initGoodsSpecObjs.add(new Object[] { s.getSpecName(), createdAt });
                s.getSpecValues().forEach(sv -> {
                    initGoodsSpecValueObjs.add(new Object[] { s.getSpecName(), sv.getSpecVname(), createdAt });
                    initGoodsSpuSpecValueObjs
                            .add(new Object[] { spuId, s.getSpecName(), sv.getSpecVname(), sv.getSpecVsort() });
                });
            });
        }
        toMqSqls.add(SqlMapping.get("goblin_goods_category_spec.insert_byreplace"));// 分类关联规格信息

        queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_GOODS.getKey(),
                SqlMapping.gets(toMqSqls, initGoodsObjs, initGoodsSkuObjs,
                        initGoodsImageObjs, initGoodsTagObjs, initGoodsArTagObjs, initGoodsServiceSupportObjs,
                        initGoodsSpecObjs,
                        initGoodsSpecValueObjs, initGoodsSpuSpecValueObjs, initGoodsSkuSpecValueObjs,
                        initGoodsCategorySpecObjs));
    }

    public boolean sqbGoodsEditSpu(String uid, GoblinSqbPerfGoodsVo mgtGoodsAddParam,
            GoblinGoodsInfoVo mgtGoodsInfoVo) {
        String spuId = mgtGoodsInfoVo.getSpuId();
        GoblinStoreMgtGoodsSqbAddParam initParam = new GoblinStoreMgtGoodsSqbAddParam();

        GoblinGoodsInfoVo updateSpuInfoVo = initParam.initEditGoodsInfoVo(mgtGoodsAddParam, mgtGoodsInfoVo);

        boolean updateImageFlg = false;
        List<String> paramImageList = mgtGoodsAddParam.getConverImages();
        List<String> befImageList = mgtGoodsInfoVo.getImageList();
        {// 图片处理
            if (befImageList.size() != paramImageList.size()) {
                updateImageFlg = true;
            } else {
                for (String imageUrl : paramImageList) {
                    if (!befImageList.contains(imageUrl)) {
                        updateImageFlg = true;
                        break;
                    }
                }
            }
            if (updateImageFlg) {
                updateSpuInfoVo.setImageList(paramImageList);
            }
        }
        updateSpuInfoVo.setUpdatedBy(uid);
        updateSpuInfoVo.setUpdatedAt(LocalDateTime.now());
        if (goblinMongoUtils.updateGoodsInfoVo(updateSpuInfoVo)) {
            goblinRedisUtils.delGoodsInfoVo(updateSpuInfoVo.getSpuId());
            log.info("商品管理:SPU编辑[UID={},PARAMS={}]", uid, JsonUtils.toJson(mgtGoodsAddParam));

            LinkedList<Object[]> updateGoodsInfoObjs = CollectionUtil.linkedListObjectArr();

            LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
            toMqSqls.add(SqlMapping.get("goblin_goods.update_by_edit"));
            updateGoodsInfoObjs.add(new Object[] {
                    updateSpuInfoVo.getSpuNo(), updateSpuInfoVo.getName(), updateSpuInfoVo.getSubtitle(),
                    updateSpuInfoVo.getSellPrice(),
                    updateSpuInfoVo.getIntro(), updateSpuInfoVo.getDetails(), updateSpuInfoVo.getCoverPic(),
                    updateSpuInfoVo.getVideo(),
                    updateSpuInfoVo.getSpecMode(), updateSpuInfoVo.getCateFid(), updateSpuInfoVo.getCateSid(),
                    updateSpuInfoVo.getCateTid(),
                    updateSpuInfoVo.getShelvesHandle(), updateSpuInfoVo.getShelvesTime(),
                    updateSpuInfoVo.getSpuValidity(), updateSpuInfoVo.getVirtualFlg(),
                    updateSpuInfoVo.getLogisticsTemplate(), updateSpuInfoVo.getUpdatedBy(),
                    updateSpuInfoVo.getUpdatedAt(), updateSpuInfoVo.getSpuErpCode(),
                    updateSpuInfoVo.getSpuId()
            });

            toMqSqls.add(SqlMapping.get("goblin_goods_image.delete"));
            LinkedList<Object[]> deleteGoodsImageObjs = CollectionUtil.linkedListObjectArr();
            toMqSqls.add(SqlMapping.get("goblin_goods_image.insert_byreplace"));
            LinkedList<Object[]> initGoodsImageObjs = CollectionUtil.linkedListObjectArr();
            if (updateImageFlg) {
                deleteGoodsImageObjs.add(new Object[] { spuId });
                updateSpuInfoVo.getImageList()
                        .forEach(imageUrl -> initGoodsImageObjs.add(new Object[] { spuId, imageUrl }));
            }

            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_GOODS.getKey(),
                    SqlMapping.gets(toMqSqls, updateGoodsInfoObjs, deleteGoodsImageObjs,
                            initGoodsImageObjs));

            this.sqbGoodsEditSku(uid, mgtGoodsAddParam, mgtGoodsInfoVo);
            return true;
        }
        return false;
    }

    @Override
    public GoblinSqbPerfGoodsVo fetchSqbGoodsByMallAndSpu(String mallSn, String sqbSpuId, String signature) {
        if (StringUtils.isBlank(mallSn) || StringUtils.isBlank(sqbSpuId) || StringUtils.isBlank(signature)) {
            return null;
        }
        List<MallProductsQueryData> products = goblinShouQianBaService.queryMallProducts(mallSn, signature);
        if (CollectionUtils.isEmpty(products)) {
            return null;
        }
        for (MallProductsQueryData product : products) {
            if (sqbSpuId.equals(product.getSpuId())) {
                GoblinSqbPerfGoodsVo vo = new GoblinSqbPerfGoodsVo();
                vo.setMallSn(mallSn);
                vo.setSignature(signature);
                vo.setSpuId(product.getSpuId());
                vo.setConverImages(product.getConverImages());
                vo.setProductIntroduction(product.getProductIntroduction());
                vo.setTitle(product.getTitle());
                vo.setSkuResults(product.getSkuResults());
                return vo;
            }
        }
        return null;
    }


    public boolean sqbGoodsEditSku(String uid, GoblinSqbPerfGoodsVo mgtGoodsAddParam,
            GoblinGoodsInfoVo goodsInfoVo) {
        LocalDateTime nowTime = LocalDateTime.now();
        List<MallProductsQueryData.Sku> skuResults = mgtGoodsAddParam.getSkuResults();
        if (goodsInfoVo == null || CollectionUtils.isEmpty(goodsInfoVo.getSkuIdList()) || CollectionUtils.isEmpty(skuResults)) {
            return false;
        }

        LambdaQueryWrapper<GoblinSqbGoodsExt> wrapper = new LambdaQueryWrapper<GoblinSqbGoodsExt>()
                .eq(GoblinSqbGoodsExt::getSpuId, goodsInfoVo.getSpuId())
                .eq(GoblinSqbGoodsExt::getDelFlg, "0");
        if (StringUtils.isNotBlank(mgtGoodsAddParam.getMallSn())) {
            wrapper.eq(GoblinSqbGoodsExt::getMallSn, mgtGoodsAddParam.getMallSn());
        }
        List<GoblinSqbGoodsExt> extList = goblinSqbGoodsExtMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(extList)) {
            return false;
        }

        Map<String, String> sqbSkuToLocalSkuMap = extList.stream()
                .filter(ext -> StringUtils.isNotBlank(ext.getSqbSkuId()) && StringUtils.isNotBlank(ext.getSkuId()))
                .collect(Collectors.toMap(GoblinSqbGoodsExt::getSqbSkuId, GoblinSqbGoodsExt::getSkuId, (a, b) -> a));

        boolean updated = false;
        LinkedList<Object[]> updateGoodsSkuObjs = CollectionUtil.linkedListObjectArr();
        for (MallProductsQueryData.Sku sqbSku : skuResults) {
            if (sqbSku == null || StringUtils.isBlank(sqbSku.getSkuId())) {
                continue;
            }
            String localSkuId = sqbSkuToLocalSkuMap.get(sqbSku.getSkuId());
            if (StringUtils.isBlank(localSkuId)) {
                continue;
            }

            GoblinGoodsSkuInfoVo skuInfoVo = goblinRedisUtils.getGoodsSkuInfoVo(localSkuId);
            if (skuInfoVo == null || !"0".equals(skuInfoVo.getDelFlg())) {
                continue;
            }
            skuInfoVo.setName(sqbSku.getSkuName());
            if (sqbSku.getPrice() != null) {
                skuInfoVo.setPrice(SqbAmountUtils.fenToYuan(sqbSku.getPrice()));
                skuInfoVo.setPriceMember(SqbAmountUtils.fenToYuan(sqbSku.getPrice()));
            }
            skuInfoVo.setUpdatedBy(uid);
            skuInfoVo.setUpdatedAt(nowTime);
            if (goblinMongoUtils.updateGoodsSkuInfoVo(skuInfoVo)) {
                goblinRedisUtils.delGoodsSkuInfoVo(localSkuId);
                updateGoodsSkuObjs.add(new Object[] {
                        sqbSku.getSkuName(), skuInfoVo.getPrice(), skuInfoVo.getPriceMember(), skuInfoVo.getStock(),
                        skuInfoVo.getSkuStock(),
                        skuInfoVo.getBuyLimit(), skuInfoVo.getUpdatedBy(), skuInfoVo.getUpdatedAt(), localSkuId
                });
                updated = true;
            }
        }
        if (updated) {
            LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
            toMqSqls.add(SqlMapping.get("goblin_goods_sku.update_by_edit_for_sqb"));
            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_GOODS.getKey(),
                    SqlMapping.gets(toMqSqls, updateGoodsSkuObjs));
        }
        return updated;
    }

}
