package com.hzs.sale.wares.controller.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.constant.msg.SaOrderMsgConstants;
import com.hzs.common.core.constant.msg.WaresMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.*;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.BdWaresExt;
import com.hzs.common.domain.sale.ext.BdWaresSpecsSkuExt;
import com.hzs.common.domain.sale.wares.*;
import com.hzs.common.domain.sale.wares.ext.WaresGradeAwards;
import com.hzs.common.domain.system.config.BdAgreement;
import com.hzs.common.domain.system.config.BdLabel;
import com.hzs.common.domain.system.ext.BdLabelExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.IMemberServiceApi;
import com.hzs.member.base.dto.ShowWaresDTO;
import com.hzs.sale.order.service.ISaOrderService;
import com.hzs.sale.shopping.service.IShoppingCartService;
import com.hzs.sale.shopping.vo.WaresItemWaresInfo;
import com.hzs.sale.wares.param.*;
import com.hzs.sale.wares.service.*;
import com.hzs.sale.wares.vo.*;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAreaCurrencyServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.AreaCurrencyDTO;
import com.hzs.system.config.dto.GradeDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 为会员端提供商品查询的入口
 */
@RestController
@RequestMapping("/api/wares")
@Slf4j
public class ApiBdWaresController extends BaseController {

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;
    @DubboReference
    IAreaCurrencyServiceApi areaCurrencyServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    @Autowired
    private IBdWaresLabelService waresLabelService;
    @Autowired
    private IBdWaresGradeService waresGradeService;
    @Autowired
    protected RedisService redisService;
    @Autowired
    protected StringRedisTemplate redisTemplate;
    @Autowired
    protected IShoppingCartService shoppingCartService;

    private IBdWaresService bdWaresService;

    private IBdWaresSpecsSkuService bdWaresSpecsSkuService;

    private IBdWaresRangeService bdWaresRangeService;

    private ISaOrderService saOrderService;

    @Autowired
    public void setSaOrderService(ISaOrderService saOrderService) {
        this.saOrderService = saOrderService;
    }

    @Autowired
    public void setBdWaresRangeService(IBdWaresRangeService bdWaresRangeService) {
        this.bdWaresRangeService = bdWaresRangeService;
    }

    @Autowired
    public void setBdWaresSpecsSkuService(IBdWaresSpecsSkuService bdWaresSpecsSkuService) {
        this.bdWaresSpecsSkuService = bdWaresSpecsSkuService;
    }

    @Autowired
    public void setBdWaresService(IBdWaresService bdWaresService) {
        this.bdWaresService = bdWaresService;
    }

