package com.sunxung.factoring.service.acceptancesheet.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.dict.impl.PurchAccrualMarginCalcMethodDict;
import com.sunxung.factoring.entity.acceptance.AcceptanceGoodsInfo;
import com.sunxung.factoring.entity.acceptance.BaseGoods;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractBasicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractPriceRule;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractRetentionInfo;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContractBasicInfo;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContract;
import com.sunxung.factoring.service.acceptancesheet.GoodsCalculateService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractBasicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractPriceRuleService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractRetentionInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractService;
import com.sunxung.factoring.service.salescontractmanagement.ICSalesContractBasicInfoService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.sys.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description : 货物计算service实现类
 * @Author : L.Jia
 * @Date: 2022-03-10 16:31
 */
@Service
public class GoodsCalculateServiceImpl implements GoodsCalculateService {

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private PurchContractPriceRuleService purchContractPriceRuleService;

    @Autowired
    private PurchContractRetentionInfoService purchContractRetentionInfoService;

    @Autowired
    private DictionaryService dictService;


    @Override
    public List<BaseGoods> calculateGoodsAmount(String businessNumber, Long supplierId, List<AcceptanceGoodsInfo> goodsInfoList,
                                                BigDecimal occupationSalesRetention, BigDecimal occupationPurchRetention) {
//        if (goodsInfoList != null && goodsInfoList.size() > 0) {
//            List<BaseGoods> goodsList = goodsInfoList.stream().map(goodsInfo -> {
//                // 计算货物销售总价、销售质保金、采购总价、采购质保金信息
//                BaseGoods baseGoods = calculate(businessNumber, supplierId,
//                        goodsInfo.getSalesPrice(), goodsInfo.getGoodsQuantity());
//                baseGoods.setAcceptanceGoodsInfoId(goodsInfo.getId());
//                baseGoods.setAcceptanceBasicInfoId(goodsInfo.getAcceptanceBasicInfoId());
//                return baseGoods;
//            }).collect(Collectors.toList());
//
//            //计算销售质保金
//            SalesContractRetentionInfo salesContractRetention = getSalesContractRetentionInfo(businessNumber);
//            if (salesContractRetention != null && salesContractRetention.getRetention() == 1) {
//                if (salesContractRetention.getLimit().equals(1)) {
//                    //如果质保金有上限，校正销售质保金金额
//                    BigDecimal retentionLimit = salesContractRetention.getRetentionLimit();
//                    if (retentionLimit == null) {
//                        throw new BusinessException(CodeUtil.FAIL, "销售质保金上限不能为空");
//                    }
//                    BigDecimal surplus = retentionLimit.subtract(occupationSalesRetention);
//                    if (surplus.compareTo(BigDecimal.ZERO) > 0) {
//                        goodsList = calculateSalesGuaranteeMoney(surplus, goodsList);
//                    } else if (surplus.compareTo(BigDecimal.ZERO) == 0) {
//                        for (BaseGoods baseGoods : goodsList) {
//                            baseGoods.setSalesGuaranteeMoney(BigDecimal.ZERO.setScale(4, BigDecimal.ROUND_HALF_UP));
//                        }
//                    }
//                }
//            }
//
//            //计算采购质保金
//            PurchContractRetentionInfo purchContractRetention = getPurchContractRetentionInfo(businessNumber, supplierId);
//            if (purchContractRetention != null && purchContractRetention.getRetention() == 1) {
//                if (purchContractRetention.getHasLimit().equals(1)) {
//                    //如果质保金有上限，校正销售质保金金额
//                    BigDecimal retentionLimit = purchContractRetention.getRetentionLimit();
//                    if (retentionLimit == null) {
//                        throw new BusinessException(CodeUtil.FAIL, "采购质保金上限不能为空");
//                    }
//                    BigDecimal surplus = retentionLimit.subtract(occupationPurchRetention);
//                    if (surplus.compareTo(BigDecimal.ZERO) > 0) {
//                        goodsList = calculatePurchGuaranteeMoney(surplus, goodsList);
//                    } else if (surplus.compareTo(BigDecimal.ZERO) == 0) {
//                        for (BaseGoods baseGoods : goodsList) {
//                            baseGoods.setPurchaseGuaranteeMoney(BigDecimal.ZERO);
//                        }
//                    }
//                }
//            }
//            return goodsList;
//        }

        return null;
    }

//    public BaseGoods calculate(String businessNumber, Long supplierId, BigDecimal salesPrice, BigDecimal goodsQuantity) {
//        BaseGoods goodsInfo = new BaseGoods();
//        //计算销售总价=销售单价*数量，保留4位小数
//        salesPrice = salesPrice == null ? BigDecimal.ZERO : salesPrice;
//        BigDecimal salesTotalPrice = salesPrice.multiply(goodsQuantity)
//                .setScale(4, RoundingMode.HALF_UP);
//        goodsInfo.setSalesTotalPrice(salesTotalPrice);
//
//        //计算销售质保金=销售总价*销售合同中的质保金比例
//        SalesContractRetentionInfo retentionInfo = getSalesContractRetentionInfo(businessNumber);
//        if (retentionInfo != null && retentionInfo.getRetention() == 1) {
//            BigDecimal salesGuaranteeMoney = salesTotalPrice.multiply(retentionInfo.getRetentionPercent())
//                    .divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
//            goodsInfo.setSalesGuaranteeMoney(salesGuaranteeMoney);
//        }
//        //计算采购相关金额
//        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.findByBusinessNumberAndSupplierId(businessNumber, supplierId);
//        PurchContractPriceRule priceRule = purchContractPriceRuleService.getOne(new QueryWrapper<PurchContractPriceRule>()
//                .eq("purch_contract_basic_info_id", purchContractBasicInfo.getId()));
//
//        BigDecimal purchasePrice = null;
//        if (priceRule.getAccrualMarginCalcMethod().equals(dictService.getByCode(PurchAccrualMarginCalcMethodDict.ChildEnum.FIXED_AMOUNT.getCode()).getId())) {
//            //如果利差计算规则=固定差额  采购单价=销售单价-差额
//            purchasePrice = salesPrice.subtract(priceRule.getDifferAmount() == null ? BigDecimal.ZERO : priceRule.getDifferAmount());
//        }
//        if (priceRule.getAccrualMarginCalcMethod().equals(dictService.getByCode(PurchAccrualMarginCalcMethodDict.ChildEnum.FIXED_INTEREST.getCode()).getId())) {
//            //如果利差计算规则=固定利率 采购单价=销售单价-销售单价*(月利率)*（预估保理融资期限/30），--不足30按30算
//            //月利率
//            BigDecimal monthlyRate = priceRule.getMonthlyInterestRate().divide(new BigDecimal(100));
//            //预估保理融资期限/30），--不足30按30算
//            BigDecimal param = new BigDecimal(priceRule.getFactoringFinanceDeadline()).divide(new BigDecimal("30"), RoundingMode.UP);
//            purchasePrice = salesPrice.subtract(salesPrice.multiply(monthlyRate).multiply(param)).setScale(4, RoundingMode.HALF_UP);
//        }
//        goodsInfo.setPurchasePrice(purchasePrice);
//
//        //采购总价
//        BigDecimal purchaseTotalPrice = purchasePrice.multiply(goodsQuantity).setScale(4, RoundingMode.HALF_UP);
//        goodsInfo.setPurchaseTotalPrice(purchaseTotalPrice);
//
//        //采购质保金
//        PurchContractRetentionInfo purchContractRetentionInfo = purchContractRetentionInfoService.getOne(new QueryWrapper<PurchContractRetentionInfo>()
//                .eq("purch_contract_basic_info_id", purchContractBasicInfo.getId()));
//        if (purchContractRetentionInfo != null && purchContractRetentionInfo.getRetention() == 1) {
//            BigDecimal purchaseGuaranteeMoney = purchaseTotalPrice.multiply(purchContractRetentionInfo.getRetentionPercent())
//                    .divide(new BigDecimal(100), 4, RoundingMode.HALF_UP);
//            goodsInfo.setPurchaseGuaranteeMoney(purchaseGuaranteeMoney);
//        }
//        return goodsInfo;
//    }

