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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DistinctByKeyUtil;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.sale.ext.BdWaresSpecsRelationExt;
import com.hzs.common.domain.sale.ext.BdWaresSpecsSkuExt;
import com.hzs.common.domain.sale.wares.BdWaresLabel;
import com.hzs.common.domain.sale.wares.BdWaresRange;
import com.hzs.common.domain.sale.wares.BdWaresSpecsSku;
import com.hzs.common.domain.system.config.BdAwards;
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.member.base.IMemberServiceApi;
import com.hzs.sale.shopping.vo.ProductGroup;
import com.hzs.sale.shopping.vo.WaresItemVo;
import com.hzs.sale.shopping.vo.WaresItemWaresInfo;
import com.hzs.sale.util.OrderUtil;
import com.hzs.sale.util.WaresSpecialUtil;
import com.hzs.sale.wares.mapper.BdWaresSpecsSkuMapper;
import com.hzs.sale.wares.param.*;
import com.hzs.sale.wares.service.*;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IRangeServiceApi;
import com.hzs.system.config.dto.RangeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 规格sku表 服务实现类
 */
@Service
public class BdWaresSpecsSkuServiceImpl extends ServiceImpl<BdWaresSpecsSkuMapper, BdWaresSpecsSku> implements IBdWaresSpecsSkuService {

    @Autowired
    private IBdWaresSpecsRelationService waresSpecsRelationService;
    @Autowired
    private IBdWaresLabelService waresLabelService;
    @Autowired
    private IBdWaresDetailService waresDetailService;
    @Autowired
    private IBdWaresRangeService bdWaresRangeService;

    @DubboReference
    ICurrencyServiceApi currencyServiceApi;
    @DubboReference
    IRangeServiceApi rangeServiceApi;
    @DubboReference
    IMemberServiceApi memberServiceApi;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;