    /**
     * 根据专区查找专区的商品
     *
     * @param cuWaresParams 专区、分类
     */
    @RequestMapping("/query-spe-wares")
    public AjaxResult queryWaresBySpecial(@RequestBody CuWaresParams cuWaresParams) {
        if (cuWaresParams.getSpecialArea() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }

        Integer pkCountry;
        if (cuWaresParams.getPkCountry() != null) {
            pkCountry = cuWaresParams.getPkCountry();
        } else {
            pkCountry = SecurityUtils.getPkCountry();
        }

        // 返回数据
        List<CuWaresParams> waresParamsList = new ArrayList<>();

        // 查询商品列表
        List<BdWaresExt> bdWaresExtList = bdWaresService.queryWaresByCondition(cuWaresParams.getSpecialArea(), cuWaresParams.getPkAreaClassify(), cuWaresParams.getWaresName(), null, null, pkCountry);

        if (CollectionUtil.isNotEmpty(bdWaresExtList)) {
            // 等级
            R<List<GradeDTO>> gradeDTO = gradeServiceApi.queryGradeList(pkCountry);
            List<GradeDTO> gradeList = gradeDTO.getData();
            Map<Integer, GradeDTO> gradeMap = gradeList.stream().filter(grade -> ESystemType.DEFAULT.getValue() == grade.getSystemType()).collect(Collectors.toMap(GradeDTO::getGradeValue, Function.identity()));

            // 当前会员ID
            Long userId = SecurityUtils.getUserId();
            CuMember cuMember = saOrderService.getCuMemberByKey(userId);
            // 当前会员编号
            String memberCode = cuMember.getMemberCode();

            // 汇率比例
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

            // 商品主键列表
            List<Integer> waresIdList = bdWaresExtList.stream().map(BdWares::getPkId).collect(Collectors.toList());
            // 检验商品团队信息
            Map<Integer, List<BdWaresAuthority>> waresAuthorityMap = bdWaresService.getWaresAuthority(waresIdList);
            List<ShowWaresDTO> showWaresList = bdWaresExtList.stream().map(we -> getShowWares(we.getPkId(), userId, memberCode, waresAuthorityMap)).collect(Collectors.toList());
            R<Map<Integer, Boolean>> waresShowMapDto = memberServiceApi.checkIsShowWares(showWaresList);
            Map<Integer, Boolean> waresShowMap = waresShowMapDto.getData();

            // 商品标签列表
            BdWaresLabel waresLabel = new BdWaresLabel();
            waresLabel.setPkIdList(waresIdList);
            List<BdLabelExt> list = waresLabelService.selectByList(waresLabel);

            // 标签
            for (BdWaresExt bdWaresExt : bdWaresExtList) {
                // 保证标签
                List<BdLabel> ensureLabelList = new ArrayList<>();
                // 卖点标签
                List<BdLabel> sellingLabelList = new ArrayList<>();

                for (BdLabelExt bdLabel : list) {

                    if (ELabelType.PREFIX.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 前缀标签
                        bdWaresExt.setPrefixLabelTarget(bdLabel);
                    }
                    if (ELabelType.COOL.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 酷炫标签
                        bdWaresExt.setCoolLabelTarget(bdLabel);
                    }
                    if (ELabelType.ENSURE.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 保证标签
                        ensureLabelList.add(bdLabel);
                    }
                    if (ELabelType.SELLING.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 卖点标签
                        sellingLabelList.add(bdLabel);
                    }
                }
                bdWaresExt.setEnsureLabelList(ensureLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
                bdWaresExt.setSellingLabelList(sellingLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
            }

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

            List<BdWaresSpecsSkuExt> waresSpecsSkuList = new ArrayList<>();
            if (waresIdList.size() > 0) {
                // 查询默认规格
                waresSpecsSkuList = bdWaresSpecsSkuService.selectByWaresSpecsSku(waresIdList);
            }

            List<BdWaresRange> bdWaresRangeList = new ArrayList<>();
            if (EOrderType.REPURCHASE_ORDER.getValue() == cuWaresParams.getSpecialArea()
                    || EOrderType.MALL_ORDER.getValue() == cuWaresParams.getSpecialArea()) {
                // 复购业绩计算
                if (waresIdList.size() > 0) {
                    bdWaresRangeList = bdWaresRangeService.queryWaresRangeByCondition(cuMember, waresIdList);
                }
            }
            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);
                });
            }

            // 海粉等级实体
            GradeDTO haiFanGradeDTO = gradeMap.get(EGrade.HAI_FAN.getValue());

