package com.hzs.sale.wares.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.sale.classify.BdSpecs;
import com.hzs.common.domain.sale.ext.BdWaresExt;
import com.hzs.common.domain.sale.ext.BdWaresSpecsRelationExt;
import com.hzs.common.domain.sale.ext.BdWaresSpecsSkuExt;
import com.hzs.common.domain.sale.wares.*;
import com.hzs.common.domain.sale.wares.ext.WaresGradeAwards;
import com.hzs.common.domain.system.config.BdAgreement;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.domain.system.config.BdLabel;
import com.hzs.common.domain.system.config.BdMenuDetail;
import com.hzs.common.domain.system.config.ext.BdRangeExt;
import com.hzs.member.base.IMemberServiceApi;

import com.hzs.sale.index.controller.param.IndexWaresParam;
import com.hzs.sale.product.service.IBdSpecsService;
import com.hzs.sale.wares.param.*;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.sale.wares.param.WaresDetailParams;
import com.hzs.sale.wares.mapper.BdWaresMapper;
import com.hzs.sale.wares.service.*;
import com.hzs.sale.wares.vo.*;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.ITransactionServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.ILabelServiceApi;
import com.hzs.system.config.IRangeServiceApi;
import com.hzs.system.config.dto.LabelConfigDTO;
import com.hzs.system.sys.IMenuDetailServiceApi;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 商品 服务实现类
 */