    @Override
    public CuWaresParams queryWaresSpecsSku(Integer specialArea, String waresCode, Long loginMemberId, Integer pkCountry) {
        List<BdWaresSpecsSkuExt> bdWaresSpecsSkuExtList;
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        R<CuMember> memberDate = memberServiceApi.getMember(loginMemberId);
        CuMember cuMember = memberDate.getData();

        if (EOrderType.REPURCHASE_ORDER.getValue() == specialArea) {
            int level = cuMember.getPkSettleGrade();
            int rangeType = ERangeType.GRADE.getValue();
            BdAwards bdAwards = awardsServiceApi.getAwardsOne(cuMember.getPkAwards()).getData();
            if (bdAwards.getAwardsValue() > EAwards.MEMBER.getValue()) {
                level = cuMember.getPkAwards();
                rangeType = ERangeType.AWARDS.getValue();
            }
            RangeDTO rangeDTO = rangeServiceApi.queryRangeDtoByCondition(cuMember.getPkSettleCountry(), rangeType, level).getData();
            if (rangeDTO == null) {
                return new CuWaresParams();
            }
            // 查询复购极差价格
            bdWaresSpecsSkuExtList = baseMapper.queryWaresSpecsRangeSku(specialArea, waresCode, rangeDTO.getPkRange());
        } else {
            bdWaresSpecsSkuExtList = baseMapper.queryWaresSpecsSku(WaresSpecialUtil.getWaresSpecial(specialArea), waresCode);
        }
        if (bdWaresSpecsSkuExtList.size() > 0) {
            Set<Integer> pkSkuIdList = new HashSet<>();
            bdWaresSpecsSkuExtList.forEach(bdWaresSpecsSkuExt ->
                    pkSkuIdList.add(bdWaresSpecsSkuExt.getPkId()));
            List<BdWaresSpecsSkuExt> bdWaresSpecsSkuList = baseMapper.queryWaresSpecsNameSku(pkSkuIdList);
            Map<Integer, String> specsNameMap = new HashMap<>(ComputeUtil.mapInitCapacity(bdWaresSpecsSkuExtList.size()));
            Map<Integer, List<Integer>> specsIdMap = new HashMap<>();
            bdWaresSpecsSkuList.forEach(bdWaresSpecsSku -> {
                String specsName = bdWaresSpecsSku.getSpecsName();
                if (specsNameMap.containsKey(bdWaresSpecsSku.getPkId())) {
                    String oldSpecsName = specsNameMap.get(bdWaresSpecsSku.getPkId());
                    specsName = oldSpecsName + "，" + specsName;
                }
                specsNameMap.put(bdWaresSpecsSku.getPkId(), specsName);
                if (specsIdMap.containsKey(bdWaresSpecsSku.getPkId())) {
                    List<Integer> idList = specsIdMap.get(bdWaresSpecsSku.getPkId());
                    idList.add(bdWaresSpecsSku.getPkSpecs());
                } else {
                    List<Integer> idList = new ArrayList<>();
                    idList.add(bdWaresSpecsSku.getPkSpecs());
                    specsIdMap.put(bdWaresSpecsSku.getPkId(), idList);
                }
            });
            CuWaresParams cuWaresParams = BeanUtil.copyProperties(bdWaresSpecsSkuExtList.get(0), CuWaresParams.class);
            cuWaresParams.setWaresPrice(bdWaresSpecsSkuExtList.get(0).getPrice());
            cuWaresParams.setPkWares(bdWaresSpecsSkuExtList.get(0).getPkWares());
            //查询标签合集
            BdWaresLabel waresLabel = new BdWaresLabel();
            waresLabel.setPkWares(bdWaresSpecsSkuExtList.get(0).getPkWares());
            List<BdLabelExt> labelList = waresLabelService.selectByList(waresLabel);
            // 保证标签
            List<BdLabel> ensureLabelList = new ArrayList<>();
            // 卖点标签
            List<BdLabel> sellingLabelList = new ArrayList<>();
            for (BdLabel bdLabel : labelList) {
                if (bdLabel.getLabelType() == ELabelType.PREFIX.getValue()) {
                    // 前缀标签
                    cuWaresParams.setPrefixLabelTarget(bdLabel);
                }
                if (bdLabel.getLabelType() == ELabelType.COOL.getValue()) {
                    // 酷炫标签
                    cuWaresParams.setCoolLabelTarget(bdLabel);
                }
                if (bdLabel.getLabelType() == ELabelType.ENSURE.getValue()) {
                    // 保证标签
                    ensureLabelList.add(bdLabel);
                }
                if (bdLabel.getLabelType() == ELabelType.SELLING.getValue()) {
                    // 卖点标签
                    sellingLabelList.add(bdLabel);
                }
                cuWaresParams.setEnsureLabelList(ensureLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
                cuWaresParams.setSellingLabelList(sellingLabelList.stream().filter(DistinctByKeyUtil.distinctByKey(BdLabel::getPkId)).collect(Collectors.toList()));
            }
            cuWaresParams.setInExchangeRate(currency.getData().getInExchangeRate());

            List<CuWaresItemsParams> cuWaresItemsParamsList = setUpWaresItemsParams(pkCountry, bdWaresSpecsSkuExtList, specsNameMap, specsIdMap, currency.getData().getInExchangeRate());
            // 前台传递结算国 跨国报单计算价格使用
            R<CurrencyDTO> kgCurrency = null;
            if (pkCountry != null) {
                kgCurrency = currencyServiceApi.getCurrency(pkCountry);
            }
            List<CuProductParams> productParams = waresDetailService.selectByWaresCode(waresCode, WaresSpecialUtil.getWaresSpecial(specialArea));
            for (CuProductParams cuProductParams : productParams) {
                List<CuWaresItemsParams> list = new ArrayList<>();
                for (CuWaresItemsParams cuWaresItemsParams : cuWaresItemsParamsList) {
                    if (cuWaresItemsParams.getIsGift().equals(cuProductParams.getIsGift())) {
                        if (cuWaresItemsParams.getPkProduct().equals(cuProductParams.getProductId())) {
                            if (pkCountry != null) {
                                // 当登陆人的结算国和前端结算国不一致 即为跨国报单
                                if (!pkCountry.equals(SecurityUtils.getPkCountry())) {
                                    BigDecimal price = cuWaresItemsParams.getPrice();
                                    // 除保留6位小数（用以处理大汇率问题），乘保留2位（用以前台显示）
                                    cuWaresItemsParams.setPrice(price.divide(kgCurrency.getData().getInExchangeRate(), 6, BigDecimal.ROUND_HALF_UP).multiply(cuWaresParams.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    // 单价 * 数量计算汇率
                                    cuWaresItemsParams.setPriceTotal(price.multiply(new BigDecimal(cuWaresItemsParams.getQuantity())).divide(kgCurrency.getData().getInExchangeRate(), 6, BigDecimal.ROUND_HALF_UP).multiply(cuWaresParams.getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                    // 跨国金额
                                    cuWaresItemsParams.setBorderPrice(price);
                                    // 跨国单位
                                    cuWaresItemsParams.setBorderUnit(kgCurrency.getData().getSymbol());
                                }

                                // 0PV专区，并且已经续约，价格打5折
                                cuWaresItemsParams.setPrice(OrderUtil.discountPrice(cuMember, specialArea, cuWaresItemsParams.getPrice()));
                                cuWaresItemsParams.setPriceTotal(OrderUtil.discountPrice(cuMember, specialArea, cuWaresItemsParams.getPriceTotal()));
                            }
                            list.add(cuWaresItemsParams);
                        }
                    }
                }
                cuProductParams.setWaresItemsParamsList(list);
                cuWaresParams.setIsMakerGift(cuProductParams.getIsMakerGift());
            }
            cuWaresParams.setProductParams(productParams);
            cuWaresParams.setSpecialArea(specialArea);

            // 0PV专区，并且已经续约，价格打5折
            cuWaresParams.setWaresPrice(OrderUtil.discountPrice(cuMember, cuWaresParams.getSpecialArea(), cuWaresParams.getWaresPrice()));

            return cuWaresParams;
        }
        return null;
    }

    /**
     * 设置返回到前台的商品明细表
     *
     * @param bdWaresSpecsSkuExtList 商品待sku
     */
    private List<CuWaresItemsParams> setUpWaresItemsParams(Integer pkCountry, List<BdWaresSpecsSkuExt> bdWaresSpecsSkuExtList, Map<Integer, String> specsNameMap, Map<Integer, List<Integer>> specsIdMap, BigDecimal inExchangeRate) {
        List<CuWaresItemsParams> cuWaresItemsParamsList = new ArrayList<>();

        bdWaresSpecsSkuExtList.forEach(bdWaresSpecsSkuExt -> {
            BigDecimal achieveTotal;
            if (SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
                achieveTotal = bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())).multiply(inExchangeRate);
            } else {
                achieveTotal = bdWaresSpecsSkuExt.getAchieve().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity()));
            }
            // bv
            BigDecimal assAchieveTotal = isitEmpty(bdWaresSpecsSkuExt.getAssAchieve()).multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity()));
            // 汇率比例
            CuWaresItemsParams cuWaresItemsParams = CuWaresItemsParams.builder()
                    .quantity(bdWaresSpecsSkuExt.getQuantity())
                    .isGift(bdWaresSpecsSkuExt.getIsGift())
                    .pkProduct(bdWaresSpecsSkuExt.getPkProduct())
                    .pkWaresDetail(bdWaresSpecsSkuExt.getPkWaresDetail())
                    .price(bdWaresSpecsSkuExt.getPrice())
                    .achieve(bdWaresSpecsSkuExt.getAchieve())
                    .specCover(bdWaresSpecsSkuExt.getSpecCover())
                    .pkSkuId(bdWaresSpecsSkuExt.getPkId())
                    .assAchieve(bdWaresSpecsSkuExt.getAssAchieve())
                    .assAchieveTotal(assAchieveTotal)
                    .specsName(specsNameMap.get(bdWaresSpecsSkuExt.getPkId()))
                    .achieveTotal(achieveTotal)
                    .inventoryNum(BigDecimal.ZERO)
                    .priceTotal(bdWaresSpecsSkuExt.getPrice().multiply(new BigDecimal(bdWaresSpecsSkuExt.getQuantity())))
                    .build();
            cuWaresItemsParamsList.add(cuWaresItemsParams);
        });
        return cuWaresItemsParamsList;
    }

    private BigDecimal isitEmpty(BigDecimal assAchieve) {
        if (StringUtils.isNotNull(assAchieve)) {
            return assAchieve;
        } else {
            return new BigDecimal(0);
        }
    }

    @Override
    public SpecsSkuParam queryWaresDetailSkuBySpecs(CuWaresItemsParams cuWaresItemsParams) {
        BdWaresSpecsSkuExt bdWaresSpecsSkuExt = baseMapper.queryWaresDetailSkuBySpecs(cuWaresItemsParams);
        return SpecsSkuParam.builder()
                .pkWaresSpecsSku(bdWaresSpecsSkuExt.getPkId())
                .price(bdWaresSpecsSkuExt.getWaresPrice())
                .achieve(bdWaresSpecsSkuExt.getWaresAchieve())
                .build();
    }

    @Override
    public void updateBySkuId(BdWaresSpecsSku sku) {
        baseMapper.updateBySkuId(sku);
    }

    @Override
    public BdWaresSpecsSku selectByWaresSpecsSkuIdAndDel(Integer pkWaresSpecsSku) {
        return baseMapper.selectByWaresSpecsSkuIdAndDel(pkWaresSpecsSku);
    }

    @Override
    public List<BdWaresSpecsSkuExt> selectByWaresSpecsSku(List<Integer> waresIds) {
        return baseMapper.selectByWaresSpecsSku(waresIds);
    }

    @Override
    public List<WaresItemWaresInfo> selectByPkIds(List<Integer> pkWaresSpecsSku) {
        return baseMapper.selectByPkIds(pkWaresSpecsSku);
    }

    @Override
    public WaresItemVo selectWaresItemsVO(Long pkMember, Integer pkCountry, Integer specialArea, String waresCode, List<ProductGroup> productGroup, Integer quantity) {
        WaresItemVo waresItemVo = WaresItemVo.builder().build();
        if (CollectionUtil.isNotEmpty(productGroup)) {
            CuMember cuMember = memberServiceApi.getMember(SecurityUtils.getUserId()).getData();

            waresItemVo = baseMapper.selectWaresItemsVO(WaresSpecialUtil.getWaresSpecial(specialArea), waresCode, productGroup);
            waresItemVo.setQuantity(quantity);
            waresItemVo.setSkuQuantity(waresItemVo.getQuantity());
            waresItemVo.setPrice(BigDecimal.ZERO);
            waresItemVo.setPriceAmount(BigDecimal.ZERO);
            waresItemVo.setAchieve(BigDecimal.ZERO);
            waresItemVo.setAchieveAmount(BigDecimal.ZERO);
            waresItemVo.setAssAchieve(BigDecimal.ZERO);
            waresItemVo.setAssAchieveAmount(BigDecimal.ZERO);
            Map<String, WaresItemWaresInfo> waresDetailExtMap = new HashMap<>();
            waresItemVo.getWaresItemsParamList().forEach(waresItemWaresInfo -> {
                waresDetailExtMap.put(waresItemWaresInfo.getPkWaresDetail().toString() + waresItemWaresInfo.getPkWaresSpecsSku(), waresItemWaresInfo);
                // 设置规格值 名称拼接
                List<BdWaresSpecsRelationExt> waresSpecsRelationExts = waresSpecsRelationService.selectByWaresSpecsSku(waresItemWaresInfo.getPkWaresSpecsSku());
                List<String> specsNames = waresSpecsRelationExts.stream().map(BdWaresSpecsRelationExt::getSpecsName).distinct().collect(Collectors.toList());
                waresItemWaresInfo.setSkuInfo(StringUtils.join(specsNames, ","));

                // 2025.01.21 新需求，续约会员指定专区购买商品打5折
                // 续约日期大于等于当前时间，为有效会员需要商品打5折
                waresItemWaresInfo.setPrice(OrderUtil.discountPrice(cuMember, specialArea, waresItemWaresInfo.getPrice()));
            });
            if (EOrderType.REPURCHASE_ORDER.getValue() == specialArea) {
                int level = cuMember.getPkSettleGrade();
                int rangeType = ERangeType.GRADE.getValue();
                BdAwards bdAwards = awardsServiceApi.getAwardsOne(cuMember.getPkAwards()).getData();
                if (bdAwards.getAwardsValue() > EAwards.MEMBER.getValue()) {
                    level = cuMember.getPkAwards();
                    rangeType = ERangeType.AWARDS.getValue();
                }
                List<Integer> pkWaresSpecsSku = productGroup.stream().map(ProductGroup::getPkSkuId).collect(Collectors.toList());
                List<BdWaresRange> bdWaresRangeList = bdWaresRangeService.querySkuWaresRangeByCondition(cuMember.getPkSettleCountry(), rangeType, level, pkWaresSpecsSku);
                bdWaresRangeList.forEach(bdWaresRange -> {
                    String key = bdWaresRange.getPkWaresDetail().toString() + bdWaresRange.getPkWaresSpecsSku();
                    if (waresDetailExtMap.containsKey(key)) {
                        waresDetailExtMap.get(key).setPrice(bdWaresRange.getPrice());
                        waresDetailExtMap.get(key).setAchieve(bdWaresRange.getAchieve());
                        waresDetailExtMap.get(key).setAssAchieve(bdWaresRange.getAssAchieve());
                    }
                });
            }
            for (WaresItemWaresInfo waresItemWaresInfo : waresItemVo.getWaresItemsParamList()) {
                waresItemVo.setPrice(ComputeUtil.computeAdd(waresItemVo.getPrice(), ComputeUtil.computeMultiply(waresItemWaresInfo.getPrice(), waresItemWaresInfo.getQuantity())));
                waresItemVo.setAchieve(ComputeUtil.computeAdd(waresItemVo.getAchieve(), ComputeUtil.computeMultiply(waresItemWaresInfo.getAchieve(), waresItemWaresInfo.getQuantity())));
                waresItemVo.setAssAchieve(ComputeUtil.computeAdd(waresItemVo.getAssAchieve(), ComputeUtil.computeMultiply(waresItemWaresInfo.getAssAchieve(), waresItemWaresInfo.getQuantity())));
            }

            // 前台传递结算国 跨国报单计算价格使用
            R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            R<CurrencyDTO> kgCurrency = null;
            if (pkCountry != null) {
                kgCurrency = currencyServiceApi.getCurrency(pkCountry);
            }
            if (pkCountry != null) {
                // 当登陆人的结算国和前端结算国不一致 即为跨国报单
                if (!pkCountry.equals(SecurityUtils.getPkCountry())) {
                    BigDecimal price = waresItemVo.getPrice();
                    waresItemVo.setPrice(price.divide(kgCurrency.getData().getInExchangeRate(), 6, BigDecimal.ROUND_HALF_UP)
                            .multiply(currency.getData().getInExchangeRate()).setScale(2, BigDecimal.ROUND_HALF_UP));
                    // 跨国金额
                    waresItemVo.setBorderPrice(price);
                    // 跨国业绩
                    waresItemVo.setBorderUnit(kgCurrency.getData().getSymbol());
                }
            }
            if (pkCountry != null && CountryConstants.CHINA_COUNTRY == pkCountry) {
                // 汇率比例
                BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
                waresItemVo.setAchieve(ComputeUtil.computeMultiply(waresItemVo.getAchieve(), inExchangeRate));
            }
            waresItemVo.setPriceAmount(ComputeUtil.computeMultiply(waresItemVo.getPrice(), waresItemVo.getQuantity()));
            if (waresItemVo.getBorderPrice() != null) {
                waresItemVo.setBorderAmount(ComputeUtil.computeMultiply(waresItemVo.getBorderPrice(), waresItemVo.getQuantity()));
            }
            waresItemVo.setAchieveAmount(ComputeUtil.computeMultiply(waresItemVo.getAchieve(), waresItemVo.getQuantity()));
            waresItemVo.setAssAchieveAmount(ComputeUtil.computeMultiply(waresItemVo.getAssAchieve(), waresItemVo.getQuantity()));

//            // 2025.01.21 新需求，续约会员指定专区购买商品打5折
//            // 续约日期大于等于当前时间，为有效会员需要商品打5折
//            if (ESpecialArea.REGISTER_AREA_CONSUMPTION.getValue() == specialArea
//                    && discountFlag) {
//                waresItemVo.setPrice(OrderUtil.discountPrice(waresItemVo.getPrice()));
//            }
        }
        return waresItemVo;
    }

    @Override
    public List<BdWaresSpecsSkuExt> selectByMinWaresSpecsSku(Integer pkWares) {
        return baseMapper.selectByMinWaresSpecsSku(pkWares);
    }

    @Override
    public BdWaresSpecsSkuExt selectByPkWaresSpecsSku(Integer pkWaresSpecsSku) {
        return baseMapper.selectByPkWaresSpecsSku(pkWaresSpecsSku);
    }

    @Override
    public List<BdWaresSpecsSkuExt> selectByMinWaresSpecsSkuByPkWaresList(List<Integer> pkWaresIds) {
        return baseMapper.selectByMinWaresSpecsSkuByPkWaresList(pkWaresIds);
    }

}
