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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.sale.classify.BdSpecs;
import com.hzs.common.domain.sale.ext.BdWaresExt;
import com.hzs.common.domain.sale.ext.BdWaresInfoExt;
import com.hzs.common.domain.sale.modifyRecord.BdModifyRecord;
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.common.domain.system.sys.SysUser;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.base.IMemberServiceApi;

import com.hzs.sale.modifyrecord.service.IBdModifyRecordService;
import com.hzs.sale.product.service.IBdSpecsService;
import com.hzs.sale.util.OrderUtil;
import com.hzs.sale.util.WaresSpecialUtil;
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.ITransactionServiceApi;
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.IUserServiceApi;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
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;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author hzs
 * @since 2022-09-08
 */
@Service
public class BdWaresServiceImpl extends ServiceImpl<BdWaresMapper, BdWares> implements IBdWaresService {

    @DubboReference
    IMenuDetailServiceApi iBdMenuDetailService;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;
    @DubboReference
    IRangeServiceApi rangeServiceApi;
    @DubboReference
    IUserServiceApi userServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;
    @DubboReference
    ILabelServiceApi labelService;
    @DubboReference
    ITransactionServiceApi transactionServiceApi;

    @Autowired
    private IBdSpecsService specsService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private IBdWaresAuthorizeService waresAuthorizeService;
    @Autowired
    private IBdWaresAwardsService waresAwardsService;
    @Autowired
    private IBdWaresGradeService waresGradeService;
    @Autowired
    private IBdModifyRecordService modifyRecordService;
    @Autowired
    private IBdWaresSpecsRelationService waresSpecsRelationService;
    @Autowired
    private IBdWaresSpecsPackService waresSpecsPackService;
    @Autowired
    private IBdWaresService waresService;
    @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;

    private RedisService redisService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @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 = transactionServiceApi.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());
        waresService.save(wares);
        // 商品拓展表
        BdWaresExtend waresExtend = BeanUtil.copyProperties(waresParams, BdWaresExtend.class);
        waresExtend.setPkWares(wares.getPkId());
        waresExtend.setPkCreator(user.getUserId());
        waresExtend.setCreationTime(new Date());
        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);
        // 生成 极差配置