@Service
public class BdWaresServiceImpl extends ServiceImpl<BdWaresMapper, BdWares> implements IBdWaresService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IBdSpecsService iBdSpecsService;
    @Autowired
    private IBdWaresAuthorizeService iBdWaresAuthorizeService;
    @Autowired
    private IBdWaresAwardsService iBdWaresAwardsService;
    @Autowired
    private IBdWaresGradeService iBdWaresGradeService;
    @Autowired
    private IBdWaresSpecsRelationService iBdWaresSpecsRelationService;
    @Autowired
    private IBdWaresSpecsPackService iBdWaresSpecsPackService;
    @Autowired
    private IBdWaresSpecsSkuService iBdWaresSpecsSkuService;
    @Autowired
    private IBdWaresSpecsService iBdWaresSpecsService;
    @Autowired
    private IBdWaresExtendService iBdWaresExtendService;
    @Autowired
    private IBdWaresRangeService iBdWaresRangeService;
    @Autowired
    private IBdWaresDetailService iBdWaresDetailService;
    @Autowired
    private IBdWaresLabelService iBdWaresLabelService;
    @Autowired
    private IBdWaresAuthorityService iBdWaresAuthorityService;

    @DubboReference
    ILabelServiceApi iLabelServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IMenuDetailServiceApi iMenuDetailServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    IRangeServiceApi iRangeServiceApi;
    @DubboReference
    ITransactionServiceApi iTransactionServiceApi;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BdWares saveWares(WaresParams waresParams, LoginUser user) {
        // 设置 wares 对象的值
        BdWares wares = BeanUtil.copyProperties(waresParams, BdWares.class);
        wares.setPkId(waresParams.getWaresId());
        R<Integer> transaction = iTransactionServiceApi.createTransaction(user.getDataCountry(), ETransactionKey.SPEC, waresParams.getWaresName(), EYesNo.NO, EYesNo.NO);
        wares.setWaresCode(waresParams.getWaresCode());
        wares.setPkTransaction(transaction.getData());
        wares.setPkCreator(user.getUserId());
        wares.setPkCountry(user.getDataCountry());
        wares.setDelFlag(EDelFlag.UN_DELETE.getValue());
        if (waresParams.getIsPutOn().equals(EYesNo.YES.getIntValue())) {
            wares.setListingTime(DateUtils.currentDateTime());
        }
        if (waresParams.getIsPutOn().equals(EYesNo.NO.getIntValue())) {
            wares.setRemovalTime(DateUtils.currentDateTime());
        }
        this.save(wares);
        // 商品拓展表
        BdWaresExtend waresExtend = BeanUtil.copyProperties(waresParams, BdWaresExtend.class);
        // 存入要转化美金
        if (!waresParams.getSpecialArea().equals(ESpecialArea.REPURCHASE_AREA.getValue())) {
            waresParams.setMakerIncome(BigDecimal.ZERO);
        }
        if (null != waresParams.getMakerIncome()) {
            R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(user.getDataCountry());
            waresExtend.setMakerIncome(waresParams.getMakerIncome().divide(currencyDto.getData().getInExchangeRate(), 6, BigDecimal.ROUND_HALF_UP));
        }
        waresExtend.setSystemType(ESystemType.DEFAULT.getValue());
        waresExtend.setPkWares(wares.getPkId());
        waresExtend.setPkCreator(user.getUserId());
        waresExtend.setCreationTime(DateUtils.currentDateTime());
        waresExtend.setPkCountry(user.getDataCountry());
        // 前缀标签
        BdLabel prefixLabel = null;
        if (waresParams.getPkPrefixLabel() != null) {
            prefixLabel = getBdLabel(waresParams.getPkPrefixLabel());
            if (prefixLabel != null) {
                waresExtend.setPrefixLabel(prefixLabel.getLabel());
            }
        }
        // 炫酷标签
        BdLabel coolLabel = null;
        if (waresParams.getPkCoolLabel() != null) {
            coolLabel = getBdLabel(waresParams.getPkCoolLabel());
            if (coolLabel != null) {
                waresExtend.setCoolLabel(coolLabel.getLabel());
            }
        }
        iBdWaresExtendService.save(waresExtend);
        // 标签关联记录
        saveWaresLabel(wares, prefixLabel, coolLabel, waresParams.getPkGuaranteeLabel(), waresParams.getPkSellingPoint(), user);

        // 生成产品明细
        saveWaresDetail(wares, waresParams.getWaresDetailList(), user);
        // 生成规格sku 表
        saveWaresSpecsSku(wares, waresParams.getWaresSpecsSkuList(), user);
        // 团队配置
        saveWaresAuthority(wares, waresParams.getWaresAuthorityList(), user);
        // 生成 极差配置
        saveWaresRange(wares, waresParams.getWaresRangeList(), user);

        // 产品包装新增
        if (waresParams.getWaresSpecsPackList().size() > 0) {
            saveWaresSpecsPack(wares, waresParams.getWaresSpecsPackList());
        }

        if (waresParams.getWaresGradeIds() != null) {
            List<BdWaresGrade> waresGradeList = new ArrayList<>();
            for (Integer waresGradeId : waresParams.getWaresGradeIds()) {
                BdWaresGrade bdWaresGrade = new BdWaresGrade();
                bdWaresGrade.setPkWares(wares.getPkId());
                bdWaresGrade.setPkRange(waresGradeId);
                bdWaresGrade.setCreationTime(DateUtils.currentDateTime());
                bdWaresGrade.setPkCreator(user.getUserId());
                bdWaresGrade.setPkCountry(user.getDataCountry());
                waresGradeList.add(bdWaresGrade);
            }
            if (waresGradeList.size() > 0) {
                iBdWaresGradeService.saveBatch(waresGradeList);
            }
        }
        // 奖衔
        if (waresParams.getWaresAwardsIds() != null) {
            List<BdWaresAwards> waresAwardsList = new ArrayList<>();
            for (Integer waresAwardsId : waresParams.getWaresAwardsIds()) {
                BdWaresAwards bdWaresAwards = new BdWaresAwards();
                bdWaresAwards.setPkWares(wares.getPkId());
                bdWaresAwards.setPkAwards(waresAwardsId);
                bdWaresAwards.setCreationTime(DateUtils.currentDateTime());
                bdWaresAwards.setPkCreator(user.getUserId());
                bdWaresAwards.setPkCountry(user.getDataCountry());
                waresAwardsList.add(bdWaresAwards);
            }
            iBdWaresAwardsService.saveBatch(waresAwardsList);
        }
        // 用户权限配置
        if (waresParams.getWaresMemberAuthorizeList() != null) {
            List<BdWaresAuthorize> waList = new ArrayList<>();
            for (Integer value : waresParams.getWaresMemberAuthorizeList()) {
                BdWaresAuthorize waresAuthorize = new BdWaresAuthorize();
                waresAuthorize.setPkWares(wares.getPkId());
                waresAuthorize.setValue(value);
                waresAuthorize.setCreationTime(DateUtils.currentDateTime());
                waresAuthorize.setPkCreator(user.getUserId());
                waresAuthorize.setPkCountry(user.getDataCountry());
                waList.add(waresAuthorize);
            }
            if (waList.size() > 0) {
                iBdWaresAuthorizeService.saveBatch(waList);
            }
        }
        return wares;
    }

    /**
     * 计算商品极差
     *
     * @return
     */
    private List<WaresRangeParams> computeWaresRange(List<WaresSpecsSkuParams> waresSpecsSkuList) {
        R<List<BdRangeExt>> rangeDto = iRangeServiceApi.queryRange(SecurityUtils.getPkCountry());
        List<BdRangeExt> rangeList = rangeDto.getData();
        List<WaresRangeParams> waresRangeParamsList = new ArrayList<>();
        for (WaresSpecsSkuParams waresSpecsSkuParams : waresSpecsSkuList) {
            List<ComputeWaresPrice> computeWaresPriceList = new ArrayList<>();
            ComputeWaresPrice computeWaresPrice = new ComputeWaresPrice();
            computeWaresPrice.setProductPrice(waresSpecsSkuParams.getProductPrice());
            computeWaresPrice.setProductPv(waresSpecsSkuParams.getProductAchieve());
            computeWaresPrice.setProductBv(waresSpecsSkuParams.getAssAchieve());
            computeWaresPrice.setPkProduct(waresSpecsSkuParams.getPkProduct());
            computeWaresPriceList.add(computeWaresPrice);
            List<ComputeWaresPrice> computeWaresPrices = this.computeWaresPrice(computeWaresPriceList, rangeList);
            for (ComputeWaresPrice waresPrice : computeWaresPrices) {
                for (RangePriceVo rangePriceVo : waresPrice.getRangePriceVoList()) {
                    WaresRangeParams waresRangeParams = new WaresRangeParams();
                    waresRangeParams.setPkRange(rangePriceVo.getPkRange());
                    waresRangeParams.setPkProduct(rangePriceVo.getPkProduct());
                    waresRangeParams.setPrice(rangePriceVo.getPrice());
                    waresRangeParams.setAchieve(rangePriceVo.getAchieve());
                    waresRangeParams.setAssAchieve(rangePriceVo.getAssAchieve());
                    waresRangeParams.setWaresSpecsList(waresSpecsSkuParams.getWaresSpecsList());
                    waresRangeParamsList.add(waresRangeParams);
                }
            }
        }
        return waresRangeParamsList;
    }

    /**
     * 所有标签生成记录
     *
     * @param wares
     * @param prefixLabel      前缀
     * @param coolLabel        酷炫
     * @param pkGuaranteeLabel 保证
     * @param pkSellingPoint   卖点
     */
    private void saveWaresLabel(BdWares wares, BdLabel prefixLabel, BdLabel coolLabel, List<Integer> pkGuaranteeLabel, List<Integer> pkSellingPoint, LoginUser user) {
        List<BdWaresLabel> list = new ArrayList<>();
        // 前缀标签
        if (prefixLabel != null) {
            BdWaresLabel prefixWaresLabel = new BdWaresLabel();
            prefixWaresLabel.setCreationTime(new Date());
            prefixWaresLabel.setPkCountry(user.getDataCountry());
            prefixWaresLabel.setPkCreator(user.getUserId());
            prefixWaresLabel.setPkWares(wares.getPkId());
            prefixWaresLabel.setLabelType(prefixLabel.getLabelType());
            prefixWaresLabel.setPkLable(prefixLabel.getPkId());
            list.add(prefixWaresLabel);
        }
        if (coolLabel != null) {
            // 酷炫标签
            BdWaresLabel coolWaresLabel = new BdWaresLabel();
            coolWaresLabel.setCreationTime(new Date());
            coolWaresLabel.setPkCountry(user.getDataCountry());
            coolWaresLabel.setPkCreator(user.getUserId());
            coolWaresLabel.setPkWares(wares.getPkId());
            coolWaresLabel.setLabelType(coolLabel.getLabelType());
            coolWaresLabel.setPkLable(coolLabel.getPkId());
            list.add(coolWaresLabel);
        }

        // 保证
        for (Integer integer : pkGuaranteeLabel) {
            BdLabel label = getBdLabel(integer);
            if (StringUtils.isNotNull(label.getPkId())) {
                BdWaresLabel guaranteeLabel = new BdWaresLabel();
                guaranteeLabel.setCreationTime(new Date());
                guaranteeLabel.setPkCountry(user.getDataCountry());
                guaranteeLabel.setPkCreator(user.getUserId());
                guaranteeLabel.setPkWares(wares.getPkId());
                guaranteeLabel.setLabelType(label.getLabelType());
                guaranteeLabel.setPkLable(label.getPkId());
                list.add(guaranteeLabel);
            }
        }
        // 卖点
        for (Integer integer : pkSellingPoint) {
            BdLabel label = getBdLabel(integer);
            if (StringUtils.isNotNull(label.getPkId())) {
                BdWaresLabel sellingLabel = new BdWaresLabel();
                sellingLabel.setCreationTime(new Date());
                sellingLabel.setPkCountry(user.getDataCountry());
                sellingLabel.setPkCreator(user.getUserId());
                sellingLabel.setPkWares(wares.getPkId());
                sellingLabel.setLabelType(label.getLabelType());
                sellingLabel.setPkLable(label.getPkId());
                list.add(sellingLabel);
            }
        }
        iBdWaresLabelService.saveBatch(list);
    }

    /**
     * 生成商品极差明细表
     *
     * @param wares
     * @param waresRangeList
     */
    private void saveWaresRange(BdWares wares, List<WaresRangeParams> waresRangeList, LoginUser user) {
        // 批量添加
        List<BdWaresRange> wrList = new ArrayList<>();
        if (waresRangeList != null && waresRangeList.size() > 0) {
            for (WaresRangeParams waresRangeParams : waresRangeList) {
                Integer pkWaresSpecsSku = null;
                // 查询sku 表中存在相同规格明细 并且相同详情外键的
                List<BdWaresSpecs> waresSpecsList = waresRangeParams.getWaresSpecsList();
                //取得所有规格值
                List<Integer> specsList = waresSpecsList.stream().map(BdWaresSpecs::getPkSpecs).collect(Collectors.toList());

                LambdaQueryWrapper<BdWaresDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BdWaresDetail::getPkWares, wares.getPkId());
                queryWrapper.eq(BdWaresDetail::getPkProduct, waresRangeParams.getPkProduct());
                if (waresRangeParams.getIsGift() != null) {
                    queryWrapper.eq(BdWaresDetail::getIsGift, waresRangeParams.getIsGift());
                }
                // 查询当前商品详情id
                BdWaresDetail waresDetail = iBdWaresDetailService.getOne(queryWrapper);
                if (waresDetail != null) {
                    // 根据详情外键查询所有规格明细值
                    LambdaQueryWrapper<BdWaresSpecsRelation> specsWrapper = new LambdaQueryWrapper<>();
                    specsWrapper.eq(BdWaresSpecsRelation::getPkWaresDetail, waresDetail.getPkId());
                    List<BdWaresSpecsRelation> relationList = iBdWaresSpecsRelationService.list(specsWrapper);
                    // 根据规格id 分组
                    Map<Integer, List<BdWaresSpecsRelation>> collect = relationList.stream().collect(Collectors.groupingBy(BdWaresSpecsRelation::getPkWaresSpecsSku));
                    for (Map.Entry<Integer, List<BdWaresSpecsRelation>> integer : collect.entrySet()) {
                        List<Integer> pkWaresSpecsList = new ArrayList<>();
                        List<Integer> pkWaresSpecsIds = integer.getValue().stream().map(BdWaresSpecsRelation::getPkWaresSpecs).collect(Collectors.toList());

                        LambdaQueryWrapper<BdWaresSpecs> listWrapper = new LambdaQueryWrapper<>();
                        listWrapper.in(BdWaresSpecs::getPkId, pkWaresSpecsIds);
                        List<BdWaresSpecs> rslist = iBdWaresSpecsService.list(listWrapper);
                        for (BdWaresSpecs bdWaresSpecs : rslist) {
                            pkWaresSpecsList.add(bdWaresSpecs.getPkSpecs());
                        }

                        Collections.sort(specsList);
                        Collections.sort(pkWaresSpecsList);
                        // 校验两数组规格是否完全一致
                        if (specsList.equals(pkWaresSpecsList)) {
                            pkWaresSpecsSku = integer.getKey();
                        }
                    }
                    BdWaresRange bdWaresRange = new BdWaresRange();
                    bdWaresRange.setPkWares(wares.getPkId());
                    bdWaresRange.setPkProduct(waresRangeParams.getPkProduct());
                    bdWaresRange.setPkWaresDetail(waresDetail.getPkId());
                    if (pkWaresSpecsSku != null) {
                        bdWaresRange.setPkWaresSpecsSku(pkWaresSpecsSku);
                    } else {
                        bdWaresRange.setPkWaresSpecsSku(relationList.get(0).getPkWaresSpecsSku());
                    }
                    bdWaresRange.setPkRange(waresRangeParams.getPkRange());
                    bdWaresRange.setPrice(waresRangeParams.getPrice() == null ? BigDecimal.ZERO : waresRangeParams.getPrice());
                    bdWaresRange.setAchieve(waresRangeParams.getAchieve() == null ? BigDecimal.ZERO : waresRangeParams.getAchieve());
                    bdWaresRange.setCreationTime(new Date());
                    bdWaresRange.setPkCountry(user.getDataCountry());
                    bdWaresRange.setPkCreator(user.getUserId());
                    bdWaresRange.setAssAchieve(waresRangeParams.getAssAchieve());
                    wrList.add(bdWaresRange);
                }
            }
            if (wrList.size() > 0) {
                iBdWaresRangeService.saveBatch(wrList);
            }
        }
    }

    /**
     * 生成特殊明细表
     *
     * @param wares
     */
    private void saveWaresAuthority(BdWares wares, List<WaresAuthorityParam> waresAuthorityList, LoginUser user) {
        List<BdWaresAuthority> waList = new ArrayList<>();
        for (WaresAuthorityParam waresAuthorityParam : waresAuthorityList) {
            Long memberId = null;
            if (StringUtils.isNotBlank(waresAuthorityParam.getMemberCode())) {
                R<CuMember> member = iMemberServiceApi.getMember(waresAuthorityParam.getMemberCode());
                if (member.getData() == null) {
                    throw new BaseException("查询会员失败");
                }
                memberId = member.getData().getPkId();
            }
            BdWaresAuthority bdWaresAuthority = new BdWaresAuthority();
            bdWaresAuthority.setPkWares(wares.getPkId());
            bdWaresAuthority.setAuthorityType(waresAuthorityParam.getAuthorityType());
            bdWaresAuthority.setCreationTime(new Date());
            bdWaresAuthority.setPkCountry(user.getDataCountry());
            bdWaresAuthority.setPkCreator(user.getUserId());
            //  选择权限类型为全部时  会员主键可以为空
            bdWaresAuthority.setPkMember(memberId);
            bdWaresAuthority.setMemberCode(waresAuthorityParam.getMemberCode());
            waList.add(bdWaresAuthority);

        }
        iBdWaresAuthorityService.saveBatch(waList);
    }

    /**
     * 生成规格明细表
     *
     * @param wares
     * @param waresSpecsSkuList
     * @param user
     */
    private void saveWaresSpecsSku(BdWares wares, List<WaresSpecsSkuParams> waresSpecsSkuList, LoginUser user) {
        for (WaresSpecsSkuParams waresSpecsSkuParams : waresSpecsSkuList) {
            if (waresSpecsSkuParams.getPkWaresSpecsSku() == null) {
                BdWaresSpecsSku bdWaresSpecsSku = new BdWaresSpecsSku();
                bdWaresSpecsSku.setPkWares(wares.getPkId());
                // 商品详情id查询
                LambdaQueryWrapper<BdWaresDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BdWaresDetail::getPkWares, wares.getPkId());
                queryWrapper.eq(BdWaresDetail::getPkProduct, waresSpecsSkuParams.getPkProduct());
                if (waresSpecsSkuParams.getIsGift() != null) {
                    queryWrapper.eq(BdWaresDetail::getIsGift, waresSpecsSkuParams.getIsGift());
                }
                BdWaresDetail waresDetail = iBdWaresDetailService.getOne(queryWrapper);
                Integer waresDetailId = waresDetail.getPkId();
                bdWaresSpecsSku.setPkWaresDetail(waresDetailId);
                bdWaresSpecsSku.setPrice(waresSpecsSkuParams.getProductPrice());
                bdWaresSpecsSku.setAchieve(waresSpecsSkuParams.getProductAchieve());
                bdWaresSpecsSku.setIsPutOn(waresSpecsSkuParams.getIsPutOn());
                bdWaresSpecsSku.setSpecCover(waresSpecsSkuParams.getSpecCover());
                bdWaresSpecsSku.setAssAchieve(waresSpecsSkuParams.getAssAchieve());
                bdWaresSpecsSku.setVipPrice(waresSpecsSkuParams.getVipPrice());
                bdWaresSpecsSku.setRetailPrice(waresSpecsSkuParams.getRetailPrice());
                iBdWaresSpecsSkuService.save(bdWaresSpecsSku);
                // 生成规格明细表
                List<BdWaresSpecs> waresSpecsList = waresSpecsSkuParams.getWaresSpecsList();
                for (BdWaresSpecs waresSpecs : waresSpecsList) {
                    waresSpecs.setPkWaresDetail(waresDetailId);
                    waresSpecs.setCreationTime(new Date());
                    waresSpecs.setPkCountry(user.getDataCountry());
                    waresSpecs.setPkCreator(user.getUserId());
                    iBdWaresSpecsService.save(waresSpecs);
                    // 生成规格明细关系表
                    BdWaresSpecsRelation waresSpecsRelation = new BdWaresSpecsRelation();
                    waresSpecsRelation.setCreationTime(new Date());
                    waresSpecsRelation.setPkWaresDetail(waresDetailId);
                    waresSpecsRelation.setPkWaresSpecs(waresSpecs.getPkId());
                    waresSpecsRelation.setPkWaresSpecsSku(bdWaresSpecsSku.getPkId());
                    iBdWaresSpecsRelationService.save(waresSpecsRelation);
                }
            } else {
                // 如果sku id 非空 表示在当前数据中修改
                BdWaresSpecsSku bdWaresSpecsSku = iBdWaresSpecsSkuService.selectByWaresSpecsSkuIdAndDel(waresSpecsSkuParams.getPkWaresSpecsSku());
                // 商品规格关联明细值 id
                // 商品详情id查询
                LambdaQueryWrapper<BdWaresDetail> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BdWaresDetail::getPkWares, wares.getPkId());
                queryWrapper.eq(BdWaresDetail::getPkProduct, waresSpecsSkuParams.getPkProduct());
                if (waresSpecsSkuParams.getIsGift() != null) {
                    queryWrapper.eq(BdWaresDetail::getIsGift, waresSpecsSkuParams.getIsGift());
                }
                BdWaresDetail waresDetail = iBdWaresDetailService.getOne(queryWrapper);
                Integer waresDetailId = waresDetail.getPkId();
                // 生成规格明细表
                List<BdWaresSpecs> waresSpecsList = waresSpecsSkuParams.getWaresSpecsList();
                for (BdWaresSpecs waresSpecs : waresSpecsList) {
                    waresSpecs.setPkWaresDetail(waresDetailId);
                    waresSpecs.setCreationTime(new Date());
                    waresSpecs.setPkCreator(user.getUserId());
                    iBdWaresSpecsService.save(waresSpecs);
                    // 生成规格明细关系表
                    BdWaresSpecsRelation waresSpecsRelation = new BdWaresSpecsRelation();
                    waresSpecsRelation.setCreationTime(new Date());
                    waresSpecsRelation.setPkWaresDetail(waresDetailId);
                    waresSpecsRelation.setPkWaresSpecs(waresSpecs.getPkId());
                    waresSpecsRelation.setPkWaresSpecsSku(bdWaresSpecsSku.getPkId());
                    iBdWaresSpecsRelationService.save(waresSpecsRelation);
                }
                // 修改sku 主表
                BdWaresSpecsSku sku = new BdWaresSpecsSku();
                sku.setPkId(bdWaresSpecsSku.getPkId());
                sku.setDelFlag(EDelFlag.UN_DELETE.getValue());
                sku.setPrice(waresSpecsSkuParams.getProductPrice());
                sku.setAchieve(waresSpecsSkuParams.getProductAchieve());
                sku.setAssAchieve(waresSpecsSkuParams.getAssAchieve());
                sku.setPkWaresDetail(waresDetailId);
                sku.setVipPrice(waresSpecsSkuParams.getVipPrice());
                sku.setRetailPrice(waresSpecsSkuParams.getRetailPrice());
                sku.setSpecCover(waresSpecsSkuParams.getSpecCover());
                if (waresSpecsSkuParams.getIsPutOn() != null) {
                    sku.setIsPutOn(waresSpecsSkuParams.getIsPutOn());
                } else {
                    sku.setIsPutOn(EYesNo.YES.getIntValue());
                }
                iBdWaresSpecsSkuService.updateBySkuId(sku);
                redisService.deleteObject(CacheConstants.BD_WARES_SPECS_RELATION + bdWaresSpecsSku.getPkId());
            }
        }
    }

    /**
     * 新增产品明细表
     */
    private void saveWaresDetail(BdWares wares, List<WaresDetailParams> list, LoginUser user) {
        List<BdWaresDetail> waresDetailList = new ArrayList<>();
        for (WaresDetailParams waresDetailParams : list) {
            BdWaresDetail bdWaresDetail = new BdWaresDetail();
            bdWaresDetail.setPkProduct(waresDetailParams.getPkProduct());
            bdWaresDetail.setQuantity(waresDetailParams.getQuantity());
            bdWaresDetail.setIsGift(waresDetailParams.getIsGift());
            bdWaresDetail.setPkWares(wares.getPkId());
            bdWaresDetail.setPkCreator(user.getUserId());
            bdWaresDetail.setCreationTime(new Date());
            bdWaresDetail.setPkCountry(user.getDataCountry());
            waresDetailList.add(bdWaresDetail);
        }
        if (waresDetailList.size() > 0) {
            iBdWaresDetailService.saveBatch(waresDetailList);
        }
    }

    /**
     * 新增产品包装
     *
     * @param wares
     * @param waresSpecsPackList
     */
    private void saveWaresSpecsPack(BdWares wares, List<WaresSpecsPackParams> waresSpecsPackList) {
        // 产品规格和包装表
        for (WaresSpecsPackParams waresSpecsPackParams : waresSpecsPackList) {
            List<BdWaresSpecsPack> list = new ArrayList<>();
            if (StringUtils.isNotBlank(waresSpecsPackParams.getKey()) && StringUtils.isNotBlank(waresSpecsPackParams.getValue())) {
                BdWaresSpecsPack bdWaresSpecsPack = new BdWaresSpecsPack();
                bdWaresSpecsPack.setPkWares(wares.getPkId());
                bdWaresSpecsPack.setKey(waresSpecsPackParams.getKey());
                bdWaresSpecsPack.setValue(waresSpecsPackParams.getValue());
                bdWaresSpecsPack.setCreationTime(new Date());
                bdWaresSpecsPack.setPkCreator(SecurityUtils.getUserId());
                bdWaresSpecsPack.setPkCountry(SecurityUtils.getPkCountry());
                list.add(bdWaresSpecsPack);
            }
            iBdWaresSpecsPackService.saveBatch(list);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWares(WaresParams waresParams, LoginUser user) {
        BdWares wares = BeanUtil.copyProperties(waresParams, BdWares.class);
        wares.setPkId(waresParams.getWaresId());
        R<Integer> transaction = iTransactionServiceApi.createTransaction(user.getDataCountry(), ETransactionKey.SPEC, waresParams.getWaresName(), EYesNo.NO, EYesNo.NO);
        wares.setPkTransaction(transaction.getData());
        if (waresParams.getIsPutOn().equals(EYesNo.YES.getIntValue())) {
            wares.setListingTime(DateUtils.currentDateTime());
        }
        if (waresParams.getIsPutOn().equals(EYesNo.NO.getIntValue())) {
            wares.setRemovalTime(DateUtils.currentDateTime());
        }
        this.updateById(wares);

        // 设置 上架时间 和下架时间 putOnTime  putOffTime
        iBdWaresExtendService.updatePutOnTimeAndPutOffTimeByWaresId(waresParams.getWaresId(), waresParams.getPutOnTime(), waresParams.getPutOffTime());

        // 商品拓展表
        BdWaresExtend waresExtend = BeanUtil.copyProperties(waresParams, BdWaresExtend.class);
        // 存入要转化美金
        if (!waresParams.getSpecialArea().equals(ESpecialArea.REPURCHASE_AREA.getValue())) {
            waresParams.setMakerIncome(BigDecimal.ZERO);
        }
        if (null != waresParams.getMakerIncome()) {
            R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(user.getDataCountry());
            waresExtend.setMakerIncome(waresParams.getMakerIncome().divide(currencyDto.getData().getInExchangeRate(), 6, BigDecimal.ROUND_HALF_UP));
        }
        waresExtend.setSystemType(ESystemType.DEFAULT.getValue());
        waresExtend.setPkWares(wares.getPkId());
        waresExtend.setPkModified(user.getUserId());
        waresExtend.setModifiedTime(new Date());
        // 根据商品id 修改信息
        LambdaQueryWrapper<BdWaresExtend> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdWaresExtend::getPkWares, wares.getPkId());
        //商品标签表
        // 前缀标签
        BdLabel prefixLabel = null;
        if (waresParams.getPkPrefixLabel() != null) {
            prefixLabel = getBdLabel(waresParams.getPkPrefixLabel());
            if (prefixLabel != null) {
                waresExtend.setPrefixLabel(prefixLabel.getLabel());
            }
        }

        // 炫酷标签
        BdLabel coolLabel = null;
        if (waresParams.getPkCoolLabel() != null) {
            coolLabel = getBdLabel(waresParams.getPkCoolLabel());
            if (coolLabel != null) {
                waresExtend.setCoolLabel(coolLabel.getLabel());
            }
        }

        iBdWaresExtendService.update(waresExtend, queryWrapper);

        // 删除关联表
        deleteWaresInfo(waresParams.getWaresId());
        // 生成关联表
        saveWaresLabel(wares, prefixLabel, coolLabel, waresParams.getPkGuaranteeLabel(), waresParams.getPkSellingPoint(), user);
        // 生成产品明细
        saveWaresDetail(wares, waresParams.getWaresDetailList(), user);

        // 生成规格sku 表
        saveWaresSpecsSku(wares, waresParams.getWaresSpecsSkuList(), user);
        // 团队配置
        saveWaresAuthority(wares, waresParams.getWaresAuthorityList(), user);
        // 生成 极差配置
//        if (waresParams.getWaresSpecsSkuList().size() > 0){
//            if (waresParams.getSpecialArea().equals(ESpecialArea.REPURCHASE_AREA.getValue()) ||
//                    waresParams.getSpecialArea().equals(ESpecialArea.CLOUD_COLLEGE_ORDER.getValue()) ||
//                    waresParams.getSpecialArea().equals(ESpecialArea.LIVE_BROADCAST.getValue()) ||
//                    waresParams.getSpecialArea().equals(ESpecialArea.COOPERATE_AREA.getValue()) ||
//                    waresParams.getSpecialArea().equals(ESpecialArea.SPECIAL_REPURCHASE_AREA.getValue())
//            ){
//                List<WaresRangeParams> waresRangeParamsList = computeWaresRange(waresParams.getWaresSpecsSkuList());
//                saveWaresRange(wares,waresRangeParamsList, user);
//            }
//        }

        saveWaresRange(wares, waresParams.getWaresRangeList(), user);

        // 产品包装新增
        if (waresParams.getWaresSpecsPackList().size() > 0) {
            saveWaresSpecsPack(wares, waresParams.getWaresSpecsPackList());
        }
        // 添加等级
        if (waresParams.getWaresGradeIds() != null) {
            LambdaQueryWrapper<BdWaresGrade> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(BdWaresGrade::getPkWares, wares.getPkId());
            iBdWaresGradeService.remove(queryWrapper1);
            for (Integer waresGradeId : waresParams.getWaresGradeIds()) {
                BdWaresGrade bdWaresGrade = new BdWaresGrade();
                bdWaresGrade.setPkWares(wares.getPkId());
                bdWaresGrade.setPkRange(waresGradeId);
                bdWaresGrade.setCreationTime(DateUtils.currentDateTime());
                bdWaresGrade.setPkCreator(user.getUserId());
                bdWaresGrade.setPkCountry(user.getDataCountry());
                iBdWaresGradeService.save(bdWaresGrade);
            }
        }
        // 奖衔
        if (waresParams.getWaresAwardsIds() != null) {
            // IBdWaresAwardsService
            LambdaQueryWrapper<BdWaresAwards> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(BdWaresAwards::getPkWares, wares.getPkId());
            iBdWaresAwardsService.remove(queryWrapper1);
            // 校验奖衔id 是否存在
            R<List<BdAwards>> awardsDto = iAwardsServiceApi.queryAwards(waresParams.getPkCountry());
            List<BdAwards> awardsList = awardsDto.getData();
            List<Integer> waresAwardsIdList = new ArrayList<>();
            for (BdAwards bdAwards : awardsList) {
                for (Integer waresAwardsId : waresParams.getWaresAwardsIds()) {
                    if (bdAwards.getPkId().equals(waresAwardsId)) {
                        waresAwardsIdList.add(waresAwardsId);
                    }
                }
            }
            for (Integer waresAwardsId : waresAwardsIdList) {
                BdWaresAwards bdWaresAwards = new BdWaresAwards();
                bdWaresAwards.setPkWares(wares.getPkId());
                bdWaresAwards.setPkAwards(waresAwardsId);
                bdWaresAwards.setCreationTime(DateUtils.currentDateTime());
                bdWaresAwards.setPkCreator(user.getUserId());
                bdWaresAwards.setPkCountry(user.getDataCountry());
                iBdWaresAwardsService.save(bdWaresAwards);
            }
        }

        // 用户权限配置
        if (waresParams.getWaresMemberAuthorizeList() != null) {
            List<BdWaresAuthorize> waList = new ArrayList<>();
            iBdWaresAuthorizeService.removeByPkWares(wares.getPkId());
            for (Integer value : waresParams.getWaresMemberAuthorizeList()) {
                BdWaresAuthorize waresAuthorize = new BdWaresAuthorize();
                waresAuthorize.setPkWares(wares.getPkId());
                waresAuthorize.setValue(value);
                waresAuthorize.setCreationTime(DateUtils.currentDateTime());
                waresAuthorize.setPkCreator(user.getUserId());
                waresAuthorize.setPkCountry(user.getDataCountry());
                waList.add(waresAuthorize);
            }
            if (waList.size() > 0) {
                iBdWaresAuthorizeService.saveBatch(waList);
            }
        }
    }

    /**
     * 商品id
     *
     * @param waresId
     */
    private void deleteWaresInfo(Integer waresId) {
        // 标签关联记录 删除
        LambdaUpdateWrapper<BdWaresLabel> deleteWrapper = new LambdaUpdateWrapper<>();
        deleteWrapper.eq(BdWaresLabel::getPkWares, waresId);
        deleteWrapper.set(BdWaresLabel::getDelFlag, EDelFlag.DELETE.getValue());
        deleteWrapper.set(BdWaresLabel::getModifiedTime, new Date());
        iBdWaresLabelService.update(deleteWrapper);

        // 删除规格
        LambdaUpdateWrapper<BdWaresSpecsSku> waresSpecsSkuWrapper = new LambdaUpdateWrapper<>();
        waresSpecsSkuWrapper.eq(BdWaresSpecsSku::getPkWares, waresId);
        waresSpecsSkuWrapper.set(BdWaresSpecsSku::getDelFlag, EDelFlag.DELETE.getValue());
        waresSpecsSkuWrapper.set(BdWaresSpecsSku::getModifiedTime, new Date());
        iBdWaresSpecsSkuService.update(waresSpecsSkuWrapper);

        // 删除规格关联数据
        LambdaQueryWrapper<BdWaresDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdWaresDetail::getPkWares, waresId);
        List<BdWaresDetail> waresDetailList = iBdWaresDetailService.list(queryWrapper);
        for (BdWaresDetail bdWaresDetail : waresDetailList) {
            // 删除商品关联规格
            LambdaUpdateWrapper<BdWaresSpecs> waresSpecsWrapper = new LambdaUpdateWrapper<>();
            waresSpecsWrapper.eq(BdWaresSpecs::getPkWaresDetail, bdWaresDetail.getPkId());
            waresSpecsWrapper.set(BdWaresSpecs::getDelFlag, EDelFlag.DELETE.getValue());
            waresSpecsWrapper.set(BdWaresSpecs::getModifiedTime, new Date());
            iBdWaresSpecsService.update(waresSpecsWrapper);
            // 删除规格关联数据
            LambdaUpdateWrapper<BdWaresSpecsRelation> waresSpecsRelationWrapper = new LambdaUpdateWrapper<>();
            waresSpecsRelationWrapper.eq(BdWaresSpecsRelation::getPkWaresDetail, bdWaresDetail.getPkId());
            waresSpecsRelationWrapper.set(BdWaresSpecsRelation::getDelFlag, EDelFlag.DELETE.getValue());
            waresSpecsRelationWrapper.set(BdWaresSpecsRelation::getModifiedTime, new Date());
            iBdWaresSpecsRelationService.update(waresSpecsRelationWrapper);
        }
        // 删除产品关联团队配置
        LambdaUpdateWrapper<BdWaresAuthority> waresAuthorityWrapper = new LambdaUpdateWrapper<>();
        waresAuthorityWrapper.eq(BdWaresAuthority::getPkWares, waresId);
        waresAuthorityWrapper.set(BdWaresAuthority::getDelFlag, EDelFlag.DELETE.getValue());
        waresAuthorityWrapper.set(BdWaresAuthority::getModifiedTime, new Date());
        iBdWaresAuthorityService.update(waresAuthorityWrapper);
        //删除产品明细
        LambdaUpdateWrapper<BdWaresDetail> waresDetailWrapper = new LambdaUpdateWrapper<>();
        waresDetailWrapper.eq(BdWaresDetail::getPkWares, waresId);
        waresDetailWrapper.set(BdWaresDetail::getDelFlag, EDelFlag.DELETE.getValue());
        waresDetailWrapper.set(BdWaresDetail::getModifiedTime, new Date());
        iBdWaresDetailService.update(waresDetailWrapper);
        // 删除极差明细
        LambdaUpdateWrapper<BdWaresRange> waresRangeWrapper = new LambdaUpdateWrapper<>();
        waresRangeWrapper.eq(BdWaresRange::getPkWares, waresId);
        waresRangeWrapper.set(BdWaresRange::getDelFlag, EDelFlag.DELETE.getValue());
        waresRangeWrapper.set(BdWaresRange::getModifiedTime, new Date());
        iBdWaresRangeService.update(waresRangeWrapper);
        // 删除包装和规格
        LambdaUpdateWrapper<BdWaresSpecsPack> waresSpecsPackWrapper = new LambdaUpdateWrapper<>();
        waresSpecsPackWrapper.eq(BdWaresSpecsPack::getPkWares, waresId);
        waresSpecsPackWrapper.set(BdWaresSpecsPack::getDelFlag, EDelFlag.DELETE.getValue());
        waresSpecsPackWrapper.set(BdWaresSpecsPack::getModifiedTime, new Date());
        iBdWaresSpecsPackService.update(waresSpecsPackWrapper);

    }

    /**
     * 删除商品记录日志
     *
     * @param wares
     */
    private void createDeleteWaresLog(BdWares wares, Integer businessType, LoginUser loginUser) {
        // 拼装发送mq
        String str = "商品删除主键" + wares.getPkId() +
                "商品名称" + wares.getWaresName() +
                "商品编号" + wares.getWaresCode();
        BusinessLogDTO log = BusinessLogDTO.builder()
                .businessType(businessType)
                .businessId(wares.getPkId().longValue())
                .pkMember(null)
                .content(str)
                .pkCreator(loginUser.getUserId())
                .pkCountry(loginUser.getDataCountry())
                .freeSignFlag(true)
                .build();
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeWares(Integer pkId, LoginUser loginUser) {
        BdWares wares = this.getWares(pkId);
        Long userId = SecurityUtils.getUserId();
        LambdaUpdateWrapper<BdWares> waresWrapper = new LambdaUpdateWrapper<>();
        waresWrapper.eq(BdWares::getPkId, pkId);
        waresWrapper.set(BdWares::getPkModified, userId);
        waresWrapper.set(BdWares::getModifiedTime, new Date());
        waresWrapper.set(BdWares::getDelFlag, EDelFlag.DELETE.getValue());
        this.update(waresWrapper);
        // 删除商品拓展表
        LambdaUpdateWrapper<BdWaresExtend> waresExpendWrapper = new LambdaUpdateWrapper<>();
        waresExpendWrapper.eq(BdWaresExtend::getPkWares, pkId);
        waresExpendWrapper.set(BdWaresExtend::getPkModified, userId);
        waresExpendWrapper.set(BdWaresExtend::getModifiedTime, new Date());
        waresExpendWrapper.set(BdWaresExtend::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresExtendService.update(waresExpendWrapper);
        // 删除
        LambdaUpdateWrapper<BdWaresAuthority> waresAuthorityWrapper = new LambdaUpdateWrapper<>();
        waresAuthorityWrapper.eq(BdWaresAuthority::getPkWares, pkId);
        waresAuthorityWrapper.set(BdWaresAuthority::getPkModified, userId);
        waresAuthorityWrapper.set(BdWaresAuthority::getModifiedTime, new Date());
        waresAuthorityWrapper.set(BdWaresAuthority::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresAuthorityService.update(waresAuthorityWrapper);
        //删除标签管理
        LambdaUpdateWrapper<BdWaresLabel> waresLabelWrapper = new LambdaUpdateWrapper<>();
        waresLabelWrapper.eq(BdWaresLabel::getPkWares, pkId);
        waresLabelWrapper.set(BdWaresLabel::getPkModified, userId);
        waresLabelWrapper.set(BdWaresLabel::getModifiedTime, new Date());
        waresLabelWrapper.set(BdWaresLabel::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresLabelService.update(waresLabelWrapper);
        // 删除极差
        LambdaUpdateWrapper<BdWaresRange> waresRangeWrapper = new LambdaUpdateWrapper<>();
        waresRangeWrapper.eq(BdWaresRange::getPkWares, pkId);
        waresRangeWrapper.set(BdWaresRange::getPkModified, userId);
        waresRangeWrapper.set(BdWaresRange::getModifiedTime, new Date());
        waresRangeWrapper.set(BdWaresRange::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresRangeService.update(waresRangeWrapper);
        // 删除规格明细
        LambdaQueryWrapper<BdWaresDetail> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(BdWaresDetail::getPkWares, pkId);
        List<BdWaresDetail> list = iBdWaresDetailService.list(detailWrapper);
        for (BdWaresDetail bdWaresDetail : list) {
            LambdaUpdateWrapper<BdWaresSpecs> waresSpecsWrapper = new LambdaUpdateWrapper<>();
            waresSpecsWrapper.eq(BdWaresSpecs::getPkWaresDetail, bdWaresDetail.getPkId());
            waresSpecsWrapper.set(BdWaresSpecs::getPkModified, userId);
            waresSpecsWrapper.set(BdWaresSpecs::getModifiedTime, new Date());
            waresSpecsWrapper.set(BdWaresSpecs::getDelFlag, EDelFlag.DELETE.getValue());
            iBdWaresSpecsService.update(waresSpecsWrapper);
        }
        // 删除商品明细表
        LambdaUpdateWrapper<BdWaresDetail> waresDetailWrapper = new LambdaUpdateWrapper<>();
        waresDetailWrapper.eq(BdWaresDetail::getPkWares, pkId);
        waresDetailWrapper.set(BdWaresDetail::getPkModified, userId);
        waresDetailWrapper.set(BdWaresDetail::getModifiedTime, new Date());
        waresDetailWrapper.set(BdWaresDetail::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresDetailService.update(waresDetailWrapper);
        // 删除规格和包装
        LambdaUpdateWrapper<BdWaresSpecsPack> waresSpecsPackWrapper = new LambdaUpdateWrapper<>();
        waresSpecsPackWrapper.eq(BdWaresSpecsPack::getPkWares, pkId);
        waresSpecsPackWrapper.set(BdWaresSpecsPack::getPkModified, userId);
        waresSpecsPackWrapper.set(BdWaresSpecsPack::getModifiedTime, new Date());
        waresSpecsPackWrapper.set(BdWaresSpecsPack::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresSpecsPackService.update(waresSpecsPackWrapper);
        // 删除sku
        LambdaQueryWrapper<BdWaresSpecsSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdWaresSpecsSku::getPkWares, pkId);
        List<BdWaresSpecsSku> waresSpecsSkuList = iBdWaresSpecsSkuService.list(queryWrapper);
        for (BdWaresSpecsSku bdWaresSpecsSku : waresSpecsSkuList) {
            LambdaUpdateWrapper<BdWaresSpecsRelation> waresSpecsRelationWrapper = new LambdaUpdateWrapper<>();
            waresSpecsRelationWrapper.eq(BdWaresSpecsRelation::getPkWaresSpecsSku, bdWaresSpecsSku.getPkId());
            waresSpecsRelationWrapper.set(BdWaresSpecsRelation::getPkModified, userId);
            waresSpecsRelationWrapper.set(BdWaresSpecsRelation::getModifiedTime, new Date());
            waresSpecsRelationWrapper.set(BdWaresSpecsRelation::getDelFlag, EDelFlag.DELETE.getValue());
            iBdWaresSpecsRelationService.update(waresSpecsRelationWrapper);
        }

        LambdaUpdateWrapper<BdWaresSpecsSku> waresSpecsSkuWrapper = new LambdaUpdateWrapper<>();
        waresSpecsSkuWrapper.eq(BdWaresSpecsSku::getPkWares, pkId);
        waresSpecsSkuWrapper.set(BdWaresSpecsSku::getPkModified, userId);
        waresSpecsSkuWrapper.set(BdWaresSpecsSku::getModifiedTime, new Date());
        waresSpecsSkuWrapper.set(BdWaresSpecsSku::getDelFlag, EDelFlag.DELETE.getValue());
        iBdWaresSpecsSkuService.update(waresSpecsSkuWrapper);
        if (wares != null) {
            createDeleteWaresLog(wares, EApprovalBusiness.WARES_REMOVE.getValue(), loginUser);
        }
    }

    @Override
    public List<BdWaresExt> queryWaresByCondition() {
        return baseMapper.queryWaresByCondition(null, null, null, null, null, null, null);
    }

    @Override
    public BdWares getWares(Integer waresId) {
        String redisKey = CacheConstants.BD_WARES + waresId;
        BdWares wares = redisService.getCacheObject(redisKey);
        if (null == wares) {
            wares = baseMapper.selectById(waresId);
            if (null != wares) {
                redisService.setCacheObject(redisKey, wares, CacheConstants.WARES_REFRESH_TIME, TimeUnit.DAYS);
            }
        }
        return wares;
    }

    @Override
    public String getLastWaresCode() {
        return baseMapper.getLastWaresCode();
    }

    @Override
    public List<WaresVo> selectByWaresInfo(WaresParams waresParams) {
        return baseMapper.selectByWaresInfo(waresParams);
    }

    @Override
    public void waresMove(Integer waresId, Integer waresMoveType, LoginUser loginUser, Integer specialArea) {
        BdWares bdWares = baseMapper.selectById(waresId);
        if (waresMoveType == EProductMoveType.MOVEUP.getIntValue()) {
            Integer sort = baseMapper.selectByMoveUpSort(waresId, specialArea);
            if (sort != null) {
                Integer maxSort = sort + 1;
                // 查询该排序号码是否重复
                LambdaQueryWrapper<BdWares> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BdWares::getSort, maxSort);
                int count = this.count(queryWrapper);
                if (count > 0) {
                    baseMapper.updateMoveUpBySort(maxSort);
                    LambdaUpdateWrapper<BdWares> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(BdWares::getPkId, waresId);
                    updateWrapper.set(BdWares::getSort, maxSort);
                    this.update(updateWrapper);
                } else {
                    LambdaUpdateWrapper<BdWares> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(BdWares::getPkId, waresId);
                    updateWrapper.set(BdWares::getSort, maxSort);
                    this.update(updateWrapper);
                }
            }
            if (bdWares != null) {
                // 产品上移日志
                createWaresMoveLog(bdWares, EApprovalBusiness.WARES_MOVEUP.getValue(), waresMoveType, loginUser);
            }
        } else if (waresMoveType == EProductMoveType.MOVEDOWN.getIntValue()) {
            Integer sort = this.selectByMoveDownSort(waresId, specialArea);
            if (sort != null) {
                Integer minSort = sort - 1;
                // 查询该排序号码是否重复
                LambdaQueryWrapper<BdWares> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(BdWares::getSort, minSort);
                int count = this.count(queryWrapper);
                if (count > 0) {
                    baseMapper.updateMoveDownBySort(minSort);
                    LambdaUpdateWrapper<BdWares> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(BdWares::getPkId, waresId);
                    updateWrapper.set(BdWares::getSort, minSort);
                    this.update(updateWrapper);
                } else {
                    LambdaUpdateWrapper<BdWares> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(BdWares::getPkId, waresId);
                    updateWrapper.set(BdWares::getSort, minSort);
                    this.update(updateWrapper);
                }
            }

            if (bdWares != null) {
                // 产品下移日志
                createWaresMoveLog(bdWares, EApprovalBusiness.WARES_MOVEDOWN.getValue(), waresMoveType, loginUser);
            }
        }
    }

    /**
     * 商品上移/下移日志
     *
     * @param bdWares       商品
     * @param businessType  业务类型
     * @param waresMoveType 上移/下移
     * @param loginUser     登录用户
     */
    private void createWaresMoveLog(BdWares bdWares, Integer businessType, Integer waresMoveType, LoginUser loginUser) {
        StringBuilder str = new StringBuilder();
        if (waresMoveType == EProductMoveType.MOVEUP.getIntValue()) {
            // 上移
            str.append("商品上移: 商品编号").append(bdWares.getWaresCode());
        } else if (waresMoveType == EProductMoveType.MOVEDOWN.getIntValue()) {
            // 下移
            str.append("商品下移: 商品编号").append(bdWares.getWaresCode());
        }
        str.append("商品名称:").append(bdWares.getWaresName());
        str.append("商品主键:").append(bdWares.getPkId());
        // 拼装发送mq
        BusinessLogDTO log = BusinessLogDTO.builder()
                .businessType(businessType)
                .businessCode(bdWares.getWaresCode())
                .businessId(bdWares.getPkId().longValue())
                .pkMember(null)
                .content(str.toString())
                .pkCreator(loginUser.getUserId())
                .pkCountry(loginUser.getDataCountry())
                .freeSignFlag(true)
                .build();
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY, log);
    }

    @Override
    public Integer selectByMoveDownSort(Integer waresId, Integer specialArea) {
        return baseMapper.selectByMoveDownSort(waresId, specialArea);
    }

    @Override
    public void floatingRoof(Integer waresId, LoginUser loginUser) {
        BdWares bdWares = new BdWares();
        bdWares.setSortStatus(1);
        bdWares.setPkId(waresId);
        this.updateById(bdWares);
    }

    @Override
    public Integer getMaxSort(Integer pkCountry) {
        return baseMapper.getMaxSort(pkCountry);
    }

    @Override
    public List<BdAgreement> selectByWaresCodeList(List<String> waresCodeList) {
        return baseMapper.selectByWaresCodeList(waresCodeList);
    }

    @Override
    public List<BdWaresExt> queryWaresByCondition(Integer specialArea, Integer pkAreaClassify, String waresName,
                                                  List<String> waresCodeInList, List<String> waresCodeNotInList, Integer pkCountry) {
        return baseMapper.queryWaresByCondition(specialArea, pkAreaClassify, null, waresName, waresCodeInList, waresCodeNotInList, pkCountry);
    }

    @Override
    public List<BdWaresExt> queryRecommendWaresByCondition(Integer specialArea, Integer pkAreaClassify, String waresName, Integer pkCountry) {
        return baseMapper.queryRecommendWaresByCondition(specialArea, pkAreaClassify, null, waresName, pkCountry);
    }

    private BdLabel getBdLabel(Integer pkId) {
        BdLabel bdLabel;
        R<LabelConfigDTO> result = iLabelServiceApi.getByPkId(pkId);
        if (result.isSuccess()) {
            bdLabel = BeanUtil.copyProperties(result.getData(), BdLabel.class);
        } else {
            bdLabel = new BdLabel();
        }
        return bdLabel;
    }

    @Override
    public RecommendWaresInfoVo queryRecommendInfo(Integer pkCountry, String memberCode, Long userId, Map<Integer, Boolean> waresShowMap) {
        // 注册专区 只有报单中心 和服务中心 能看国内 海粉可以看到（复购、升级、海粉、合作） pk_settle_grade=1
        // 登录用户
        R<CuMemberExt> loginMemberDto = iMemberServiceApi.getMemberByCode(memberCode);
        CuMemberExt loginMember = loginMemberDto.getData();

        // 续约标记 -- 会员还有3月到期，需要能看到续约专区
        boolean expireFlag = false;
        if (null != loginMember.getExpireDate()) {
            expireFlag = DateUtils.addMonths(new Date(), 3).compareTo(loginMember.getExpireDate()) > 0;
        }

        // 注册专区权限
        boolean isLexRegister = ERegistrationAuthority.DECLARATION.getValue() == loginMember.getRegisterAuthority()
                || ERegistrationAuthority.SERVICE.getValue() == loginMember.getRegisterAuthority();

        // 查询配置菜单列表
        // 结算等级
        int pkGrade = loginMember.getPkSettleGrade();
        // 真实奖衔
        int pkAwards = loginMember.getPkAwards();
        // 注册权限
        int authority = loginMember.getRegisterAuthority();
        // 查询权限配置
        List<BdMenuDetail> menuDetailList = iMenuDetailServiceApi.showMenuDetail(pkGrade, pkAwards, authority, pkCountry).getData();

        // 查询存在推荐的专区
        List<Integer> saList = baseMapper.queryRecommendWaresSpecial();
        List<Integer> specialAreaList = new ArrayList<>();
        //校验菜单权限  如果没有配置则全部显示
        if (menuDetailList.size() > 0) {
            for (BdMenuDetail bdMenuDetail : menuDetailList) {
                for (Integer specialArea : saList) {
                    ESpecialArea sarea = ESpecialArea.getESpecialAreaEnum(specialArea);
                    if (bdMenuDetail.getDetailValue().equals(sarea.getMenuDetailValue())) {
                        specialAreaList.add(specialArea);
                    }
                }
            }
        } else {
            specialAreaList = saList;
        }

        RecommendWaresInfoVo recommendWaresInfoVo = new RecommendWaresInfoVo();
        // 推荐专区
        List<RecommendSpecialAreaVo> resultList = new ArrayList<>();
        for (Integer specialArea : specialAreaList) {
            ESpecialArea sArea = ESpecialArea.getESpecialAreaEnum(specialArea);
            if (sArea != null) {
                if (StringUtils.isNotBlank(sArea.getLabel())) {
                    RecommendSpecialAreaVo recommendSpecialAreaVo = new RecommendSpecialAreaVo();

                    if (specialArea.equals(ESpecialArea.SPECIAL_REGISTER_AREA.getValue())
                            || specialArea.equals(ESpecialArea.SPECIAL_UPGRADE_AREA.getValue())) {
                        // 乐学注册权限判断
                        if (!isLexRegister) {
                            continue;
                        }
                    }
                    if (specialArea.equals(ESpecialArea.RENEWAL_AREA.getValue())) {
                        // 续约专区，只有有效期小于3个月的能看到
                        if (!expireFlag) {
                            continue;
                        }
                    }
                    resultList.add(recommendSpecialAreaVo);

                    recommendSpecialAreaVo.setSpecialArea(specialArea);
                    recommendSpecialAreaVo.setSort(sArea.getSort());
                    recommendSpecialAreaVo.setSpecialAreaName(sArea.getLabel());

                    // 推荐商品 取值前两个
                    List<BdWaresExt> waresList = this.queryByRecommendList(specialArea, EYesNo.YES.getIntValue(), pkCountry, waresShowMap);
                    List<BdWaresExt> filterList = new ArrayList<>();
                    if (waresList.size() > 3) {
                        filterList.add(waresList.get(0));
                        filterList.add(waresList.get(1));
                        filterList.add(waresList.get(2));
                    } else {
                        filterList.addAll(waresList);
                    }
                    List<WaresVo> waresVoList = filterList.stream().map(wl -> {
                        WaresVo waresVo = new WaresVo();
                        waresVo.setPkWares(wl.getPkId());
                        waresVo.setIsSale(wl.getIsSale());
                        waresVo.setPreSaleStatus(wl.getPreSaleStatus());
                        waresVo.setWaresCode(wl.getWaresCode());
                        waresVo.setSpecialArea(wl.getSpecialArea());
                        waresVo.setCover(wl.getCover());
                        waresVo.setCover1(wl.getCover1());
                        waresVo.setWaresPrice(wl.getWaresPrice());
                        return waresVo;
                    }).collect(Collectors.toList());
                    recommendSpecialAreaVo.setWaresList(waresVoList);
                }
            }
        }

        //  根据专区排序（按照指定排序排序: 注冊 升级 复购 自营 海粉 嗨粉）
        resultList.sort(Comparator.comparingInt(RecommendSpecialAreaVo::getSort));
        recommendWaresInfoVo.setRecommendSpecialAreaList(resultList);

        // 查询推荐商品
        List<BdWaresExt> waresList = this.selectByRecommentList(pkCountry, specialAreaList);
        // 校验商品奖衔和等级/团队权限
        List<Integer> waresIdList = waresList.stream().map(BdWares::getPkId).collect(Collectors.toList());

        Set<Integer> waresIdSet = new HashSet<>();
        List<String> authWaresList = new ArrayList<>();
        if (waresIdList.size() > 0) {
            // 处理商品权限
            List<WaresGradeAwards> waresGradeAwardsList = iBdWaresGradeService.queryWaresGradeAwards(waresIdList);
            // 先处理没有配置等级、奖衔的商品
            waresGradeAwardsList.forEach(waresGradeAwards -> {
                waresIdSet.add(waresGradeAwards.getPkWares());
                String key = waresGradeAwards.getPkWares() + "_" + waresGradeAwards.getRangeType() + "_" + waresGradeAwards.getPkRange().toString();
                authWaresList.add(key);
            });
        }

        List<BdWaresExt> wsList = new ArrayList<>();
        // 查询商品sku 最小值 和数量
        Map<Integer, List<BdWaresSpecsSkuExt>> waresSpecsSkuMap = new HashMap<>();
        if (waresIdList.size() > 0) {
            List<BdWaresSpecsSkuExt> waresSpecsSkuArray = iBdWaresSpecsSkuService.selectByMinWaresSpecsSkuByPkWaresList(waresIdList);
            waresSpecsSkuMap = waresSpecsSkuArray.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getPkWares));
        }

        for (BdWaresExt waresExt : waresList) {
            if (waresIdSet.contains(waresExt.getPkId())) {
                String gradeKey = waresExt.getPkId() + "_" + ERangeType.GRADE.getValue() + "_" + loginMember.getPkSettleGrade();
                String awardsKey = waresExt.getPkId() + "_" + ERangeType.AWARDS.getValue() + "_" + loginMember.getPkAwards();
                String authorityKey = waresExt.getPkId() + "_" + ERangeType.AUTHORITY.getValue() + "_" + loginMember.getRegisterAuthority();
                if (!authWaresList.contains(gradeKey) && !authWaresList.contains(awardsKey) && !authWaresList.contains(authorityKey)) {
                    continue;
                }
            }

            List<BdWaresSpecsSkuExt> waresSpecsSku = waresSpecsSkuMap.get(waresExt.getPkId());
            waresSpecsSku = waresSpecsSku.stream().peek(a -> a.setProductGift(a.getPkProduct() + "" + a.getIsGift())).collect(Collectors.toList());
            Map<String, List<BdWaresSpecsSkuExt>> col = waresSpecsSku.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getProductGift));
            BigDecimal waresPrice = BigDecimal.ZERO;
            BigDecimal waresAchieve = BigDecimal.ZERO;
            BigDecimal assAchieve = BigDecimal.ZERO;
            // 会员价
            BigDecimal vipAchieve = BigDecimal.ZERO;
            // 零售价
            BigDecimal retailPrice = BigDecimal.ZERO;
            for (Map.Entry<String, List<BdWaresSpecsSkuExt>> integerListEntry : col.entrySet()) {
                // 取得每一个商品价格最小值
                Optional<BdWaresSpecsSkuExt> minBdWaresSpecsSkuExt = integerListEntry.getValue().stream().filter(Objects::nonNull).min(Comparator.comparing(BdWaresSpecsSkuExt::getPrice));
                BdWaresSpecsSkuExt bdWaresSpecsSkuExt = minBdWaresSpecsSkuExt.get();
                waresPrice = waresPrice.add(bdWaresSpecsSkuExt.getPrice().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                waresAchieve = waresAchieve.add(bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                assAchieve = assAchieve.add(bdWaresSpecsSkuExt.getAssAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                // 会员价
                vipAchieve = vipAchieve.add(bdWaresSpecsSkuExt.getVipPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
                // 零售价
                retailPrice = retailPrice.add(bdWaresSpecsSkuExt.getRetailPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
            }
            waresExt.setWaresPrice(waresPrice);
            waresExt.setWaresAchieve(waresAchieve);
            waresExt.setVipAPrice(vipAchieve);
            waresExt.setRetailPrice(retailPrice);

            wsList.add(waresExt);
        }

//        //商品区域图片轮播
//        List<WaresCoverInfoVo> waresCoverInfoVoList = new ArrayList<>();
        // 推荐商品展示
        List<WaresVo> waresVoList = new ArrayList<>();
        List<BdWaresRange> bdWaresRangeList = new ArrayList<>();
        if (waresIdList.size() > 0) {
            bdWaresRangeList = iBdWaresRangeService.queryWaresRangeByCondition(loginMember, waresIdList);
        }

        for (BdWaresExt bdWares : wsList) {
//            WaresCoverInfoVo waresCoverInfoVo = new WaresCoverInfoVo();
//            waresCoverInfoVo.setCover(bdWares.getCover1());
//            List<String> coverList = new ArrayList<>();
//            if (StringUtils.isNotBlank(bdWares.getCover1())) {
//                coverList.add(bdWares.getCover1());
//            }
//            if (StringUtils.isNotBlank(bdWares.getCover2())) {
//                coverList.add(bdWares.getCover2());
//            }
//            if (StringUtils.isNotBlank(bdWares.getCover3())) {
//                coverList.add(bdWares.getCover3());
//            }
//            if (StringUtils.isNotBlank(bdWares.getCover4())) {
//                coverList.add(bdWares.getCover4());
//            }
//            if (StringUtils.isNotBlank(bdWares.getCover5())) {
//                coverList.add(bdWares.getCover5());
//            }
//            if (StringUtils.isNotBlank(bdWares.getCover6())) {
//                coverList.add(bdWares.getCover6());
//            }
//            waresCoverInfoVo.setCoverList(coverList);
//            waresCoverInfoVoList.add(waresCoverInfoVo);
            Boolean isShow = waresShowMap.get(bdWares.getPkId());
            if (isShow == null || isShow) {
                // 商品信息填充
                WaresVo waresVo = new WaresVo();

                if (bdWares.getSpecialArea().equals(ESpecialArea.SPECIAL_REGISTER_AREA.getValue())
                        || bdWares.getSpecialArea().equals(ESpecialArea.SPECIAL_UPGRADE_AREA.getValue())) {
                    // 乐学注册权限判断
                    if (!isLexRegister) {
                        continue;
                    }
                }
                if (bdWares.getSpecialArea().equals(ESpecialArea.RENEWAL_AREA.getValue())) {
                    // 续约专区，只有有效期小于3个月的能看到
                    if (!expireFlag) {
                        continue;
                    }
                }
                waresVoList.add(waresVo);

                waresVo.setCover(bdWares.getCover());
                waresVo.setCover1(bdWares.getCover1());
                waresVo.setWaresName(bdWares.getWaresName());
                BigDecimal price = BigDecimal.ZERO;
                if (EOrderType.REPURCHASE_ORDER.getValue() == bdWares.getSpecialArea()) {
                    for (BdWaresRange bdWaresRange : bdWaresRangeList) {
                        if (bdWares.getPkId().intValue() == bdWaresRange.getPkWares().intValue()) {
                            price = price.add(bdWaresRange.getPrice());
                        }
                    }
                } else {
                    price = bdWares.getWaresPrice();
                }
                waresVo.setIsSale(bdWares.getIsSale());
                waresVo.setPreSaleStatus(bdWares.getPreSaleStatus());
                waresVo.setWaresPrice(price);
                waresVo.setSales(bdWares.getSales());
                waresVo.setWaresCode(bdWares.getWaresCode());
                waresVo.setSpecialArea(bdWares.getSpecialArea());
                waresVo.setPkWares(bdWares.getPkId());
                waresVo.setVipPrice(bdWares.getVipAPrice());
                waresVo.setRetailPrice(bdWares.getRetailPrice());
            }
        }
        recommendWaresInfoVo.setWaresVoList(waresVoList);
//        recommendWaresInfoVo.setWaresCoverInfoList(waresCoverInfoVoList);
        return recommendWaresInfoVo;
    }


    @Override
    public RecommendWaresInfoVo listWares(Integer pkCountry, Long userId, Map<Integer, Boolean> waresShowMap) {
        // 登录用户
        CuMemberExt loginMember = iMemberServiceApi.getMemberById(userId).getData();

        // 续约标记 -- 会员还有3月到期，需要能看到续约专区
        boolean expireFlag = false;
        if (null != loginMember.getExpireDate()) {
            expireFlag = DateUtils.addMonths(new Date(), 3).compareTo(loginMember.getExpireDate()) > 0;
        }

        // 注册专区权限
        boolean isLexRegister = ERegistrationAuthority.DECLARATION.getValue() == loginMember.getRegisterAuthority()
                || ERegistrationAuthority.SERVICE.getValue() == loginMember.getRegisterAuthority();

        // 结算等级
        int pkGrade = loginMember.getPkSettleGrade();
        // 真实奖衔
        int pkAwards = loginMember.getPkAwards();
        // 注册权限
        int authority = loginMember.getRegisterAuthority();
        // 查询权限配置
        List<BdMenuDetail> menuDetailList = iMenuDetailServiceApi.showMenuDetail(pkGrade, pkAwards, authority, pkCountry).getData();

        // 查询存在推荐的专区
        List<Integer> saList = baseMapper.queryRecommendWaresSpecial();
        List<Integer> specialAreaList = new ArrayList<>();
        //校验菜单权限  如果没有配置则全部显示
        if (menuDetailList.size() > 0) {
            for (BdMenuDetail bdMenuDetail : menuDetailList) {
                for (Integer specialArea : saList) {
                    ESpecialArea sarea = ESpecialArea.getESpecialAreaEnum(specialArea);
                    if (bdMenuDetail.getDetailValue().equals(sarea.getMenuDetailValue())) {
                        specialAreaList.add(specialArea);
                    }
                }
            }
        } else {
            specialAreaList = saList;
        }

        RecommendWaresInfoVo recommendWaresInfoVo = new RecommendWaresInfoVo();
        // 推荐专区
        List<RecommendSpecialAreaVo> resultList = new ArrayList<>();
        for (Integer specialArea : specialAreaList) {
            ESpecialArea sArea = ESpecialArea.getESpecialAreaEnum(specialArea);
            if (sArea != null) {
                if (StringUtils.isNotBlank(sArea.getLabel())) {
                    RecommendSpecialAreaVo recommendSpecialAreaVo = new RecommendSpecialAreaVo();

                    if (specialArea.equals(ESpecialArea.SPECIAL_REGISTER_AREA.getValue())
                            || specialArea.equals(ESpecialArea.SPECIAL_UPGRADE_AREA.getValue())) {
                        // 乐学注册权限判断
                        if (!isLexRegister) {
                            continue;
                        }
                    }
                    if (specialArea.equals(ESpecialArea.RENEWAL_AREA.getValue())) {
                        // 续约专区，只有有效期小于3个月的能看到
                        if (!expireFlag) {
                            continue;
                        }
                    }
                    recommendSpecialAreaVo.setSpecialArea(specialArea);
                    recommendSpecialAreaVo.setSort(sArea.getSort());
                    recommendSpecialAreaVo.setSpecialAreaName(sArea.getLabel());
                    resultList.add(recommendSpecialAreaVo);

                    // 推荐商品 取值前两个
                    List<BdWaresExt> waresList = this.queryByRecommendList(specialArea, EYesNo.YES.getIntValue(), pkCountry, waresShowMap);
                    List<BdWaresExt> filterList = new ArrayList<>();
                    if (waresList.size() > 3) {
                        filterList.add(waresList.get(0));
                        filterList.add(waresList.get(1));
                        filterList.add(waresList.get(2));
                    } else {
                        filterList.addAll(waresList);
                    }
                    List<WaresVo> waresVoList = filterList.stream().map(wl -> {
                        WaresVo waresVo = new WaresVo();
                        waresVo.setPkWares(wl.getPkId());
                        waresVo.setWaresCode(wl.getWaresCode());
                        waresVo.setWaresName(wl.getWaresName());
                        waresVo.setWaresPrice(wl.getWaresPrice());
                        waresVo.setCover(wl.getCover());
                        waresVo.setCover1(wl.getCover1());
                        waresVo.setIsSale(wl.getIsSale());
                        waresVo.setPreSaleStatus(wl.getPreSaleStatus());
                        waresVo.setSpecialArea(wl.getSpecialArea());
                        return waresVo;
                    }).collect(Collectors.toList());
                    recommendSpecialAreaVo.setWaresList(waresVoList);
                }
            }
        }

        //  根据专区排序（按照指定排序排序: 注冊 升级 复购 自营 海粉 嗨粉）
        resultList.sort(Comparator.comparingInt(RecommendSpecialAreaVo::getSort));
        recommendWaresInfoVo.setRecommendSpecialAreaList(resultList);
        return recommendWaresInfoVo;
    }

    @Override
    public List<BdWaresExt> queryByRecommendList(Integer specialArea, Integer isRecommend, Integer pkCountry, Map<Integer, Boolean> waresShowMap) {
        List<BdWaresExt> bdWares = baseMapper.queryByRecommendList(specialArea, isRecommend, pkCountry);
        List<BdWaresExt> waresList = new ArrayList<>();
        for (BdWaresExt bdWare : bdWares) {
            // 校验推荐商品专区的团队信息
            Boolean isShow = waresShowMap.get(bdWare.getPkId());
            if (isShow == null || isShow) {
                waresList.add(bdWare);
            }
        }
        return waresList;
    }

    @Override
    public void updateByAutoStartAndAutoStart(Date currentTime) {
        baseMapper.updateByAutoStartAndAutoStart(currentTime);
    }

    @Override
    public void waresPreSale() {
        baseMapper.waresPreSale();
    }

    @Override
    public void updateByAutoStartAndAutoEnd(Date currentTime) {
        baseMapper.updateByAutoStartAndAutoEnd(currentTime);
    }

    @Override
    public List<ComputeWaresPrice> computeWaresPrice(List<ComputeWaresPrice> computeWaresPriceList) {
        // 极差
        R<List<BdRangeExt>> rangeDto = iRangeServiceApi.queryRange(SecurityUtils.getPkCountry());
        List<BdRangeExt> rangeList = rangeDto.getData();
        return computeWaresPrice(computeWaresPriceList, rangeList);
    }

    @Override
    public List<ComputeWaresPrice> computeWaresPrice(List<ComputeWaresPrice> computeWaresPriceList, List<BdRangeExt> rangeList) {
        // 极差
        BigDecimal bfb = new BigDecimal(100);

        Set<Integer> specsIds = new HashSet<>();
        if (computeWaresPriceList.size() > 0) {
            // 计算价格
            for (ComputeWaresPrice computeWaresPrice : computeWaresPriceList) {
                if (computeWaresPrice.getSpecsIds() != null) {
                    specsIds.addAll(computeWaresPrice.getSpecsIds());
                }
            }
            // 查询所有的规格名称
            Map<Integer, BdSpecs> specsMap = new HashMap<>();
            if (specsIds.size() > 0) {
                LambdaQueryWrapper<BdSpecs> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.in(BdSpecs::getPkId, specsIds);
                List<BdSpecs> specsList = iBdSpecsService.list(queryWrapper);
                specsMap = specsList.stream().collect(Collectors.toMap(BdSpecs::getPkId, a -> a, (v1, v2) -> v1));
            }

            for (ComputeWaresPrice computeWaresPrice : computeWaresPriceList) {
                List<String> specsNames = new ArrayList<>();
                List<BdWaresSpecs> waresSpecsList = new ArrayList<>();
                List<RangePriceVo> rangePriceVoList = new ArrayList<>();

                if (specsIds.size() > 0) {
                    // 名称
                    for (Integer specsId : computeWaresPrice.getSpecsIds()) {
                        specsNames.add(specsMap.get(specsId).getSpecsName());
                        BdWaresSpecs waresSpecs = new BdWaresSpecs();
                        waresSpecs.setPkSpecs(specsMap.get(specsId).getPkId());
                        waresSpecs.setPkSpecsType(specsMap.get(specsId).getPkSpecsType());
                        waresSpecsList.add(waresSpecs);
                    }
                }
                computeWaresPrice.setSpecsNames(specsNames);

                // 商品主键
                Integer pkWares = computeWaresPrice.getPkWares();
                // 产品主键
                Integer pkProduct = computeWaresPrice.getPkProduct();
                // sku 主键
                Integer pkWaresSpecsSku = computeWaresPrice.getPkWaresSpecsSku();

                if (pkWares != null && pkProduct != null && pkWaresSpecsSku != null) {
                    List<Integer> waresSpecsIds = waresSpecsList.stream().map(BdWaresSpecs::getPkSpecs).collect(Collectors.toList());
                    List<BdWaresSpecsRelationExt> waresSpecsRelationList = iBdWaresSpecsRelationService.getWaresProduct(pkWares, pkProduct, pkWaresSpecsSku, waresSpecsIds);
                    // 数组一致
                    Map<Integer, List<BdWaresSpecsRelationExt>> collect = waresSpecsRelationList.stream().collect(Collectors.groupingBy(BdWaresSpecsRelationExt::getPkRange));

                    if (collect.size() == 0) {
                        // 极差等级
                        for (BdRangeExt bdRangeExt : rangeList) {
                            RangePriceVo rangePriceVo = new RangePriceVo();
                            rangePriceVo.setPkProduct(computeWaresPrice.getPkProduct());
                            if (bdRangeExt.getMoneyRatio() != null && computeWaresPrice.getProductPrice() != null) {
                                rangePriceVo.setPrice(bdRangeExt.getMoneyRatio().multiply(computeWaresPrice.getProductPrice()).divide(bfb));
                            } else {
                                rangePriceVo.setPrice(BigDecimal.ZERO);
                            }
                            if (bdRangeExt.getAchieveRatio() != null && computeWaresPrice.getProductPv() != null) {
                                rangePriceVo.setAchieve(bdRangeExt.getAchieveRatio().multiply(computeWaresPrice.getProductPv()).divide(bfb));
                            } else {
                                rangePriceVo.setAchieve(BigDecimal.ZERO);
                            }
                            rangePriceVo.setWaresSpecsList(waresSpecsList);
                            rangePriceVo.setAssAchieve(computeWaresPrice.getProductBv());
                            rangePriceVo.setPkRange(bdRangeExt.getPkId());
                            rangePriceVo.setRangeName(bdRangeExt.getRangeName());
                            rangePriceVo.setIsGift(computeWaresPrice.getIsGift());
                            rangePriceVo.setProductCode(computeWaresPrice.getProductCode());
                            rangePriceVo.setProductName(computeWaresPrice.getProductName());
                            rangePriceVo.setProductCover(computeWaresPrice.getProductCover());
                            rangePriceVo.setSpecsNames(StringUtils.join(specsNames, ","));
                            rangePriceVoList.add(rangePriceVo);
                        }
                    } else {
                        for (Map.Entry<Integer, List<BdWaresSpecsRelationExt>> integerListEntry : collect.entrySet()) {
                            List<BdWaresSpecsRelationExt> waresSpecsRelationExtList = integerListEntry.getValue();
                            BdWaresSpecsRelationExt waresSpecsRelationExt = waresSpecsRelationExtList.get(0);
                            RangePriceVo rangePriceVo = new RangePriceVo();
                            rangePriceVo.setPkProduct(waresSpecsRelationExt.getPkProduct());
                            rangePriceVo.setPrice(waresSpecsRelationExt.getPrice());
                            rangePriceVo.setAchieve(waresSpecsRelationExt.getAchieve());
                            rangePriceVo.setWaresSpecsList(waresSpecsList);
                            rangePriceVo.setIsGift(computeWaresPrice.getIsGift());
                            rangePriceVo.setAssAchieve(computeWaresPrice.getProductBv());
                            rangePriceVo.setPkRange(waresSpecsRelationExt.getPkRange());
                            rangePriceVo.setRangeName(waresSpecsRelationExt.getRangeName());
                            rangePriceVo.setProductCode(computeWaresPrice.getProductCode());
                            rangePriceVo.setProductName(computeWaresPrice.getProductName());
                            rangePriceVo.setProductCover(computeWaresPrice.getProductCover());
                            rangePriceVo.setSpecsNames(StringUtils.join(specsNames, ","));
                            rangePriceVoList.add(rangePriceVo);

                            // 对结果值进行排序
                            rangePriceVoList.sort(Comparator.comparing(RangePriceVo::getPkRange));
                        }
                    }
                } else {
                    // 极差等级
                    for (BdRangeExt bdRangeExt : rangeList) {
                        RangePriceVo rangePriceVo = new RangePriceVo();
                        rangePriceVo.setPkProduct(computeWaresPrice.getPkProduct());
                        if (bdRangeExt.getMoneyRatio() != null && computeWaresPrice.getProductPrice() != null) {
                            rangePriceVo.setPrice(bdRangeExt.getMoneyRatio().multiply(computeWaresPrice.getProductPrice()).divide(bfb));
                        } else {
                            rangePriceVo.setPrice(BigDecimal.ZERO);
                        }
                        if (bdRangeExt.getAchieveRatio() != null && computeWaresPrice.getProductPv() != null) {
                            rangePriceVo.setAchieve(bdRangeExt.getAchieveRatio().multiply(computeWaresPrice.getProductPv()).divide(bfb));
                        } else {
                            rangePriceVo.setAchieve(BigDecimal.ZERO);
                        }
                        rangePriceVo.setWaresSpecsList(waresSpecsList);
                        rangePriceVo.setAssAchieve(computeWaresPrice.getProductBv());
                        rangePriceVo.setPkRange(bdRangeExt.getPkId());
                        rangePriceVo.setRangeName(bdRangeExt.getRangeName());
                        rangePriceVo.setIsGift(computeWaresPrice.getIsGift());
                        rangePriceVo.setProductCode(computeWaresPrice.getProductCode());
                        rangePriceVo.setProductName(computeWaresPrice.getProductName());
                        rangePriceVo.setProductCover(computeWaresPrice.getProductCover());
                        rangePriceVo.setSpecsNames(StringUtils.join(specsNames, ","));
                        rangePriceVoList.add(rangePriceVo);
                    }
                }
                computeWaresPrice.setRangePriceVoList(rangePriceVoList);
            }
        }
        return computeWaresPriceList;
    }

    @Override
    public Map<Integer, List<BdWaresAuthority>> getWaresAuthority(List<Integer> pkWaresList) {
        Map<Integer, List<BdWaresAuthority>> map = new HashMap<>();
        if (pkWaresList.size() > 0) {
            LambdaQueryWrapper<BdWaresAuthority> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(BdWaresAuthority::getPkWares, pkWaresList);
            // 只查询不为全部的，全部的话默认都是可见的
            queryWrapper.ne(BdWaresAuthority::getAuthorityType, EWaresPermissionType.AUTH_ORITY_TYPE.getValue());
            List<BdWaresAuthority> waresAuthorityList = iBdWaresAuthorityService.list(queryWrapper);
            map = waresAuthorityList.stream().collect(Collectors.groupingBy(BdWaresAuthority::getPkWares, Collectors.toList()));
        }
        return map;
    }

    /**
     * 查询推荐商品
     *
     * @param pkCountry
     * @return
     */
    private List<BdWaresExt> selectByRecommentList(Integer pkCountry, List<Integer> specialAreaList) {
        // 查询推荐商品
        return baseMapper.selectByRecommentList(pkCountry, specialAreaList);
    }

    @Override
    public WaresAuthorityVo getWaresAuthorityFirst(Integer pkWares) {
        return baseMapper.getWaresAuthorityFirst(pkWares);
    }

    @Override
    public void bottomUp(Integer waresId, LoginUser loginUser) {
        BdWares bdWares = new BdWares();
        bdWares.setSortStatus(-1);
        bdWares.setPkId(waresId);
        this.updateById(bdWares);
    }

    @Override
    public List<BdWaresExt> listWares(IndexWaresParam param) {
        return baseMapper.listWaresNew(param);

    }

}
