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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
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.mapper.GoblinSqbGoodsExtMapper;
import com.liquidnet.service.goblin.param.shouqianba.response.data.MallProductsQueryData;
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.ObjectUtil;
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;

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


    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(BigDecimal.valueOf(sqbSku.getPrice()));
                skuInfoVo.setPriceMember(BigDecimal.valueOf(sqbSku.getPrice()));
            }
            skuInfoVo.setUpdatedBy(uid);
            skuInfoVo.setUpdatedAt(nowTime);
            if (goblinMongoUtils.updateGoodsSkuInfoVo(skuInfoVo)) {
                goblinRedisUtils.delGoodsSkuInfoVo(localSkuId);
                updateGoodsSkuObjs.add(new Object[] {
                        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_coupon"));
            queueUtils.sendMsgByRedis(MQConst.GoblinQueue.SQL_GOODS.getKey(),
                    SqlMapping.gets(toMqSqls, updateGoodsSkuObjs));
        }
        return updated;
    }

}