            for (BdWaresExt waresExt : bdWaresExtList) {
                // 校验团队信息
                Boolean isShowWares = waresShowMap.get(waresExt.getPkId());
                if (null == isShowWares || !isShowWares) {
                    continue;
                }

                CuWaresParams waresParams = BeanUtil.copyProperties(waresExt, CuWaresParams.class);
                if (waresIdSet.contains(waresExt.getPkId())) {
                    String gradeKey = waresExt.getPkId() + "_" + ERangeType.GRADE.getValue() + "_" + cuMember.getPkSettleGrade();
                    String awardsKey = waresExt.getPkId() + "_" + ERangeType.AWARDS.getValue() + "_" + cuMember.getPkAwards();
                    //  添加商品注册权限配置
                    String authorityKey = waresExt.getPkId() + "_" + ERangeType.AUTHORITY.getValue() + "_" + cuMember.getRegisterAuthority();
                    if (!authWaresList.contains(gradeKey) && !authWaresList.contains(awardsKey) && !authWaresList.contains(authorityKey)) {
                        continue;
                    }
                }

                // 价格
                BigDecimal waresPrice = BigDecimal.ZERO;
                // 业绩
                BigDecimal waresAchieve = BigDecimal.ZERO;
                // bv
                BigDecimal assAchieve = BigDecimal.ZERO;
                // 会员价
                BigDecimal vipAchieve = BigDecimal.ZERO;
                // 零售价
                BigDecimal retailPrice = BigDecimal.ZERO;

                if (EOrderType.REPURCHASE_ORDER.getValue() == cuWaresParams.getSpecialArea()
                        || EOrderType.MALL_ORDER.getValue() == cuWaresParams.getSpecialArea()) {
                    for (BdWaresRange bdWaresRange : bdWaresRangeList) {
                        if (waresExt.getPkId().equals(bdWaresRange.getPkWares())) {
                            waresPrice = waresPrice.add(bdWaresRange.getPrice());
                            waresAchieve = waresAchieve.add(bdWaresRange.getAchieve());
                            assAchieve = assAchieve.add(bdWaresRange.getAssAchieve());
                        }
                    }
                } else {
                    List<BdWaresSpecsSkuExt> waresSpecsSku = waresSpecsSkuMap.get(waresExt.getPkId());
                    waresSpecsSku = waresSpecsSku.stream().peek(a -> a.setProductGift(a.getPkProduct() + "" + a.getIsGift())).collect(Collectors.toList());
                    Map<String, List<BdWaresSpecsSkuExt>> col = waresSpecsSku.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getProductGift));
                    for (Map.Entry<String, List<BdWaresSpecsSkuExt>> integerListEntry : col.entrySet()) {
                        // 取得每一个商品价格最小值
                        Optional<BdWaresSpecsSkuExt> minBdWaresSpecsSkuExt = integerListEntry.getValue().stream().filter(Objects::nonNull).min(Comparator.comparing(BdWaresSpecsSkuExt::getPrice));
                        BdWaresSpecsSkuExt bdWaresSpecsSkuExt = minBdWaresSpecsSkuExt.get();
                        waresPrice = waresPrice.add(bdWaresSpecsSkuExt.getPrice().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        waresAchieve = waresAchieve.add(bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        assAchieve = assAchieve.add(bdWaresSpecsSkuExt.getAssAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        // 会员价
                        vipAchieve = vipAchieve.add(bdWaresSpecsSkuExt.getVipPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
                        // 零售价
                        retailPrice = retailPrice.add(bdWaresSpecsSkuExt.getRetailPrice().multiply(BigDecimal.valueOf(bdWaresSpecsSkuExt.getQuantity())));
                    }
                    if (cuWaresParams.getPkCountry() != null && !pkCountry.equals(SecurityUtils.getPkCountry())) {
                        // 当登陆人的结算国和前端结算国不一致 即为跨国报单
                        if (!pkCountry.equals(SecurityUtils.getPkCountry())) {
                            // 跨国报单 跨国汇率
                            R<CurrencyDTO> kgCurrency = currencyServiceApi.getCurrency(pkCountry);
                            waresPrice = waresPrice.multiply(inExchangeRate).divide(kgCurrency.getData().getInExchangeRate(), 2, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }

                // 计算商品列表价格和业绩最小值
                waresParams.setWaresPrice(waresPrice);
                waresParams.setWaresAchieve(waresAchieve);
                waresParams.setAssAchieve(assAchieve);
                waresParams.setVipPrice(vipAchieve);
                waresParams.setRetailPrice(retailPrice);
                waresParams.setIsMakerGift(waresExt.getIsMakerGift());
                // 商品业绩计算汇率
                if (waresParams.getWaresAchieve() != null) {
                    if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                        waresParams.setWaresAchieve(waresParams.getWaresAchieve().multiply(inExchangeRate));
                    } else {
                        waresParams.setWaresAchieve(waresParams.getWaresAchieve());
                        waresParams.setWaresPrice(waresParams.getWaresPrice());
                    }
                } else {
                    waresParams.setWaresAchieve(BigDecimal.ZERO);
                    waresParams.setWaresPrice(BigDecimal.ZERO);
                }

                // 查询默认规格
                JSONArray jsonArray = new JSONArray();
                List<BdWaresSpecsSkuExt> collect = waresSpecsSkuList.stream().filter(DistinctByKeyUtil.distinctByKey(BdWaresSpecsSku::getPkWaresDetail)).collect(Collectors.toList());
                for (BdWaresSpecsSkuExt bdWaresSpecsSku : collect) {
                    if (bdWaresSpecsSku.getPkWares().equals(waresExt.getPkId())) {
                        JSONObject js = new JSONObject();
                        js.put("pkProduct", bdWaresSpecsSku.getPkProduct());
                        js.put("pkSkuId", bdWaresSpecsSku.getPkId());
                        js.put("quantity", bdWaresSpecsSku.getQuantity());
                        jsonArray.add(js);
                    }
                }
                waresParams.setProductGroup(jsonArray);
                waresParamsList.add(waresParams);
            }
            // 封装抵扣
            if (ESpecialArea.RESCISSION_AREA.getValue() == cuWaresParams.getSpecialArea()) {
                BigDecimal deductRatio = getSpecialDeductRatio(cuWaresParams, pkCountry, EAccount.REPEAT.getValue());
                Set<Integer> pkCurrencySet = new HashSet<>();
                for (CuWaresParams waresParams : waresParamsList) {
                    if (waresParams.getPkSpecialCurrency() != null) {
                        pkCurrencySet.add(waresParams.getPkSpecialCurrency());
                    }
                }
                List<AreaCurrencyDTO> areaCurrencyDTOList = new ArrayList<>();
                if (pkCurrencySet.size() > 0) {
                    areaCurrencyDTOList = areaCurrencyServiceApi.queryAreaCurrencyBySpecialArea(pkCurrencySet, EAccount.REPEAT.getValue());
                }

                for (CuWaresParams waresParams : waresParamsList) {
                    waresParams.setDeductMoney(ComputeUtil.computeBonusMultiply(waresParams.getWaresPrice(), deductRatio));
                    if (areaCurrencyDTOList.size() > 0) {
                        for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
                            if (areaCurrencyDTO.getPkSpecialCurrency().equals(waresParams.getPkSpecialCurrency())
                                    && areaCurrencyDTO.getFieldValue().equals(EAccount.REPEAT.getValue())
                                    && areaCurrencyDTO.getDeductMaxRatio().compareTo(BigDecimal.ZERO) > 0) {
                                // 当前支付配置，重消币配置，最大比例不为0
                                waresParams.setDeductMoney(ComputeUtil.computeBonusMultiply(waresParams.getDeductMoney(), areaCurrencyDTO.getDeductMaxRatio()));
                            }
                        }
                    }
                }
            }
        }
        return AjaxResult.success(waresParamsList);
    }

    /*
     * 获得专区抵扣比例
     **/
    private BigDecimal getSpecialDeductRatio(CuWaresParams cuWaresParams, Integer pkCountry, Integer accountValue) {
        // 查询专区所属币种
        List<AreaCurrencyDTO> areaCurrencyDTOList = areaCurrencyServiceApi.queryAreaCurrencyByCondition(cuWaresParams.getSpecialArea(), pkCountry).getData();
        BigDecimal elseRatio = BigDecimal.ZERO;
        BigDecimal deductRatio = BigDecimal.ZERO;
        boolean flag = false;
        for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
            if (accountValue.equals(areaCurrencyDTO.getFieldValue())) {
                deductRatio = ComputeUtil.computeAdd(deductRatio, areaCurrencyDTO.getDeductRatio());
                flag = true;
            } else {
                elseRatio = ComputeUtil.computeAdd(elseRatio, areaCurrencyDTO.getDeductRatio());
            }
        }
        if (flag) {
            if (ComputeUtil.compareValue(deductRatio)) {
                return deductRatio;
            } else {
                return ComputeUtil.computeSubtract(BigDecimal.valueOf(100), elseRatio);
            }
        } else {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 查询团队配置是否展示该商品
     *
     * @param pkWares
     * @return
     */
    public ShowWaresDTO getShowWares(Integer pkWares, Long loginMember, String loginMemberCode, Map<Integer, List<BdWaresAuthority>> waresAuthorityMap) {
        ShowWaresDTO showWaresDTO = new ShowWaresDTO();
        showWaresDTO.setPkWares(pkWares);
        showWaresDTO.setLoginMember(loginMember);
        showWaresDTO.setLoginMemberCode(loginMemberCode);
        showWaresDTO.setWaresAuthorityList(waresAuthorityMap.get(pkWares));
        return showWaresDTO;
    }

    /**
     * 根据编号，查找商品的明细，点击加入购物车
     *
     * @param cuWaresParams 专区、分类
     */
    @RequestMapping("/query-spe-wares-detail")
    public AjaxResult queryWaresDetailByCode(@RequestBody CuWaresParams cuWaresParams) {
        if (cuWaresParams.getSpecialArea() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }
        if (cuWaresParams.getWaresCode() == null) {
            return AjaxResult.error(WaresMsgConstants.WARES_NUMBER_DOES_NOT_EXIST);
        }
        Long loginMemberId = SecurityUtils.getUserId();
        Integer pkCountry;
        if (cuWaresParams.getPkCountry() == null) {
            pkCountry = SecurityUtils.getPkCountry();
        } else {
            pkCountry = cuWaresParams.getPkCountry();
        }
        cuWaresParams = bdWaresSpecsSkuService.queryWaresSpecsSku(cuWaresParams.getSpecialArea(), cuWaresParams.getWaresCode(), loginMemberId, pkCountry);

        // 预计发货时间（秒）
        if (cuWaresParams.getArrivalTime() != null && cuWaresParams.getCreationTime() != null) {
            long ArrivalTime = cuWaresParams.getArrivalTime().getTime();
            long thisTime = System.currentTimeMillis();
            if (ArrivalTime < thisTime) {
                cuWaresParams.setDeliveryTimeMs(0L);
            } else {

                cuWaresParams.setDeliveryTimeMs(DateUtil.betweenMs(cuWaresParams.getArrivalTime(), new Date()) / 1000);
            }
        }

        // 封装抵扣
        if (ESpecialArea.RESCISSION_AREA.getValue() == cuWaresParams.getSpecialArea()) {
            BigDecimal deductRatio = getSpecialDeductRatio(cuWaresParams, pkCountry, EAccount.REPEAT.getValue());
            Set<Integer> pkCurrencySet = new HashSet<>();
            if (cuWaresParams.getPkSpecialCurrency() != null) {
                pkCurrencySet.add(cuWaresParams.getPkSpecialCurrency());
            }

            List<AreaCurrencyDTO> areaCurrencyDTOList = new ArrayList<>();
            if (pkCurrencySet.size() > 0) {
                areaCurrencyDTOList = areaCurrencyServiceApi.queryAreaCurrencyBySpecialArea(pkCurrencySet, EAccount.REPEAT.getValue());
            }
            cuWaresParams.setDeductMoney(ComputeUtil.computeBonusMultiply(cuWaresParams.getWaresPrice(), deductRatio));
            if (areaCurrencyDTOList.size() > 0) {
                for (AreaCurrencyDTO areaCurrencyDTO : areaCurrencyDTOList) {
                    if (areaCurrencyDTO.getPkSpecialCurrency().equals(cuWaresParams.getPkSpecialCurrency())
                            && areaCurrencyDTO.getFieldValue().equals(EAccount.REPEAT.getValue())
                            && areaCurrencyDTO.getDeductMaxRatio().compareTo(BigDecimal.ZERO) > 0) {
                        // 当前支付配置，重消币配置，最大比例不为0
                        cuWaresParams.setDeductMoney(ComputeUtil.computeBonusMultiply(cuWaresParams.getDeductMoney(), areaCurrencyDTO.getDeductMaxRatio()));
                    }
                }
            }

        }
        return AjaxResult.success(cuWaresParams);
    }

    /**
     * 查询商品sku详情, 选择规格后，查询出sku，选择规格
     *
     * @param cuWaresItemsParams 参数,编码
     */
    @RequestMapping("/query-wares-detail-sku")
    public AjaxResult queryWaresSkuByCode(@RequestBody CuWaresItemsParams cuWaresItemsParams) {
        if (cuWaresItemsParams.getWaresCode() == null || cuWaresItemsParams.getPkWaresDetail() == null) {
            return AjaxResult.error(WaresMsgConstants.WARES_NUMBER_DOES_NOT_EXIST);
        }
        return AjaxResult.success(bdWaresSpecsSkuService.queryWaresDetailSkuBySpecs(cuWaresItemsParams));
    }

    /**
     * 查询商品
     */
    @PostMapping("get-wares-agreement")
    public AjaxResult getWaresAgreement(@RequestBody WaresAgrementParam waresAgrementParam) {
        if (waresAgrementParam.getWaresCodeList().size() == 0) {
            return AjaxResult.error(TransactionUtils.getContent(WaresMsgConstants.WARES_CODE_NOT_NULL));
        }

        List<BdAgreement> waresExtList = bdWaresService.selectByWaresCodeList(waresAgrementParam.getWaresCodeList());
        OrderAlertVo orderAlertVo = new OrderAlertVo();
        Integer alertTime = 0;
        orderAlertVo.setWaresExtList(waresExtList);
        for (BdAgreement agreement : waresExtList) {
            if (agreement.getIsForcedRead() == EYesNo.YES.getIntValue()) {
                if (agreement.getForcedReadTime() > alertTime) {
                    alertTime = agreement.getForcedReadTime();
                }
            }
        }
        orderAlertVo.setAlertTime(alertTime);
        return AjaxResult.success(orderAlertVo);
    }

    /**
     * 商品推荐接口 （公司商品）
     */
    @RequestMapping("/recommend_wares")
    public AjaxResult recommnedWares(@RequestBody CuWaresParams cuWaresParams) {
        if (cuWaresParams.getSpecialArea() == null) {
            return AjaxResult.error(TransactionUtils.getContent(SaOrderMsgConstants.SPECIAL_AREA_NOT_EMPTY));
        }

        Integer pkCountry;
        if (cuWaresParams.getPkCountry() != null) {
            pkCountry = cuWaresParams.getPkCountry();
        } else {
            pkCountry = SecurityUtils.getPkCountry();
        }

        // 返回数据列表
        List<CuWaresParams> waresParamsList = new ArrayList<>();

        // 查询商品列表
        List<BdWaresExt> bdWaresExtList = bdWaresService.queryRecommendWaresByCondition(cuWaresParams.getSpecialArea(), cuWaresParams.getPkAreaClassify(), cuWaresParams.getWaresName(), pkCountry);

        if (CollectionUtil.isNotEmpty(bdWaresExtList)) {
            // 商品ID列表
            List<Integer> pkWaresIds = bdWaresExtList.stream().map(BdWares::getPkId).collect(Collectors.toList());

            // 当前会员
            CuMember cuMember = saOrderService.getCuMemberByKey(SecurityUtils.getUserId());
            // 汇率比例
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

            // 查询商品标签列表
            BdWaresLabel waresLabel = new BdWaresLabel();
            waresLabel.setPkIdList(pkWaresIds);
            List<BdLabelExt> labelList = waresLabelService.selectByList(waresLabel);

            // 标签
            for (BdWaresExt bdWaresExt : bdWaresExtList) {
                // 保证标签
                List<BdLabel> ensureLabelList = new ArrayList<>();
                // 卖点标签
                List<BdLabel> sellingLabelList = new ArrayList<>();
                for (BdLabelExt bdLabel : labelList) {
                    if (ELabelType.PREFIX.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 前缀标签
                        bdWaresExt.setPrefixLabelTarget(bdLabel);
                    }
                    if (ELabelType.COOL.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 酷炫标签
                        bdWaresExt.setCoolLabelTarget(bdLabel);
                    }
                    if (ELabelType.ENSURE.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 保证标签
                        ensureLabelList.add(bdLabel);
                    }
                    if (ELabelType.SELLING.getValue() == bdLabel.getLabelType() && bdLabel.getPkWares().equals(bdWaresExt.getPkId())) {
                        // 卖点标签
                        sellingLabelList.add(bdLabel);
                    }
                }
                bdWaresExt.setEnsureLabelList(ensureLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
                bdWaresExt.setSellingLabelList(sellingLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
            }


            Map<Integer, List<BdWaresSpecsSkuExt>> waresSpecsSkuMap = new HashMap<>();
            if (pkWaresIds.size() > 0) {
                List<BdWaresSpecsSkuExt> waresSpecsSkuArray = bdWaresSpecsSkuService.selectByMinWaresSpecsSkuByPkWaresList(pkWaresIds);
                waresSpecsSkuMap = waresSpecsSkuArray.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getPkWares));
            }

            for (BdWaresExt waresExt : bdWaresExtList) {
                CuWaresParams waresParams = BeanUtil.copyProperties(waresExt, CuWaresParams.class);
                // 价格
                BigDecimal waresPrice = BigDecimal.ZERO;
                // 业绩
                BigDecimal waresAchieve = BigDecimal.ZERO;
                // bv
                BigDecimal assAchieve = BigDecimal.ZERO;
                if (EOrderType.REPURCHASE_ORDER.getValue() == cuWaresParams.getSpecialArea()) {
                    // 复购业绩计算
                    List<Integer> waresIdSet = new ArrayList<>();
                    bdWaresExtList.forEach(we -> {
                        waresIdSet.add(we.getPkId());
                    });
                    List<BdWaresRange> bdWaresRangeList = bdWaresRangeService.queryWaresRangeByCondition(cuMember, waresIdSet);
                    for (BdWaresRange bdWaresRange : bdWaresRangeList) {
                        if (waresExt.getPkId().intValue() == bdWaresRange.getPkWares().intValue()) {
                            waresPrice = waresPrice.add(bdWaresRange.getPrice());
                            waresAchieve = waresAchieve.add(bdWaresRange.getAchieve());
                            assAchieve = assAchieve.add(bdWaresRange.getAssAchieve());
                        }
                    }
                } else {
                    //计算商品的价格和业绩 sku价格最小值 * 商品数量
                    List<BdWaresSpecsSkuExt> waresSpecsSku = waresSpecsSkuMap.get(waresExt.getPkId());
                    waresSpecsSku = waresSpecsSku.stream().peek(a -> a.setProductGift(a.getPkProduct() + "" + a.getIsGift())).collect(Collectors.toList());
                    Map<String, List<BdWaresSpecsSkuExt>> col = waresSpecsSku.stream().collect(Collectors.groupingBy(BdWaresSpecsSkuExt::getProductGift));
                    for (Map.Entry<String, List<BdWaresSpecsSkuExt>> integerListEntry : col.entrySet()) {
                        // 取得每一个商品价格最小值
                        Optional<BdWaresSpecsSkuExt> minBdWaresSpecsSkuExt = integerListEntry.getValue().stream().filter(Objects::nonNull).min(Comparator.comparing(BdWaresSpecsSkuExt::getPrice));
                        BdWaresSpecsSkuExt bdWaresSpecsSkuExt = minBdWaresSpecsSkuExt.get();
                        if (bdWaresSpecsSkuExt.getIsGift().equals(EYesNo.NO.getIntValue())) {
                            waresPrice = waresPrice.add(bdWaresSpecsSkuExt.getPrice().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                            waresAchieve = waresAchieve.add(bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                            assAchieve = assAchieve.add(bdWaresSpecsSkuExt.getAssAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())));
                        }
                    }
                }

                // 计算商品列表价格和业绩最小值
                waresParams.setWaresPrice(waresPrice);
                waresParams.setWaresAchieve(waresAchieve);
                waresParams.setAssAchieve(assAchieve);
                // 商品业绩计算汇率
                if (waresParams.getWaresAchieve() != null) {
                    if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                        waresParams.setWaresAchieve(waresParams.getWaresAchieve().multiply(inExchangeRate));

                    } else {
                        waresParams.setWaresAchieve(waresParams.getWaresAchieve());
                    }
                } else {
                    waresParams.setWaresAchieve(BigDecimal.ZERO);
                }
                // 商品bv 计算
                if (waresParams.getAssAchieve() != null) {
                    if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                        waresParams.setAssAchieve(waresParams.getAssAchieve().multiply(inExchangeRate));
                    } else {
                        waresParams.setAssAchieve(waresParams.getAssAchieve());
                    }
                } else {
                    waresParams.setAssAchieve(BigDecimal.ZERO);
                }

                // 查询默认规格
                JSONArray jsonArray = new JSONArray();
                List<BdWaresSpecsSkuExt> list = bdWaresSpecsSkuService.selectByWaresSpecsSku(Collections.singletonList(waresExt.getPkId()));
                List<BdWaresSpecsSkuExt> collect = list.stream().filter(DistinctByKeyUtil.distinctByKey(BdWaresSpecsSku::getPkWaresDetail)).collect(Collectors.toList());
                for (BdWaresSpecsSkuExt bdWaresSpecsSku : collect) {
                    JSONObject js = new JSONObject();
                    js.put("pkProduct", bdWaresSpecsSku.getPkProduct());
                    js.put("pkSkuId", bdWaresSpecsSku.getPkId());
                    js.put("quantity", bdWaresSpecsSku.getQuantity());
                    jsonArray.add(js);
                }
                waresParams.setProductGroup(jsonArray);
                // 查询等级配置
                QueryWrapper<BdWaresGrade> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PK_WARES", waresExt.getPkId());
                List<BdWaresGrade> waresGradeList = waresGradeService.list(queryWrapper);
                if (waresGradeList.size() > 0) {
                    // 查询等级和商品是否存在 不存在不返回该数据
                    for (BdWaresGrade bdWaresGrade : waresGradeList) {
                        Integer pkSettleGrade = cuMember.getPkSettleGrade();
                        if (pkSettleGrade.equals(bdWaresGrade.getPkRange())) {
                            waresParamsList.add(waresParams);
                        }

                    }
                } else {
                    waresParamsList.add(waresParams);
                }
            }
        }
        return AjaxResult.success(waresParamsList);
    }