    public List<BaseGoods> calculateSalesGuaranteeMoney(BigDecimal surplusAmount, List<BaseGoods> goodsList) {

        //分配销售质保金
        BigDecimal guaranteeMoneyTotal = goodsList.stream().filter(goods -> goods.getSalesGuaranteeMoney() != null)
                .map(BaseGoods::getSalesGuaranteeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (surplusAmount.compareTo(guaranteeMoneyTotal) >= 0) {
            //如果质保金上限大于等于货物质保金之和
            return goodsList;
        } else {
            //如果质保金上限小于货物质保金之和，需要重新分配
            for (BaseGoods baseGoods : goodsList) {
                if (baseGoods.getSalesGuaranteeMoney() != null) {
                    BigDecimal currentGuaranteeMoney = baseGoods.getSalesGuaranteeMoney();
                    if (baseGoods.getSalesGuaranteeMoney().compareTo(surplusAmount) >= 0) {
                        currentGuaranteeMoney = surplusAmount.setScale(4, RoundingMode.HALF_UP);
                    }
                    baseGoods.setSalesGuaranteeMoney(currentGuaranteeMoney);
                    surplusAmount = surplusAmount.subtract(currentGuaranteeMoney);
                }
            }
        }
        return goodsList;
    }

    public List<BaseGoods> calculatePurchGuaranteeMoney(BigDecimal surplusAmount, List<BaseGoods> goodsList) {

        //分配采购质保金
        BigDecimal guaranteeMoneyTotal = goodsList.stream().filter(goods -> goods.getPurchaseGuaranteeMoney() != null)
                .map(BaseGoods::getPurchaseGuaranteeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (surplusAmount.compareTo(guaranteeMoneyTotal) >= 0) {
            //如果质保金上限大于等于货物质保金之和
            return goodsList;
        } else {
            //如果质保金上限小于货物质保金之和，需要重新分配
            for (BaseGoods baseGoods : goodsList) {
                if (baseGoods.getPurchaseGuaranteeMoney() != null) {
                    BigDecimal currentGuaranteeMoney = baseGoods.getPurchaseGuaranteeMoney();
                    if (baseGoods.getPurchaseGuaranteeMoney().compareTo(surplusAmount) >= 0) {
                        currentGuaranteeMoney = surplusAmount.setScale(4, RoundingMode.HALF_UP);
                    }
                    baseGoods.setPurchaseGuaranteeMoney(currentGuaranteeMoney);
                    surplusAmount = surplusAmount.subtract(currentGuaranteeMoney);
                }
            }
        }
        return goodsList;
    }


    /**
     * 获取销售质保金信息
     *
     * @param businessNumber
     * @return
     */
//    public SalesContractRetentionInfo getSalesContractRetentionInfo(String businessNumber) {
//        CSalesContract salesContractManagement = salesContractService.getByBusinessNumber(businessNumber);
//        if (salesContractManagement == null || salesContractManagement.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "销售合同管理不能为空");
//        }
//        CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.getOne(new QueryWrapper<CSalesContractBasicInfo>()
//                        .eq("",salesContractManagement.getId()));
//        if (salesContractBasicInfo == null || salesContractBasicInfo.getId() == null) {
//            throw new BusinessException(CodeUtil.FAIL, "销售合同基础信息不能为空");
//        }
//        return salesContractRetentionInfoService.findByBasicInfoId(salesContractBasicInfo.getId());
//    }

    public PurchContractRetentionInfo getPurchContractRetentionInfo(String businessNumber, Long supplierId) {

        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.findByBusinessNumberAndSupplierId(businessNumber, supplierId);
        if (purchContractBasicInfo != null && purchContractBasicInfo.getId() != null) {
            return purchContractRetentionInfoService.getOne(new QueryWrapper<PurchContractRetentionInfo>()
                    .eq("purch_contract_basic_info_id", purchContractBasicInfo.getId()));
        }
        return null;
    }
}