//        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) {

            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) {
            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());
                waresAwardsService.save(bdWaresAwards);
            }
        }
        // 用户权限配置
        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) {
        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());

                QueryWrapper<BdWaresDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PK_WARES", wares.getPkId());
                queryWrapper.eq("PK_PRODUCT", waresRangeParams.getPkProduct());
                // 查询当前商品详情id
                BdWaresDetail waresDetail = waresDetailService.getOne(queryWrapper);
                if (waresDetail != null) {

                    // 根据详情外键查询所有规格明细值
                    QueryWrapper<BdWaresSpecsRelation> specsWrapper = new QueryWrapper<>();
                    specsWrapper.eq("PK_WARES_DETAIL", 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());
                        // for (BdWaresSpecsRelation waresSpecsRelation : integer.getValue()) {

                        QueryWrapper<BdWaresSpecs> listWrapper = new QueryWrapper<>();
                        listWrapper.in("PK_ID", 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());
                    waresRangeService.save(bdWaresRange);
                }

            }
        }

    }

    /**
     * 生成特殊明细表
     *
     * @param wares
     */

    private void saveWaresAuthority(BdWares wares, List<WaresAuthorityParam> waresAuthorityList, LoginUser user) {
        for (WaresAuthorityParam waresAuthorityParam : waresAuthorityList) {
            Long memberId = null;
            if (StringUtils.isNotBlank(waresAuthorityParam.getMemberCode())) {
                R<CuMember> member = memberServiceApi.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());
            waresAuthorityService.save(bdWaresAuthority);
        }
    }

    /**
     * 生成规格明细表
     *
     * @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查询
                QueryWrapper<BdWaresDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PK_WARES", wares.getPkId());
                queryWrapper.eq("PK_PRODUCT", waresSpecsSkuParams.getPkProduct());
                if (waresSpecsSkuParams.getIsGift() != null) {
                    queryWrapper.eq("IS_GIFT", 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());
                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查询
                QueryWrapper<BdWaresDetail> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PK_WARES", wares.getPkId());
                queryWrapper.eq("PK_PRODUCT", waresSpecsSkuParams.getPkProduct());
                if (waresSpecsSkuParams.getIsGift() != null) {
                    queryWrapper.eq("IS_GIFT", 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.setSpecCover(waresSpecsSkuParams.getSpecCover());
                if (waresSpecsSkuParams.getIsPutOn() != null) {
                    sku.setIsPutOn(waresSpecsSkuParams.getIsPutOn());
                } else {
                    sku.setIsPutOn(EYesNo.YES.getIntValue());
                }
                waresSpecsSkuService.updateBySkuId(sku);
                redisService.deleteObject(CacheConstants.BD_WARES_SPECS_RELATION + bdWaresSpecsSku.getPkId());
            }
        }
    }

    /**
     * 新增产品明细表
     */
    private void saveWaresDetail(BdWares wares, List<WaresDetailParams> list, LoginUser user) {
        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());
            waresDetailService.save(bdWaresDetail);
        }

    }

    /**
     * 新增产品包装
     *
     * @param wares
     * @param waresSpecsPackList
     */
    private void saveWaresSpecsPack(BdWares wares, List<WaresSpecsPackParams> waresSpecsPackList) {
        // 产品规格和包装表
        for (WaresSpecsPackParams waresSpecsPackParams : waresSpecsPackList) {
            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());
                waresSpecsPackService.save(bdWaresSpecsPack);
            }

        }
    }

    /**
     * 修改商品基础信息
     *
     * @param waresParams
     * @param user
     */
    @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 = transactionServiceApi.createTransaction(user.getDataCountry(), ETransactionKey.SPEC, waresParams.getWaresName(), EYesNo.NO, EYesNo.NO);
        wares.setPkTransaction(transaction.getData());
        waresService.updateById(wares);
        // 设置 上架时间 和下架时间 putOnTime  putOffTime
        waresExtendService.updatePutOnTime(waresParams.getWaresId());
        waresExtendService.updatePutOffTime(waresParams.getWaresId());

        // 商品拓展表
        BdWaresExtend waresExtend = BeanUtil.copyProperties(waresParams, BdWaresExtend.class);
        waresExtend.setPkWares(wares.getPkId());
        waresExtend.setPkModified(user.getUserId());
        waresExtend.setModifiedTime(new Date());
        // 根据商品id 修改信息
        QueryWrapper<BdWaresExtend> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_WARES", 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);
        // 生成 极差配置