    /**
     * 下单商品信息展示
     *
     * @return
     */
    @PostMapping("get-wares-info")
    public AjaxResult getWaresInfo(@RequestBody WaresInfoParam waresInfoParam) {
        BdWares wares = bdWaresService.getWares(waresInfoParam.getPkWares());
        WaresInfoVo waresInfoVo = new WaresInfoVo();
        waresInfoVo.setWaresName(wares.getWaresName());

        waresInfoVo.setNumber(waresInfoParam.getNumber());
        waresInfoVo.setPkWares(wares.getPkId());
        waresInfoVo.setCover(wares.getCover1());

        List<Integer> waresSpecsSkuList = waresInfoParam.getWaresSpecsSku().stream().map(WaresSpecsSkuParam::getPkWaresSpecsSku).collect(Collectors.toList());
        List<WaresItemWaresInfo> waresItemWaresInfos = bdWaresSpecsSkuService.selectByPkIds(waresSpecsSkuList);
        BigDecimal waresPrice = BigDecimal.ZERO;
        BigDecimal pv = BigDecimal.ZERO;
        BigDecimal waresPriceAmount = BigDecimal.ZERO;
        BigDecimal pvAmount = BigDecimal.ZERO;
        for (WaresItemWaresInfo waresItemWaresInfo : waresItemWaresInfos) {
            waresPrice = waresPrice.add(waresItemWaresInfo.getPrice());
            pv = pv.add(waresItemWaresInfo.getAchieve());
            for (WaresSpecsSkuParam waresSpecsSkuParam : waresInfoParam.getWaresSpecsSku()) {
                if (waresSpecsSkuParam.getPkWaresSpecsSku().equals(waresItemWaresInfo.getPkWaresSpecsSku())) {
                    waresPriceAmount = waresPriceAmount.add(waresItemWaresInfo.getPrice().multiply(new BigDecimal(waresSpecsSkuParam.getQuantity())));
                    pvAmount = pvAmount.add(waresItemWaresInfo.getAchieve().multiply(new BigDecimal(waresSpecsSkuParam.getQuantity())));
                }
            }
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CountryConstants.CHINA_COUNTRY.equals(pkCountry)) {
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
            // 汇率比例
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
            pv = ComputeUtil.computeMultiply(pv, inExchangeRate);
            pvAmount = ComputeUtil.computeMultiply(pvAmount, inExchangeRate);
        }
        waresInfoVo.setWaresPrice(waresPrice);
        waresInfoVo.setPv(pv);
        waresInfoVo.setWaresCode(wares.getWaresCode());
        waresInfoVo.setWaresPriceAmount(waresPriceAmount);
        waresInfoVo.setPvAmount(pvAmount);
        waresInfoVo.setWaresSpecsSkuInfoList(waresItemWaresInfos);
        return AjaxResult.success(waresInfoVo);
    }

}
