package com.fjhx.sale.service.statement.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjhx.account.entity.account.vo.AccountRequestFundsDetailVo;
import com.fjhx.account.entity.tax.po.TaxRefundDetails;
import com.fjhx.account.service.account.AccountRequestFundsDetailService;
import com.fjhx.account.service.account.AccountRunningWaterService;
import com.fjhx.account.service.tax.TaxRefundDetailsService;
import com.fjhx.common.entity.currency.po.CurrencyRate;
import com.fjhx.common.enums.FlowStatusEnum1;
import com.fjhx.common.service.currency.CurrencyRateService;
import com.fjhx.customer.service.customer.CustomerService;
import com.fjhx.purchase.entity.pay.po.Pay;
import com.fjhx.purchase.entity.purchase.enums.PurchaseStatusEnum;
import com.fjhx.purchase.entity.purchase.po.Purchase;
import com.fjhx.purchase.service.pay.PayDetailService;
import com.fjhx.purchase.service.purchase.PurchaseService;
import com.fjhx.sale.entity.claim.po.ClaimContract;
import com.fjhx.sale.entity.contract.bo.ContractCurrencyRate;
import com.fjhx.sale.entity.contract.dto.ContractSelectDto;
import com.fjhx.sale.entity.contract.po.Contract;
import com.fjhx.sale.entity.contract.vo.ContractBudgetVo;
import com.fjhx.sale.entity.contract.vo.ContractVo;
import com.fjhx.sale.entity.statement.dto.ProfitSettlementDto;
import com.fjhx.sale.entity.statement.vo.ProfitSettlementVo;
import com.fjhx.sale.service.claim.ClaimContractService;
import com.fjhx.sale.service.contract.ContractService;
import com.fjhx.sale.service.statement.SaleStatementService;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.system.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SaleStatementServiceImpl implements SaleStatementService {

    @Autowired
    private ContractService contractService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private CurrencyRateService currencyRateService;

    @Autowired
    private TaxRefundDetailsService taxRefundDetailsService;

    @Autowired
    private ClaimContractService claimContractService;

    @Autowired
    private PayDetailService payDetailService;

    @Autowired
    private PurchaseService purchaseService;

    @Autowired
    private AccountRequestFundsDetailService accountRequestFundsDetailService;

    @Override
    public Page<ProfitSettlementVo> getProfitSettlement(ProfitSettlementDto dto) {
        Page<ContractVo> contractPage = contractService.getProfitSettlement(dto);
        List<ContractVo> records = contractPage.getRecords();
        if (records.size() == 0) {
            return new Page<>();
        }
        // 转换为vo
        List<ProfitSettlementVo> list = createResultList(records);
        // 赋值业务员名称
        UserUtil.assignmentNickName(list, ProfitSettlementVo::getUserId, ProfitSettlementVo::setUserName);
        // 赋值客户名称
        customerService.attributeAssign(list, ProfitSettlementVo::getCustomerId, (item, customer) -> {
            item.setCustomerName(customer.getName());
        });
        //赋值合同到账金额、退税金额、采购金额
        setContractArrivalAndRefundMoney(list,1);
        // 计算
        calculation(list);
        // 转page
        return toPage(contractPage, list);
    }

    /**
     * 利润结算表头部统计
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> getProfitSettlementHead(ProfitSettlementDto dto) {
        List<ContractVo> records = contractService.getProfitSettlementHead(dto);
        if (records.size() == 0) {
            return new HashMap<>();
        }
        // 转换为vo
        List<ProfitSettlementVo> list = createResultList(records);
        //赋值合同到账金额、退税金额、采购金额
        setContractArrivalAndRefundMoney(list,2);
        // 计算
        calculation(list);

        return sumData(list);
    }

    /**
     * 获取单条合同汇率
     */
    private Map<Long, Map<String, BigDecimal>> getDetailsRateMap(
            List<ContractVo> records, Map<String, BigDecimal> defaultRateMap) {

        HashMap<Long, Map<String, BigDecimal>> result = new HashMap<>();

        for (Contract record : records) {

            Map<String, BigDecimal> map;

            // 明细数据税率
            String currencyRateJson = record.getCurrencyRateJson();
            if (!StrUtil.isBlank(currencyRateJson)) {
                List<ContractCurrencyRate> contractCurrencyRates = JSON.parseArray(currencyRateJson, ContractCurrencyRate.class);

                map = contractCurrencyRates.stream()
                        .collect(Collectors.toMap(ContractCurrencyRate::getType, ContractCurrencyRate::getRate));

                defaultRateMap.forEach(map::putIfAbsent);

            } else {
//                map = new HashMap<>(defaultRateMap);
                map = new HashMap<>();
                map.put(record.getCurrency(), record.getRate());
            }

            result.put(record.getId(), map);
        }

        return result;
    }

//    /**
//     * 获取合同分页
//     */
//    private Page<Contract> getContractPage(ProfitSettlementDto dto) {
//
//        IWrapper<Contract> wrapper = IWrapper.getWrapper();
//        wrapper.orderByDesc(Contract::getCreateTime);
//        wrapper.between(Contract::getStatus, FlowStatusEnum1.PASS.getKey(), FlowStatusEnum1.UPDATE.getKey() - 1);
//        if(ObjectUtil.isNotEmpty(dto.getSettlementStatus())){
//            wrapper.eq( Contract::getSettlementStatus, dto.getSettlementStatus());
//        }
//        if(ObjectUtil.isNotEmpty(dto.getUserId())){
//            wrapper.eq( Contract::getCreateUser, dto.getUserId());
//        }
//        if(StringUtil.isNotEmpty(dto.getKeyword())){
//            wrapper.like(Contract::getCode,dto.getKeyword());
//        }
//        if(dto.getIsArrival()==1){//已到账----//预付比例等于0||到账认领金额 >= 合同金额 * 预付比例%
//            wrapper.eq(Contract::getAdvanceRatio,"0");
//        }
//        Page<Contract> page = contractService.page(dto.getPage(),wrapper);
//        return page;
//    }

    /**
     * 创建结果集list
     */
    private List<ProfitSettlementVo> createResultList(List<ContractVo> records) {

        return records.stream().map(item -> {
            ProfitSettlementVo profitSettlementVo = new ProfitSettlementVo();
            profitSettlementVo.setContractId(item.getId());
            profitSettlementVo.setContractCode(item.getCode());
            profitSettlementVo.setCustomerId(item.getBuyCorporationId());
            profitSettlementVo.setUserId(item.getCreateUser());
            profitSettlementVo.setContractAmount(item.getAmount());
            profitSettlementVo.setCurrency(item.getCurrency());
            profitSettlementVo.setRate(item.getRate());
            profitSettlementVo.setCurrencyRateJson(item.getCurrencyRateJson());
            profitSettlementVo.setSettlementStatus(item.getSettlementStatus());

            return profitSettlementVo;
        }).collect(Collectors.toList());

    }

    /**
     * 获取默认汇率
     */
    private Map<String, BigDecimal> getDefaultRateMap() {
        List<CurrencyRate> list = currencyRateService.list();
        return list.stream().collect(Collectors.toMap(CurrencyRate::getType, CurrencyRate::getRate));
    }

    /**
     * 赋值合同到账金额、退税金额、采购金额
     * type:1 列表 2头部
     */
    private void setContractArrivalAndRefundMoney(List<ProfitSettlementVo> list,int type) {
        List<CurrencyRate> currencyRateList = currencyRateService.list();

        List<String> currencyList = new ArrayList<>();
        // 合同id
        List<Long> contractIdList = list.stream().map(ProfitSettlementVo::getContractId).collect(Collectors.toList());
        //通过合同ID查询到账认领合同的数据
        List<ClaimContract> claimContractList = claimContractService.getListByContractIds(contractIdList);
        Map<Long, List<ClaimContract>> claimContractMap = claimContractList.stream().collect(Collectors.groupingBy(ClaimContract::getContractId));

        //通过合同ID查询到退税数据
        List<TaxRefundDetails> refundDetails = taxRefundDetailsService.getSumMoneyByContractIds(contractIdList);
        Map<Long, List<TaxRefundDetails>> refundDetailsMap = refundDetails.stream().collect(Collectors.groupingBy(TaxRefundDetails::getContractId));

        //通过合同IDS查询出采购数据
        List<Purchase> purchaseList = purchaseService.list(q -> q.in(Purchase::getDataResourceId, contractIdList).ge(Purchase::getPurchaseStatus, PurchaseStatusEnum.PASS.getKey()).lt(Purchase::getPurchaseStatus, FlowStatusEnum1.UPDATE.getKey()));
        Map<Long, List<Purchase>> purchaseMap = purchaseList.stream().collect(Collectors.groupingBy(Purchase::getDataResourceId));

        //通过合同ID查询出请款数据
        List<AccountRequestFundsDetailVo> accountRequestFundsDetailVoList = accountRequestFundsDetailService.getListByContractIds(contractIdList);
        Map<Long, List<AccountRequestFundsDetailVo>> accountRequestFundsDetailVoMap = accountRequestFundsDetailVoList.stream().collect(Collectors.groupingBy(AccountRequestFundsDetailVo::getContractId));

        //通过合同ID查询出采购数据
        List<Pay> pays = payDetailService.getPayDetailListByContractIds(contractIdList);
        Map<Long, List<Pay>> payMap = pays.stream().collect(Collectors.groupingBy(Pay::getContractId));

        for (ProfitSettlementVo p : list) {
            currencyList.add(p.getCurrency());
            if (StringUtil.isNotEmpty(p.getCurrencyRateJson())) {//取设置的汇率
                List<CurrencyRate> assignCurrencyRatesList = JSON.parseArray(p.getCurrencyRateJson(), CurrencyRate.class);
                Map<String, BigDecimal> assignCurrencyRatesMap = assignCurrencyRatesList.stream().collect(Collectors.toMap(CurrencyRate::getType, CurrencyRate::getRate));
                /**
                 * 处理到账金额
                 */
                List<ClaimContract> cList = claimContractMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(cList)) {
                    BigDecimal contractArrival = cList.stream().map(claimContract -> {
                        //获取汇率
                        BigDecimal rate = assignCurrencyRatesMap.getOrDefault(claimContract.getCurrency(), BigDecimal.ONE);
                        // 获取认领金额
                        BigDecimal money = claimContract.getMoney();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setContractArrival(contractArrival);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(cList, ClaimContract::getCreateUser, ClaimContract::setUserName);
                        p.setClaimList(cList);
                        currencyList.addAll(cList.stream().map(ClaimContract::getCurrency).collect(Collectors.toList()));
                    }

                }
                /**
                 * 处理退税金额
                 */
                List<TaxRefundDetails> rList = refundDetailsMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(rList)) {
                    BigDecimal taxReturnMoney = rList.stream().map(taxRefundDetails -> {
                        //获取汇率
                        BigDecimal rate = assignCurrencyRatesMap.getOrDefault(taxRefundDetails.getCurrency(), BigDecimal.ONE);
                        // 获取认领金额
                        BigDecimal money = taxRefundDetails.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setTaxReturnMoney(taxReturnMoney);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(rList, TaxRefundDetails::getCreateUser, TaxRefundDetails::setUserName);
                        p.setTaxReturnList(rList);
                        currencyList.addAll(rList.stream().map(TaxRefundDetails::getCurrency).collect(Collectors.toList()));
                    }

                }
                /**
                 * 处理采购金额
                 */
                List<Purchase> pList = purchaseMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(pList)) {

                    BigDecimal purchaseAmount = pList.stream().map(purchase -> {
                        //获取汇率
                        BigDecimal rate = assignCurrencyRatesMap.getOrDefault(purchase.getCurrency(), BigDecimal.ONE);
                        // 获取认领金额
                        BigDecimal money = purchase.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setPurchaseAmount(purchaseAmount);
                    if(type==1){
                        p.setPurchaseList(pList);
                        currencyList.addAll(pList.stream().map(Purchase::getCurrency).collect(Collectors.toList()));
                    }
                }
                /**
                 * 处理支付款金额
                 */
                List<Pay> payList = payMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(payList)) {
                    BigDecimal payAmount = payList.stream().map(pay -> {
                        //获取汇率
                        BigDecimal rate = pay.getRate()==null?BigDecimal.ONE:pay.getRate();
                        // 获取金额
                        BigDecimal money = pay.getAmount()==null?BigDecimal.ZERO:pay.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setPayForGoods(payAmount);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(payList, Pay::getCreateUser, Pay::setUserName);
                        p.setPayList(payList);
                        currencyList.addAll(payList.stream().map(Pay::getCurrency).collect(Collectors.toList()));
                    }
                }
                /**
                 * 其他收入金额
                 */
                List<AccountRequestFundsDetailVo> accountRequestFundsDetailVos = accountRequestFundsDetailVoMap.getOrDefault(p.getContractId(), null);
//                List<AccountRequestFundsDetailVo> accountRequestFundsDetailVos = accountRequestFundsDetailService.getListByContractId(p.getContractId());
                if (CollectionUtils.isNotEmpty(accountRequestFundsDetailVos)) {
                    BigDecimal otherExpenses = accountRequestFundsDetailVos.stream().map(acc -> {
                        //获取汇率
                        BigDecimal rate = assignCurrencyRatesMap.getOrDefault(acc.getCurrency(), BigDecimal.ONE);
                        // 获取认领金额
                        BigDecimal money = acc.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setOtherExpenses(otherExpenses);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(accountRequestFundsDetailVos, AccountRequestFundsDetailVo::getCreateUser, AccountRequestFundsDetailVo::setUserName);
                        p.setAccountRequestFundsDetailList(accountRequestFundsDetailVos);
                        currencyList.addAll(accountRequestFundsDetailVos.stream().map(AccountRequestFundsDetailVo::getCurrency).collect(Collectors.toList()));
                    }

                }
            } else {//取数据汇率
                /**
                 * 处理到账金额
                 */
                List<ClaimContract> cList = claimContractMap.getOrDefault(p.getContractId(), new ArrayList<>());
//                List<Long> warterIds = cList.stream().distinct().map(ClaimContract::getBusinessId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(cList)) {
//                    //查出流水
//                    List<AccountRunningWater> accountRunningWaterList = accountRunningWaterService.list(Wrappers.<AccountRunningWater>query().lambda().in(AccountRunningWater::getId, warterIds));
//                    Map<Long, BigDecimal> waterMap = accountRunningWaterList.stream().collect(Collectors.toMap(AccountRunningWater::getId, AccountRunningWater::getRate));
                    BigDecimal contractArrival = cList.stream().map(claimContract -> {
                        //获取汇率
                        BigDecimal rate = claimContract.getRate();
                        // 获取金额
                        BigDecimal money = claimContract.getMoney();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setContractArrival(contractArrival);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(cList, ClaimContract::getCreateUser, ClaimContract::setUserName);
                        p.setClaimList(cList);
                        currencyList.addAll(cList.stream().map(ClaimContract::getCurrency).collect(Collectors.toList()));
                    }

                }
                /**
                 * 处理退税金额
                 */
                List<TaxRefundDetails> rList = refundDetailsMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(rList)) {
                    BigDecimal taxReturnMoney = rList.stream().map(taxRefundDetails -> {
                        //获取汇率
                        BigDecimal rate = taxRefundDetails.getRate();
                        // 获取认领金额
                        BigDecimal money = taxRefundDetails.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setTaxReturnMoney(taxReturnMoney);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(rList, TaxRefundDetails::getCreateUser, TaxRefundDetails::setUserName);
                        p.setTaxReturnList(rList);
                        currencyList.addAll(rList.stream().map(TaxRefundDetails::getCurrency).collect(Collectors.toList()));
                    }

                }
                /**
                 * 处理采购金额
                 */
                List<Purchase> pList = purchaseMap.getOrDefault(p.getContractId(), null);

                if (CollectionUtils.isNotEmpty(pList)) {
                    BigDecimal purchaseAmount = pList.stream().map(purchase -> {
                        //获取汇率
                        BigDecimal rate = purchase.getRate() == null ? BigDecimal.ONE : purchase.getRate();
                        // 获取认领金额
                        BigDecimal money = purchase.getAmount() == null ? BigDecimal.ZERO : purchase.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setPurchaseAmount(purchaseAmount);
                    if(type==1){
                        p.setPurchaseList(pList);
                        currencyList.addAll(pList.stream().map(Purchase::getCurrency).collect(Collectors.toList()));
                    }
                }
                /**
                 * 处理支付款金额
                 */
                List<Pay> payList = payMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(payList)) {
                    BigDecimal payAmount = payList.stream().map(pay -> {
                        //获取汇率
                        BigDecimal rate = pay.getRate()==null?BigDecimal.ONE:pay.getRate();
                        // 获取认领金额
                        BigDecimal money = pay.getAmount()==null?BigDecimal.ZERO:pay.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setPayForGoods(payAmount);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(payList, Pay::getCreateUser, Pay::setUserName);
                        p.setPayList(payList);
                        currencyList.addAll(payList.stream().map(Pay::getCurrency).collect(Collectors.toList()));
                    }
                }
                /**
                 * 其他收入金额
                 */
                List<AccountRequestFundsDetailVo> accountRequestFundsDetailVos = accountRequestFundsDetailVoMap.getOrDefault(p.getContractId(), null);
                if (CollectionUtils.isNotEmpty(accountRequestFundsDetailVos)) {
                    BigDecimal otherExpenses = accountRequestFundsDetailVos.stream().map(acc -> {
                        //获取汇率
                        BigDecimal rate = acc.getRate() == null ? BigDecimal.ZERO : acc.getRate();
                        // 获取认领金额
                        BigDecimal money = acc.getAmount();
                        // 返回兑人民币后金额
                        return rate.multiply(money);
                    }).reduce(BigDecimal.ZERO, BigDecimal::add);
                    p.setOtherExpenses(otherExpenses);
                    if(type==1){
                        // 赋值业务员名称
                        UserUtil.assignmentNickName(accountRequestFundsDetailVos, AccountRequestFundsDetailVo::getCreateUser, AccountRequestFundsDetailVo::setUserName);
                        p.setAccountRequestFundsDetailList(accountRequestFundsDetailVos);
                        currencyList.addAll(accountRequestFundsDetailVos.stream().map(AccountRequestFundsDetailVo::getCurrency).collect(Collectors.toList()));
                    }

                }
            }
            if(type==1){
                p.setCurrencyList(currencyRateList.stream()
                        .filter((CurrencyRate c) ->currencyList.contains(c.getType()))
                        .collect(Collectors.toList()));
            }
        }
    }

    /**
     * 利润结算表头部统计
     * @param dto
     * @return
     */
    @Override
    public Page<ContractBudgetVo> getProfitClearingPageHeadStatistics(ContractSelectDto dto) {
        return null;
    }

    /**
     * 赋值采购合同金额和支付货款
     */
    private void setPurchaseAmountAndPayForGoods(
            List<ProfitSettlementVo> list, Map<Long, Map<String, BigDecimal>> detailsRateMap) {
//
//        // 合同id
//        List<Long> contractIdList = list.stream().map(ProfitSettlementVo::getContractId).collect(Collectors.toList());
//
//        List<Purchase> purchaseList = purchaseService.list(q -> q.in(Purchase::getDataResourceId, contractIdList));
//
//        Map<Long,List<Purchase>> purchaseMap = purchaseList.stream().collect(Collectors.groupingBy(Purchase::getDataResourceId));
//        if (purchaseList.size() == 0) {
//            purchaseList.forEach(item -> item.setAmount(BigDecimal.ZERO));
//            return;
//        }

//        List<Long> purchaseIdList = purchaseDetailList.stream().map(PurchaseDetail::getPurchaseId).collect(Collectors.toList());
//        List<Purchase> purchaseList = purchaseService.listByIds(purchaseIdList);

//        // 采购id 币种 map
//        Map<Long, String> purchaseIdCurrencyMap = purchaseList.stream()
//                .collect(Collectors.toMap(BaseIdPo::getId, Purchase::getCurrency));

//        // 合同id 申购单列表 map
//        Map<Long, List<PurchaseDetail>> contractIdPurchaseDetailListMap = purchaseDetailList.stream()
//                .collect(Collectors.groupingBy(PurchaseDetail::getDataResourceId));

//        for (ProfitSettlementVo profitSettlementVo : list) {
//
//            // 合同id
//            Long contractId = profitSettlementVo.getContractId();
//            List<Purchase> pList = purchaseMap.getOrDefault(contractId,null);
//
////            // 申购单
////            List<PurchaseDetail> itemPurchaseDetailList = contractIdPurchaseDetailListMap.getOrDefault(contractId, new ArrayList<>());
//
//            // 汇率币种map
//            Map<String, BigDecimal> map = detailsRateMap.getOrDefault(contractId, new HashMap<>());
//
//            BigDecimal purchaseAmount = itemPurchaseDetailList.stream().map(purchaseDetail -> {
//
//                // 根据申购单id获取币种
//                String currency = purchaseIdCurrencyMap.get(purchaseDetail.getPurchaseId());
//
//                // 根据币种获取汇率
//                BigDecimal rate = map.getOrDefault(currency, BigDecimal.ONE);
//
//                // 获取申购金额
//                BigDecimal money = purchaseDetail.getAmount();
//
//                // 返回兑人民币后金额
//                return rate.multiply(money);
//
//            }).reduce(BigDecimal.ZERO, BigDecimal::add);
//
//            profitSettlementVo.setPurchaseAmount(purchaseAmount);
//
//        }

    }

    /**
     * 计算
     */
    private void calculation(List<ProfitSettlementVo> list) {

        for (ProfitSettlementVo profitSettlementVo : list) {

            // 收入
            BigDecimal totalIncome = profitSettlementVo.getOtherIncome().add(profitSettlementVo.getContractArrival().add(profitSettlementVo.getTaxReturnMoney()));
            profitSettlementVo.setTotalIncome(totalIncome);

            // 支出
            BigDecimal totalExpenses = profitSettlementVo.getOtherExpenses().add(profitSettlementVo.getPayForGoods());
            profitSettlementVo.setTotalExpenses(totalExpenses);

            // 毛利
            BigDecimal grossProfit = totalIncome.subtract(totalExpenses);
            profitSettlementVo.setGrossProfit(grossProfit);

            if (totalIncome.equals(BigDecimal.ZERO)) {
                profitSettlementVo.setGrossProfitMargin(BigDecimal.ZERO);
            } else {
                profitSettlementVo.setGrossProfitMargin(
                        new BigDecimal("100").multiply(grossProfit).divide(totalIncome, 2, RoundingMode.HALF_UP)
                );
            }

        }

    }

    /**
     * 统计数据
     */
    private Map<String,Object> sumData(List<ProfitSettlementVo> list) {
        Map<String,Object> map = new HashMap<>();
        BigDecimal contractSumAmount = BigDecimal.ZERO;
        BigDecimal purchaseSumAmount = BigDecimal.ZERO;
        BigDecimal contractArrivalSumAmount = BigDecimal.ZERO;
        BigDecimal taxReturnMoneySumAmount = BigDecimal.ZERO;
        BigDecimal otherIncomeSumAmount = BigDecimal.ZERO;
        BigDecimal payForGoodsSumAmount = BigDecimal.ZERO;
        BigDecimal otherExpensesSumAmount = BigDecimal.ZERO;
        BigDecimal totalIncomeSumAmount = BigDecimal.ZERO;
        BigDecimal totalExpensesSumAmount = BigDecimal.ZERO;
        BigDecimal grossProfitMargin = BigDecimal.ZERO;
        for (ProfitSettlementVo p : list) {
            contractSumAmount = contractSumAmount.add(ObjectUtil.isEmpty(p.getContractAmount())?BigDecimal.ZERO:p.getContractAmount().multiply(p.getRate()));//合同金额
            contractArrivalSumAmount = contractArrivalSumAmount.add(ObjectUtil.isEmpty(p.getContractArrival())?BigDecimal.ZERO:p.getContractArrival());//合同到账
            taxReturnMoneySumAmount = taxReturnMoneySumAmount.add(ObjectUtil.isEmpty(p.getTaxReturnMoney())?BigDecimal.ZERO:p.getTaxReturnMoney());//退税
            otherIncomeSumAmount = otherIncomeSumAmount.add(ObjectUtil.isEmpty(p.getOtherIncome())?BigDecimal.ZERO:p.getOtherIncome());//其他收入
            payForGoodsSumAmount = payForGoodsSumAmount.add(ObjectUtil.isEmpty(p.getPayForGoods())?BigDecimal.ZERO:p.getPayForGoods());//支付货款
            otherExpensesSumAmount = otherExpensesSumAmount.add(ObjectUtil.isEmpty(p.getOtherExpenses())?BigDecimal.ZERO:p.getOtherExpenses());//其他支出
            totalIncomeSumAmount = totalIncomeSumAmount.add(ObjectUtil.isEmpty(p.getTotalIncome())?BigDecimal.ZERO:p.getTotalIncome());//收入
            totalExpensesSumAmount = totalExpensesSumAmount.add(ObjectUtil.isEmpty(p.getTotalExpenses())?BigDecimal.ZERO:p.getTotalExpenses());//支出
            purchaseSumAmount = purchaseSumAmount.add(ObjectUtil.isEmpty(p.getPurchaseAmount())?BigDecimal.ZERO:p.getPurchaseAmount());
        }
        //计算总毛利和总毛利率
        BigDecimal grossProfitSum = totalIncomeSumAmount.subtract(totalExpensesSumAmount);//毛利
        if (totalIncomeSumAmount.compareTo(BigDecimal.ZERO)>0) {
            grossProfitMargin = new BigDecimal("100").multiply(grossProfitSum).divide(totalIncomeSumAmount, 2, RoundingMode.HALF_UP);//毛利率
        }
        map.put("GrossProfitMargin",grossProfitMargin.setScale(2, RoundingMode.HALF_UP));
        map.put("contractSumAmount",contractSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("contractCount",list.size());
        map.put("purchaseSumAmount",purchaseSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("contractArrivalSumAmount",contractArrivalSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("taxReturnMoneySumAmount",taxReturnMoneySumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("otherIncomeSumAmount",otherIncomeSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("payForGoodsSumAmount",payForGoodsSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("otherExpensesSumAmount",otherExpensesSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("totalIncomeSumAmount",totalIncomeSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("totalExpensesSumAmount",totalExpensesSumAmount.setScale(2, RoundingMode.HALF_UP));
        map.put("grossProfitSum",grossProfitSum.setScale(2, RoundingMode.HALF_UP));
        return map;
    }

    /**
     * 转page
     */
    private Page<ProfitSettlementVo> toPage(Page<ContractVo> contractPage, List<ProfitSettlementVo> list) {
        Page<ProfitSettlementVo> page = new Page<>();
        page.setTotal(contractPage.getTotal());
        page.setCurrent(contractPage.getCurrent());
        page.setPages(contractPage.getPages());
        page.setSize(contractPage.getSize());
        page.setRecords(list);

        return page;
    }


}
