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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
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.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.base.CuMember;
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.wares.*;
import com.hzs.common.domain.system.config.*;
import com.hzs.common.domain.system.config.ext.BdRangeExt;
import com.hzs.member.base.IMemberServiceApi;

import com.hzs.retail.wares.param.RetailWaresParam;
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.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.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.stream.Collectors;

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

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IBdSpecsService specsService;
    @Autowired
    private IBdWaresAuthorizeService waresAuthorizeService;
    @Autowired
    private IBdWaresAwardsService waresAwardsService;
    @Autowired
    private IBdWaresGradeService waresGradeService;
    @Autowired
    private IBdWaresSpecsRelationService waresSpecsRelationService;
    @Autowired
    private IBdWaresSpecsPackService waresSpecsPackService;
    @Autowired
    private IBdWaresSpecsSkuService waresSpecsSkuService;
    @Autowired
    private IBdWaresSpecsService waresSpecsService;
    @Autowired
    private IBdWaresExtendService waresExtendService;
    @Autowired
    private IBdWaresRangeService waresRangeService;
    @Autowired
    private IBdWaresDetailService waresDetailService;
    @Autowired
    private IBdWaresLabelService waresLabelService;
    @Autowired
    private IBdWaresAuthorityService waresAuthorityService;

    @DubboReference
    ILabelServiceApi iLabelServiceApi;
    @DubboReference
    IMemberServiceApi iMemberServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    IRangeServiceApi iRangeServiceApi;

    @Override
    public int getMaxSortNum() {
        Integer maxSort = this.getMaxSort(SecurityUtils.getPkCountry());
        if(ObjectUtil.isNotEmpty(maxSort)){
            return maxSort + 1;
        }
        return  1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BdWares saveWares(WaresParams waresParams, LoginUser user) {
        // 设置 wares 对象的值
        BdWares wares = BeanUtil.copyProperties(waresParams, BdWares.class);
        wares.setPkId(waresParams.getWaresId());
        wares.setWaresCode(waresParams.getWaresCode());
        wares.setPkCreator(user.getUserId());
        wares.setPkCountry(user.getDataCountry());
        wares.setSystemType(user.getSystemType());
        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);
        waresExtend.setSystemType(user.getSystemType());
        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());
            }
        }
        waresExtendService.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) {
                waresGradeService.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);
            }
            waresAwardsService.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) {
                waresAuthorizeService.saveBatch(waList);
            }
        }
        return wares;
    }

    /**
     * 所有标签生成记录
     *
     * @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);
            }
        }
        waresLabelService.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 = waresDetailService.getOne(queryWrapper);
                if (waresDetail != null) {
                    // 根据详情外键查询所有规格明细值
                    LambdaQueryWrapper<BdWaresSpecsRelation> specsWrapper = new LambdaQueryWrapper<>();
                    specsWrapper.eq(BdWaresSpecsRelation::getPkWaresDetail, waresDetail.getPkId());
                    List<BdWaresSpecsRelation> relationList = waresSpecsRelationService.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 = waresSpecsService.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) {
                waresRangeService.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);

        }
        waresAuthorityService.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 = waresDetailService.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());
                waresSpecsSkuService.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());
                    waresSpecsService.save(waresSpecs);
                    // 生成规格明细关系表
                    BdWaresSpecsRelation waresSpecsRelation = new BdWaresSpecsRelation();
                    waresSpecsRelation.setCreationTime(new Date());
                    waresSpecsRelation.setPkWaresDetail(waresDetailId);
                    waresSpecsRelation.setPkWaresSpecs(waresSpecs.getPkId());
                    waresSpecsRelation.setPkWaresSpecsSku(bdWaresSpecsSku.getPkId());
                    waresSpecsRelationService.save(waresSpecsRelation);
                }
            } else {
                // 如果sku id 非空 表示在当前数据中修改
                BdWaresSpecsSku bdWaresSpecsSku = waresSpecsSkuService.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 = waresDetailService.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());
                    waresSpecsService.save(waresSpecs);
                    // 生成规格明细关系表
                    BdWaresSpecsRelation waresSpecsRelation = new BdWaresSpecsRelation();
                    waresSpecsRelation.setCreationTime(new Date());
                    waresSpecsRelation.setPkWaresDetail(waresDetailId);
                    waresSpecsRelation.setPkWaresSpecs(waresSpecs.getPkId());
                    waresSpecsRelation.setPkWaresSpecsSku(bdWaresSpecsSku.getPkId());
                    waresSpecsRelationService.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());
                }
                waresSpecsSkuService.updateBySkuId(sku);
            }
        }
    }

    /**
     * 新增产品明细表
     */
    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) {
            waresDetailService.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);
            }
            waresSpecsPackService.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());
        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
        waresExtendService.updatePutOnTimeAndPutOffTimeByWaresId(waresParams.getWaresId(), waresParams.getPutOnTime(), waresParams.getPutOffTime());

        // 商品拓展表
        BdWaresExtend waresExtend = BeanUtil.copyProperties(waresParams, BdWaresExtend.class);
        waresExtend.setSystemType(user.getSystemType());
        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());
            }
        }

        waresExtendService.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);
        // 生成商品级差
        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());
            waresGradeService.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());
                waresGradeService.save(bdWaresGrade);
            }
        }
        // 奖衔
        if (waresParams.getWaresAwardsIds() != null) {
            LambdaQueryWrapper<BdWaresAwards> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(BdWaresAwards::getPkWares, wares.getPkId());
            waresAwardsService.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());
                waresAwardsService.save(bdWaresAwards);
            }
        }

        // 用户权限配置
        if (waresParams.getWaresMemberAuthorizeList() != null) {
            List<BdWaresAuthorize> waList = new ArrayList<>();
            waresAuthorizeService.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) {
                waresAuthorizeService.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());
        waresLabelService.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());
        waresSpecsSkuService.update(waresSpecsSkuWrapper);

        // 删除规格关联数据
        LambdaQueryWrapper<BdWaresDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdWaresDetail::getPkWares, waresId);
        List<BdWaresDetail> waresDetailList = waresDetailService.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());
            waresSpecsService.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());
            waresSpecsRelationService.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());
        waresAuthorityService.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());
        waresDetailService.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());
        waresRangeService.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());
        waresSpecsPackService.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());
        waresExtendService.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());
        waresAuthorityService.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());
        waresLabelService.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());
        waresRangeService.update(waresRangeWrapper);
        // 删除规格明细
        LambdaQueryWrapper<BdWaresDetail> detailWrapper = new LambdaQueryWrapper<>();
        detailWrapper.eq(BdWaresDetail::getPkWares, pkId);
        List<BdWaresDetail> list = waresDetailService.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());
            waresSpecsService.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());
        waresDetailService.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());
        waresSpecsPackService.update(waresSpecsPackWrapper);
        // 删除sku
        LambdaQueryWrapper<BdWaresSpecsSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BdWaresSpecsSku::getPkWares, pkId);
        List<BdWaresSpecsSku> waresSpecsSkuList = waresSpecsSkuService.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());
            waresSpecsRelationService.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());
        waresSpecsSkuService.update(waresSpecsSkuWrapper);
        if (wares != null) {
            createDeleteWaresLog(wares, EApprovalBusiness.WARES_REMOVE.getValue(), loginUser);
        }
    }

    @Override
    public BdWares getWares(Integer waresId) {
        return baseMapper.selectById(waresId);
    }

    @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 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, Integer specialArea) {
        // 极差
        R<List<BdRangeExt>> rangeDto = iRangeServiceApi.queryRange(SecurityUtils.getPkCountry());
        List<BdRangeExt> rangeList = rangeDto.getData();
        rangeList = rangeList.stream().filter(range -> range.getSystemType().equals(ESystemType.DEFAULT.getValue())).collect(Collectors.toList());
        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 = specsService.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 = waresSpecsRelationService.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);
                        }
                    }
                } 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);
                    }
                }
                // 对结果值进行排序
                rangePriceVoList.sort(Comparator.comparing(RangePriceVo::getPkRange));
                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);
            List<BdWaresAuthority> waresAuthorityList = waresAuthorityService.list(queryWrapper);
            map = waresAuthorityList.stream().collect(Collectors.groupingBy(BdWaresAuthority::getPkWares, Collectors.toList()));
        }
        return map;
    }

    @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> listRetailWaresByCondition(RetailWaresParam param) {
        return baseMapper.listRetailWaresByCondition(param);
    }

    @Override
    public List<Integer> listBoxProduct(List<String> boxWaresList) {
        return baseMapper.listBoxProduct(boxWaresList, null, null).stream().map(BdWaresDetail::getPkProduct).collect(Collectors.toList());
    }

    @Override
    public List<BdWaresDetail> listBoxProductAndWares(List<String> boxWaresList, Integer pkProduct, Integer specialArea) {
        return baseMapper.listBoxProduct(boxWaresList, pkProduct, specialArea);
    }

    @Override
    public List<String> listWaresCodeByVertex(Long pkVertex) {
        return baseMapper.listWaresCodeByVertex(pkVertex);
    }

    @Override
    public List<BdWaresExt> listWaresNoSale(WaresNoSaleParam param) {
        return baseMapper.listWaresNoSale(param);
    }

}