//        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) {
            QueryWrapper<BdWaresGrade> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("PK_WARES", 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) {
            // IBdWaresAwardsService
            QueryWrapper<BdWaresAwards> queryWrapper1 = new QueryWrapper<BdWaresAwards>();
            queryWrapper1.eq("PK_WARES", wares.getPkId());
            waresAwardsService.remove(queryWrapper1);
            // 校验奖衔id 是否存在
            R<List<BdAwards>> awardsDto = awardsServiceApi.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) {
        // 标签关联记录 删除
        UpdateWrapper<BdWaresLabel> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("PK_WARES", waresId);
        deleteWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        deleteWrapper.set("MODIFIED_TIME", new Date());
        waresLabelService.update(deleteWrapper);

        // 删除规格
        UpdateWrapper<BdWaresSpecsSku> waresSpecsSkuWrapper = new UpdateWrapper<>();
        waresSpecsSkuWrapper.eq("PK_WARES", waresId);
        waresSpecsSkuWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresSpecsSkuWrapper.set("MODIFIED_TIME", new Date());
        waresSpecsSkuService.update(waresSpecsSkuWrapper);

        // 删除规格关联数据
        QueryWrapper<BdWaresDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_WARES", waresId);
        List<BdWaresDetail> waresDetailList = waresDetailService.list(queryWrapper);
        for (BdWaresDetail bdWaresDetail : waresDetailList) {
            // 删除商品关联规格
            UpdateWrapper<BdWaresSpecs> waresSpecsWrapper = new UpdateWrapper<>();
            waresSpecsWrapper.eq("PK_WARES_DETAIL", bdWaresDetail.getPkId());
            waresSpecsWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
            waresSpecsWrapper.set("MODIFIED_TIME", new Date());
            waresSpecsService.update(waresSpecsWrapper);
            // 删除规格关联数据
            UpdateWrapper<BdWaresSpecsRelation> waresSpecsRelationWrapper = new UpdateWrapper<>();
            waresSpecsRelationWrapper.eq("PK_WARES_DETAIL", bdWaresDetail.getPkId());
            waresSpecsRelationWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
            waresSpecsRelationWrapper.set("MODIFIED_TIME", new Date());
            waresSpecsRelationService.update(waresSpecsRelationWrapper);
        }
        // 删除产品关联团队配置
        UpdateWrapper<BdWaresAuthority> waresAuthorityWrapper = new UpdateWrapper<>();
        waresAuthorityWrapper.eq("PK_WARES", waresId);
        waresAuthorityWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresAuthorityWrapper.set("MODIFIED_TIME", new Date());
        waresAuthorityService.update(waresAuthorityWrapper);
        //删除产品明细
        UpdateWrapper<BdWaresDetail> waresDetailWrapper = new UpdateWrapper<>();
        waresDetailWrapper.eq("PK_WARES", waresId);
        waresDetailWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresDetailWrapper.set("MODIFIED_TIME", new Date());
        waresDetailService.update(waresDetailWrapper);
        // 删除极差明细
        UpdateWrapper<BdWaresRange> waresRangeWrapper = new UpdateWrapper<>();
        waresRangeWrapper.eq("PK_WARES", waresId);
        waresRangeWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresRangeWrapper.set("MODIFIED_TIME", new Date());
        waresRangeService.update(waresRangeWrapper);
        // 删除包装和规格
        UpdateWrapper<BdWaresSpecsPack> waresSpecsPackWrapper = new UpdateWrapper<>();
        waresSpecsPackWrapper.eq("PK_WARES", waresId);
        waresSpecsPackWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresSpecsPackWrapper.set("MODIFIED_TIME", new Date());
        waresSpecsPackService.update(waresSpecsPackWrapper);
    }

    /**
     * 删除商品
     *
     * @param pkId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeWares(Integer pkId) {
        Long userId = SecurityUtils.getUserId();
        UpdateWrapper<BdWares> waresWrapper = new UpdateWrapper<>();
        waresWrapper.eq("PK_ID", pkId);
        waresWrapper.set("PK_MODIFIED", userId);
        waresWrapper.set("MODIFIED_TIME", new Date());
        waresWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresService.update(waresWrapper);
        // 删除商品拓展表
        UpdateWrapper<BdWaresExtend> waresExpendWrapper = new UpdateWrapper<>();
        waresExpendWrapper.eq("PK_WARES", pkId);
        waresExpendWrapper.set("PK_MODIFIED", userId);
        waresExpendWrapper.set("MODIFIED_TIME", new Date());
        waresExpendWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresExtendService.update(waresExpendWrapper);

        // 删除
        UpdateWrapper<BdWaresAuthority> waresAuthorityWrapper = new UpdateWrapper<>();
        waresAuthorityWrapper.eq("PK_WARES", pkId);
        waresAuthorityWrapper.set("PK_MODIFIED", userId);
        waresAuthorityWrapper.set("MODIFIED_TIME", new Date());
        waresAuthorityWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresAuthorityService.update(waresAuthorityWrapper);
        //删除标签管理
        UpdateWrapper<BdWaresLabel> waresLabelWrapper = new UpdateWrapper<>();
        waresLabelWrapper.eq("PK_WARES", pkId);
        waresLabelWrapper.set("PK_MODIFIED", userId);
        waresLabelWrapper.set("MODIFIED_TIME", new Date());
        waresLabelWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresLabelService.update(waresLabelWrapper);
        // 删除极差
        UpdateWrapper<BdWaresRange> waresRangeWrapper = new UpdateWrapper<>();
        waresRangeWrapper.eq("PK_WARES", pkId);
        waresRangeWrapper.set("PK_MODIFIED", userId);
        waresRangeWrapper.set("MODIFIED_TIME", new Date());
        waresRangeWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresRangeService.update(waresRangeWrapper);
        // 删除规格明细
        QueryWrapper<BdWaresDetail> detailWrapper = new QueryWrapper<>();
        detailWrapper.eq("PK_WARES", pkId);
        List<BdWaresDetail> list = waresDetailService.list(detailWrapper);
        for (BdWaresDetail bdWaresDetail : list) {
            UpdateWrapper<BdWaresSpecs> waresSpecsWrapper = new UpdateWrapper<>();
            waresSpecsWrapper.eq("PK_WARES_DETAIL", bdWaresDetail.getPkId());
            waresSpecsWrapper.set("PK_MODIFIED", userId);
            waresSpecsWrapper.set("MODIFIED_TIME", new Date());
            waresSpecsWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
            waresSpecsService.update(waresSpecsWrapper);
        }
        // 删除商品明细表
        UpdateWrapper<BdWaresDetail> waresDetailWrapper = new UpdateWrapper<>();
        waresDetailWrapper.eq("PK_WARES", pkId);
        waresDetailWrapper.set("PK_MODIFIED", userId);
        waresDetailWrapper.set("MODIFIED_TIME", new Date());
        waresDetailWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresDetailService.update(waresDetailWrapper);
        // 删除规格和包装
        UpdateWrapper<BdWaresSpecsPack> waresSpecsPackWrapper = new UpdateWrapper<>();
        waresSpecsPackWrapper.eq("PK_WARES", pkId);
        waresSpecsPackWrapper.set("PK_MODIFIED", userId);
        waresSpecsPackWrapper.set("MODIFIED_TIME", new Date());
        waresSpecsPackWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresSpecsPackService.update(waresSpecsPackWrapper);
        // 删除sku
        QueryWrapper<BdWaresSpecsSku> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PK_WARES", pkId);
        List<BdWaresSpecsSku> waresSpecsSkuList = waresSpecsSkuService.list(queryWrapper);
        for (BdWaresSpecsSku bdWaresSpecsSku : waresSpecsSkuList) {
            UpdateWrapper<BdWaresSpecsRelation> waresSpecsRelationWrapper = new UpdateWrapper<>();
            waresSpecsRelationWrapper.eq("PK_WARES_SPECS_SKU", bdWaresSpecsSku.getPkId());
            waresSpecsRelationWrapper.set("PK_MODIFIED", userId);
            waresSpecsRelationWrapper.set("MODIFIED_TIME", new Date());
            waresSpecsRelationWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
            waresSpecsRelationService.update(waresSpecsRelationWrapper);
        }

        UpdateWrapper<BdWaresSpecsSku> waresSpecsSkuWrapper = new UpdateWrapper<>();
        waresSpecsSkuWrapper.eq("PK_WARES", pkId);
        waresSpecsSkuWrapper.set("PK_MODIFIED", userId);
        waresSpecsSkuWrapper.set("MODIFIED_TIME", new Date());
        waresSpecsSkuWrapper.set("DEL_FLAG", EDelFlag.DELETE.getValue());
        waresSpecsSkuService.update(waresSpecsSkuWrapper);
    }

    @Override
    public BdWaresExt queryWaresByCondition(Integer specialArea, String waresCode) {
        BdWaresExt bdWaresExt = redisService.getCacheObject(CacheConstants.BD_WARES + specialArea + waresCode);
        if (bdWaresExt == null) {
            List<BdWaresExt> bdWaresExtList = baseMapper.queryWaresByCondition(WaresSpecialUtil.getWaresSpecial(specialArea), null, waresCode, null, null);
            if (bdWaresExtList != null && bdWaresExtList.size() > 0) {
                bdWaresExt = bdWaresExtList.get(0);
                redisService.setCacheObject(CacheConstants.BD_WARES + specialArea + waresCode, bdWaresExt);
            }
        }
        return bdWaresExt;
    }

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

    /**
     * 根据商品外键查询商品
     *
     * @param waresId
     * @return
     */
    @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;
    }

    /**
     * 查询最末商品编号
     *
     * @return
     */
    @Override
    public String getLastWaresCode() {
        return baseMapper.getLastWaresCode();
    }

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

    /**
     * 上移 下移
     *
     * @param waresId
     * @param waresMoveType
     */
    @Override
    public void waresMove(Integer waresId, Integer waresMoveType) {
        if (waresMoveType == EProductMoveType.MOVEUP.getIntValue()) {
            Integer sort = baseMapper.selectByMoveUpSort(waresId);
            if (sort != null) {
                Integer maxSort = sort + 1;
                // 查询该排序号码是否重复
                QueryWrapper<BdWares> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SORT", maxSort);
                int count = waresService.count(queryWrapper);
                if (count > 0) {
                    baseMapper.updateMoveUpBySort(maxSort);
                    UpdateWrapper<BdWares> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_ID", waresId);
                    updateWrapper.set("SORT", maxSort);
                    waresService.update(updateWrapper);
                } else {
                    UpdateWrapper<BdWares> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_ID", waresId);
                    updateWrapper.set("SORT", maxSort);
                    waresService.update(updateWrapper);
                }
            }
        } else if (waresMoveType == EProductMoveType.MOVEDOWN.getIntValue()) {
            Integer sort = waresService.selectByMoveDownSort(waresId);
            if (sort != null) {
                Integer minSort = sort - 1;
                // 查询该排序号码是否重复
                QueryWrapper<BdWares> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("SORT", minSort);
                int count = waresService.count(queryWrapper);
                if (count > 0) {
                    baseMapper.updateMoveDownBySort(minSort);
                    UpdateWrapper<BdWares> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_ID", waresId);
                    updateWrapper.set("SORT", minSort);
                    waresService.update(updateWrapper);
                } else {
                    UpdateWrapper<BdWares> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_ID", waresId);
                    updateWrapper.set("SORT", minSort);
                    waresService.update(updateWrapper);
                }
            }
        }

    }

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

    @Override
    public void floatingRoof(Integer waresId) {
        // 查询排序最大值
        Integer sort = baseMapper.selectMaxSort();
        UpdateWrapper<BdWares> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PK_ID", waresId);
        updateWrapper.set("SORT", sort + 1);
        waresService.update(updateWrapper);
    }

    /**
     * 新增商品记录添加审核
     *
     * @param waresParams
     * @param loginUser
     */
    @Override
    public void saveWaresModifyRecord(WaresParams waresParams, LoginUser loginUser, Integer modifyRecordTypeValue) {
        // 生成新增日志记录
        R<SysUser> user = userServiceApi.selectUserById(SecurityUtils.getUserId());
        BdModifyRecord modifyRecord = BdModifyRecord.builder().newValue(JSONUtil.toJsonStr(waresParams))
                .auditStatus(EModifyRecordStatus.CHECK_PENDING.getValue())
                .pkCountry(loginUser.getDataCountry())
                .pkCreator(loginUser.getUserId())
                .type(modifyRecordTypeValue)
                .creationTime(new Date())
                .name(waresParams.getWaresName())
                .code(waresParams.getWaresCode())
                .creatorName(SecurityUtils.getUsername())
                .pkCreationDept(user.getData().getPkDept())
                .creationDeptName(user.getData().getDeptName())
                .pkCreator(SecurityUtils.getUserId())
                .build();
        modifyRecordService.save(modifyRecord);
    }

    @Override
    public void updateWaresModifyRecord(WaresParams waresParams, LoginUser loginUser) {
        // 生成修改日志记录
        BdModifyRecord modifyRecord = BdModifyRecord.builder().newValue(JSONUtil.toJsonStr(waresParams))
                .auditStatus(EModifyRecordStatus.CHECK_PENDING.getValue())
                .type(EModifyRecordType.WARES_UPDATE.getValue())
                .creationTime(new Date())
                .pkWares(waresParams.getWaresId())
                .pkCreator(SecurityUtils.getUserId())
                .build();
        modifyRecordService.save(modifyRecord);
    }

    /**
     * 获取最大商品序号
     *
     * @return
     */
    @Override
    public Integer getMaxSort(Integer pkCountry) {
        return baseMapper.getMaxSort(pkCountry);
    }

    /**
     * 根据商品编号查询商品信息
     *
     * @param waresCodeList
     * @return
     */
    @Override
    public List<BdAgreement> selectByWaresCodeList(List<String> waresCodeList) {
        return baseMapper.selectByWaresCodeList(waresCodeList);
    }

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

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

    /**
     * 根据条件查询推荐商品 ，专区商品列表
     *
     * @param specialArea    所属专区
     * @param pkAreaClassify 所属分类
     * @param waresName      名称
     * @param pkCountry      所属国家
     * @return: List<BdWaresExt>
     * @Author: sui q
     * @Date: 2022/9/19 9:05
     */
    @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 = labelService.getByPkId(pkId);
        if (result.isSuccess()) {
            bdLabel = BeanUtil.copyProperties(result.getData(), BdLabel.class);
        } else {
            bdLabel = new BdLabel();
        }
        return bdLabel;
    }

    /**
     * 查询存在推荐的专区
     *
     * @return
     */
    @Override
    public List<Integer> queryRecommendWaresSpecialAndWaresInfo() {
        return baseMapper.queryRecommendWaresSpecial();
    }

    /**
     * 查询app 首页推荐专区 和推荐商品
     */
    @Override
    public RecommendWaresInfoVo queryRecommendInfo(Integer pkCountry, String memberCode, Map<Integer, Boolean> waresShowMap) {
        //登录用户
        R<CuMember> loginMemberDto = memberServiceApi.getMember(memberCode);
        CuMember loginMember = loginMemberDto.getData();

        // 查询配置菜单列表
        // 结算等级
        int pkGrade = loginMember.getPkSettleGrade();
        // 真实奖衔
        int pkAwards = loginMember.getPkAwards();
        // 注册权限
        int authority = loginMember.getRegisterAuthority();
        // 查询权限配置
        R<List<BdMenuDetail>> menuDetailListDto = iBdMenuDetailService.showMenuDetail(pkGrade, pkAwards, authority, pkCountry);
        List<BdMenuDetail> menuDetailList = menuDetailListDto.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;
        }

        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ESpecialArea.values());

        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();
                    recommendSpecialAreaVo.setSpecialArea(specialArea);
                    recommendSpecialAreaVo.setSort(sarea.getSort());
                    String label = transactionMap.get(sarea.getKey());
                    if (StringUtils.isNotBlank(label)) {
                        recommendSpecialAreaVo.setSpecialAreaName(label);
                    } else {
                        recommendSpecialAreaVo.setSpecialAreaName(sarea.getLabel());
                    }

                    QueryWrapper<BdWares> qe = new QueryWrapper<>();
                    qe.eq("SPECIAL_AREA", specialArea);
                    qe.eq("IS_RECOMMEND", EYesNo.YES.getIntValue());
                    qe.eq("PK_COUNTRY", pkCountry);
                    List<BdWares> waresList = this.queryByRecommendList(specialArea, EYesNo.YES.getIntValue(), pkCountry, waresShowMap);
                    List<BdWares> filterList = new ArrayList<>();
                    if (waresList.size() > 2) {
                        filterList.add(waresList.get(0));
                        filterList.add(waresList.get(1));
                    } else {
                        filterList.addAll(waresList);
                    }
                    List<WaresVo> waresVoList = filterList.stream().map(wl -> {
                        WaresVo waresVo = new WaresVo();
                        waresVo.setPkWares(wl.getPkId());
                        waresVo.setWaresCode(wl.getWaresCode());
                        waresVo.setSpecialArea(wl.getSpecialArea());
                        waresVo.setCover1(wl.getCover1());
                        waresVo.setWaresPrice(wl.getWaresPrice());
                        return waresVo;
                    }).collect(Collectors.toList());
                    recommendSpecialAreaVo.setWaresList(waresVoList);
                    resultList.add(recommendSpecialAreaVo);

                    if (sarea.getValue() == ESpecialArea.REGISTER_AREA_FORM.getValue()
                            || sarea.getValue() == ESpecialArea.REGISTER_AREA_CONSUMPTION.getValue()) {
                        // 报单加盟，同步到累计消费专区
                        // 消费加盟，同步到商品消费专区
                        ESpecialArea tmpSpecialArea;
                        if (sarea.getValue() == ESpecialArea.REGISTER_AREA_CONSUMPTION.getValue()) {
                            tmpSpecialArea = ESpecialArea.UPGRADE_CONSUMPTION;
                        } else {
                            tmpSpecialArea = ESpecialArea.UPGRADE_FORM;
                        }

                        RecommendSpecialAreaVo tmpVO = new RecommendSpecialAreaVo();
                        tmpVO.setSpecialArea(tmpSpecialArea.getValue());
                        tmpVO.setSort(tmpSpecialArea.getSort());
                        String tmpLabel = transactionMap.get(tmpSpecialArea.getKey());
                        if (StringUtils.isNotBlank(tmpLabel)) {
                            tmpVO.setSpecialAreaName(tmpLabel);
                        } else {
                            tmpVO.setSpecialAreaName(tmpSpecialArea.getLabel());
                        }
                        List<WaresVo> tmpWaresVOList = filterList.stream().map(wl -> {
                            WaresVo waresVo = new WaresVo();
                            waresVo.setPkWares(wl.getPkId());
                            waresVo.setWaresCode(wl.getWaresCode());
                            waresVo.setSpecialArea(tmpSpecialArea.getValue());
                            waresVo.setCover1(wl.getCover1());
                            waresVo.setWaresPrice(wl.getWaresPrice());
                            return waresVo;
                        }).collect(Collectors.toList());
                        tmpVO.setWaresList(tmpWaresVOList);
                        resultList.add(tmpVO);
                    }
                }
            }
        }

        //  根据专区排序（按照指定排序排序: 注冊 升级 复购 自营 海粉 嗨粉）
        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 = waresGradeService.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<>();
        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;
                }
            }
            wsList.add(waresExt);
        }


        //商品区域图片轮播
        List<WaresCoverInfoVo> waresCoverInfoVoList = new ArrayList<>();
        // 推荐商品展示
        List<WaresVo> waresVoList = new ArrayList<>();
        List<BdWaresRange> bdWaresRangeList = new ArrayList<>();
        if (waresIdList.size() > 0) {
            bdWaresRangeList = waresRangeService.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();
                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.getPrice().multiply(BigDecimal.valueOf(bdWares.getQuantity()));
                }
                waresVo.setWaresPrice(OrderUtil.discountPrice(loginMember, bdWares.getSpecialArea(), price));
                waresVo.setSales(bdWares.getSales());
                waresVo.setWaresCode(bdWares.getWaresCode());
                waresVo.setSpecialArea(bdWares.getSpecialArea());
                waresVo.setPkWares(bdWares.getPkId());
                waresVoList.add(waresVo);
            }

        }
        recommendWaresInfoVo.setWaresVoList(waresVoList);
        recommendWaresInfoVo.setWaresCoverInfoList(waresCoverInfoVoList);
        return recommendWaresInfoVo;
    }

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

    /**
     * 修改自动上下架状态（自动上架）
     *
     * @param currentTime 当前时间
     */
    @Override
    public void updateByAutoStartAndAutoStart(Date currentTime) {
        baseMapper.updateByAutoStartAndAutoStart(currentTime);
    }

    /**
     * 修改自动上下架状态（自动下架）
     *
     * @param currentTime 当前时间
     */
    @Override
    public void updateByAutoStartAndAutoEnd(Date currentTime) {
        baseMapper.updateByAutoStartAndAutoEnd(currentTime);
    }

    /**
     * 查询推荐商品
     *
     * @param specialArea
     * @return
     */
    @Override
    public List<BdWares> queryRecommnedWares(Integer specialArea) {
        return baseMapper.queryRecommnedWares(specialArea);
    }

    /**
     * 计算商品业绩
     */
    @Override
    public List<ComputeWaresPrice> computeWaresPrice(List<ComputeWaresPrice> computeWaresPriceList) {
        // 极差
        R<List<BdRangeExt>> rangeDto = rangeServiceApi.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) {
                QueryWrapper<BdSpecs> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("PK_ID", 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);
                //    computeWaresPrice.setWaresSpecsList(waresSpecsList);
                // 极差等级
                for (BdRangeExt bdRangeExt : rangeList) {
                    RangePriceVo rangePriceVo = new RangePriceVo();
                    rangePriceVo.setPkProduct(computeWaresPrice.getPkProduct());
                    if (bdRangeExt.getMoneyRatio() != null && computeWaresPrice.getProductPrice() != null) {
                        rangePriceVo.setPrice(bdRangeExt.getMoneyRatio().divide(bfb).multiply(computeWaresPrice.getProductPrice()));
                    } else {
                        rangePriceVo.setPrice(BigDecimal.ZERO);
                    }
                    if (bdRangeExt.getAchieveRatio() != null && computeWaresPrice.getProductPv() != null) {
                        rangePriceVo.setAchieve(bdRangeExt.getAchieveRatio().divide(bfb).multiply(computeWaresPrice.getProductPv()));
                    } else {
                        rangePriceVo.setAchieve(BigDecimal.ZERO);
                    }
                    rangePriceVo.setWaresSpecsList(waresSpecsList);
                    rangePriceVo.setAssAchieve(computeWaresPrice.getProductBv());
                    rangePriceVo.setPkRange(bdRangeExt.getPkId());
                    rangePriceVo.setRangeName(bdRangeExt.getRangeName());
                    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;

    }

    /**
     * 查询商品团队信息
     *
     * @return
     */
    @Override
    public Map<Integer, List<BdWaresAuthority>> getWaresAuthority(List<Integer> pkWaresList) {
        Map<Integer, List<BdWaresAuthority>> map = new HashMap<>();
        if (pkWaresList.size() > 0) {
            QueryWrapper<BdWaresAuthority> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("PK_WARES", pkWaresList);
            List<BdWaresAuthority> waresAuthorityList = waresAuthorityService.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 BdWaresInfoExt selectWaresBySpecial(Integer specialArea, Integer pkCountry) {
        return baseMapper.selectWaresBySpecial(specialArea, pkCountry);
    }
}
