package com.jwipc.finance.logic.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.convert.AccountStatementDetailConvert;
import com.jwipc.finance.dto.AccountStatementDTO;
import com.jwipc.finance.dto.FastStatementItemDTO;
import com.jwipc.finance.dto.InvoicedApplyItemDTO;
import com.jwipc.finance.dto.StatementItemDTO;
import com.jwipc.finance.entity.AccountStatement;
import com.jwipc.finance.entity.AccountStatementDetail;
import com.jwipc.finance.entity.ReceiveVoucher;
import com.jwipc.finance.logic.AccountStatementDetailLogic;
import com.jwipc.finance.logic.InvoicedApplyDetailLogic;
import com.jwipc.finance.logic.ReceiptVoucherLogic;
import com.jwipc.finance.model.po.AccountStatementPO;
import com.jwipc.finance.model.po.FastStatementItemPO;
import com.jwipc.finance.model.po.InvoicedApplyItemPO;
import com.jwipc.finance.model.po.StatementItemPO;
import com.jwipc.finance.model.query.AccountStatementDetailQuery;
import com.jwipc.finance.model.query.CreateInvoicedApplyPageQuery;
import com.jwipc.finance.model.query.CreateInvoicedApplyQuery;
import com.jwipc.finance.model.query.ReceiveVoucherQuery;
import com.jwipc.finance.service.IAccountStatementDetailService;
import com.jwipc.finance.service.IAccountStatementService;
import com.jwipc.finance.service.IReceiveVoucherService;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.prop.PriceHandle;
import com.jwipc.query.BasePageQuery;
import com.jwipc.sys.client.ProductClient;
import com.jwipc.sys.client.dto.ProductInfoDTO;
import com.jwipc.util.EasyExcelImportUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

import static com.baomidou.dynamic.datasource.support.DdConstants.SLAVE;

/**
 * @author shenyang.ou
 * @date 2024/3/4 14:00
 * @desc
 */
@Service
@RequiredArgsConstructor
@DS(SLAVE)
public class AccountStatementDetailLogicImpl implements AccountStatementDetailLogic {
    private final AccountStatementDetailConvert accountStatementDetailConvert;
    private final IAccountStatementDetailService accountStatementDetailService;
    private final ReceiptVoucherLogic receiptVoucherLogic;
    private final ProductClient productClient;
    private final InvoicedApplyDetailLogic invoicedApplyDetailLogic;
    private final IAccountStatementService accountStatementService;
    private final IReceiveVoucherService receiveVoucherService;
    private final PriceHandle priceHandle;
    @Override
    public PageView findByStatementIdPage(Long asId) {
        if (asId!=null){
            List<StatementItemPO> statementItemPOS = accountStatementDetailService.findByStatementId(asId);
            List<StatementItemDTO> list = accountStatementDetailConvert.po2DtoList(statementItemPOS);
            // 实时获取对账凭证数据
            final AccountStatement as = accountStatementService.getById(asId);
            this.realTimeReceiveData(
                    list, asId, as.getCompanyCode(), as.getSupplierCode(), DateUtil.format(as.getInStockStartDate(), "yyyy-MM-dd"),
                    DateUtil.format(as.getInStockEndDate(), "yyyy-MM-dd"), as.getOrderType()
            );


            BasePageQuery basePageQuery = new BasePageQuery();
            basePageQuery.setPage(1);
            basePageQuery.setRows(list.size());
            final Page<StatementItemDTO> toPage = PageUtil.toPage(basePageQuery);
            toPage.setRecords(list);
            Map<String,String> materiaNameMap = new HashMap<>();
            BigDecimal notTaxAmount = BigDecimal.ZERO, taxAmount = BigDecimal.ZERO, diffTaxAmount = BigDecimal.ZERO,
                    asDiffAmount = BigDecimal.ZERO, invoicedAmount = BigDecimal.ZERO, surplusAmount = BigDecimal.ZERO,
                    asNtAmount = BigDecimal.ZERO, asItAmount = BigDecimal.ZERO, asDtAmount = BigDecimal.ZERO,
                    storageQuantity = BigDecimal.ZERO, statementQuantity = BigDecimal.ZERO;
            for(StatementItemDTO dto: list){
                notTaxAmount = notTaxAmount.add(dto.getNotTaxAmount() == null?BigDecimal.ZERO:dto.getNotTaxAmount());
                taxAmount = taxAmount.add(dto.getTaxAmount() == null?BigDecimal.ZERO:dto.getTaxAmount());
                diffTaxAmount = diffTaxAmount.add(dto.getDiffTaxAmount() == null?BigDecimal.ZERO:dto.getDiffTaxAmount());
                asDiffAmount = asDiffAmount.add(dto.getAsDiffAmount() == null?BigDecimal.ZERO:dto.getAsDiffAmount());
                invoicedAmount = invoicedAmount.add(dto.getInvoicedAmount() == null?BigDecimal.ZERO:dto.getInvoicedAmount());
                surplusAmount = surplusAmount.add(dto.getSurplusAmount() == null?BigDecimal.ZERO:dto.getSurplusAmount());
                asNtAmount = asNtAmount.add(dto.getAsNtAmount() == null?BigDecimal.ZERO:dto.getAsNtAmount());
                asItAmount = asItAmount.add(dto.getAsItAmount() == null?BigDecimal.ZERO:dto.getAsItAmount());
                asDtAmount = asDtAmount.add(dto.getAsDtAmount() == null?BigDecimal.ZERO:dto.getAsDtAmount());
                statementQuantity = statementQuantity.add(dto.getAsQuantity() == null?BigDecimal.ZERO:dto.getAsQuantity());
                storageQuantity = storageQuantity.add(dto.getReceiveNum() == null?BigDecimal.ZERO:dto.getReceiveNum());
                //设置最新的物料名称，如果物料名称有变化，则取最新的物料名称， 2024-08-14 邓京术
                initMaterialName(dto, materiaNameMap);
            }

            JSONArray footer = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("notTaxAmount", notTaxAmount);
            obj.put("taxAmount", taxAmount);
            obj.put("diffTaxAmount", diffTaxAmount);
            obj.put("asDiffAmount", asDiffAmount);
            obj.put("invoicedAmount", invoicedAmount);
            obj.put("surplusAmount", surplusAmount);
            obj.put("asNtAmount", asNtAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("asItAmount", asItAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("asDtAmount", asDtAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("receiveNum", storageQuantity);
            obj.put("asQuantity", statementQuantity);
            footer.add(obj);
            PageView pageView = PageUtil.getPV(list, list.size());
            pageView.setFooter(footer);
            return pageView;
        }else {
            return null;
        }
    }

    private void initMaterialName(StatementItemDTO po , Map<String,String> materialNameMap) {
        if (materialNameMap.keySet().contains(po.getMaterialCode())) {
            po.setMaterialName(materialNameMap.get(po.getMaterialCode()));
        } else {
            ProductInfoDTO productInfoDTO = productClient.getByMaterialCodeAndFactoryCode(po.getMaterialCode(), po.getFactoryCode());
            if (Objects.nonNull(productInfoDTO)) {
                materialNameMap.put(po.getMaterialCode(), productInfoDTO.getMaterialName());
                po.setMaterialName(productInfoDTO.getMaterialName());
            }
        }
    }

    @Override
    public PageView findByStatementIdAndFactoryCodePage(Long asId, String factoryCode,String removeLists) {
        if (asId!=null){
            List<StatementItemPO> statementItemPOS = accountStatementDetailService.findByStatementIdAndFactoryCode(asId,factoryCode);
            List<StatementItemDTO> list = accountStatementDetailConvert.po2DtoList(statementItemPOS);
            list.forEach(statementItemDTO -> {
                statementItemDTO.setOriginalTaxAmount(statementItemDTO.getOriginalTaxPrice().multiply(statementItemDTO.getMvNum()));
            });
            // 实时获取对账凭证数据
            final AccountStatement as = accountStatementService.getById(asId);
//            this.realTimeReceiveData(
//                    list, asId, as.getCompanyCode(), as.getSupplierCode(), DateUtil.format(as.getInStockStartDate(), "yyyy-MM-dd"),
//                    DateUtil.format(as.getInStockEndDate(), "yyyy-MM-dd"), as.getOrderType()
//            );
            //移除某些符合的项
            if (StringUtils.isNotEmpty(removeLists)){
                List<String> removeList = StrUtil.split(removeLists, ',');
                if (CollectionUtils.isNotEmpty(removeList)){
                    for (String remove : removeList){
                        list.removeIf(statementItemDTO -> (statementItemDTO.getReceiveId().toString()).equals(remove));
                    }
                }
            }

            BasePageQuery basePageQuery = new BasePageQuery();
            basePageQuery.setPage(1);
            basePageQuery.setRows(list.size());
            final Page<StatementItemDTO> toPage = PageUtil.toPage(basePageQuery);
            toPage.setRecords(list);
            Map<String,String> materiaNameMap = new HashMap<>();
            BigDecimal notTaxAmount = BigDecimal.ZERO, taxAmount = BigDecimal.ZERO, diffTaxAmount = BigDecimal.ZERO,
                    asDiffAmount = BigDecimal.ZERO, invoicedAmount = BigDecimal.ZERO, surplusAmount = BigDecimal.ZERO,
                    asNtAmount = BigDecimal.ZERO, asItAmount = BigDecimal.ZERO, asDtAmount = BigDecimal.ZERO,
                    storageQuantity = BigDecimal.ZERO, statementQuantity = BigDecimal.ZERO;
            for(StatementItemDTO dto: list){
                notTaxAmount = notTaxAmount.add(dto.getNotTaxAmount() == null?BigDecimal.ZERO:dto.getNotTaxAmount());
                taxAmount = taxAmount.add(dto.getTaxAmount() == null?BigDecimal.ZERO:dto.getTaxAmount());
                diffTaxAmount = diffTaxAmount.add(dto.getDiffTaxAmount() == null?BigDecimal.ZERO:dto.getDiffTaxAmount());
                asDiffAmount = asDiffAmount.add(dto.getAsDiffAmount() == null?BigDecimal.ZERO:dto.getAsDiffAmount());
                invoicedAmount = invoicedAmount.add(dto.getInvoicedAmount() == null?BigDecimal.ZERO:dto.getInvoicedAmount());
                surplusAmount = surplusAmount.add(dto.getSurplusAmount() == null?BigDecimal.ZERO:dto.getSurplusAmount());
                asNtAmount = asNtAmount.add(dto.getAsNtAmount() == null?BigDecimal.ZERO:dto.getAsNtAmount());
                asItAmount = asItAmount.add(dto.getAsItAmount() == null?BigDecimal.ZERO:dto.getAsItAmount());
                asDtAmount = asDtAmount.add(dto.getAsDtAmount() == null?BigDecimal.ZERO:dto.getAsDtAmount());
                statementQuantity = statementQuantity.add(dto.getAsQuantity() == null?BigDecimal.ZERO:dto.getAsQuantity());
                storageQuantity = storageQuantity.add(dto.getReceiveNum() == null?BigDecimal.ZERO:dto.getReceiveNum());
                //设置最新的物料名称，如果物料名称有变化，则取最新的物料名称， 2024-08-14 邓京术
                initMaterialName(dto, materiaNameMap);
            }

            JSONArray footer = new JSONArray();
            JSONObject obj = new JSONObject();
            obj.put("notTaxAmount", notTaxAmount);
            obj.put("taxAmount", taxAmount);
            obj.put("diffTaxAmount", diffTaxAmount);
            obj.put("asDiffAmount", asDiffAmount);
            obj.put("invoicedAmount", invoicedAmount);
            obj.put("surplusAmount", surplusAmount);
            obj.put("asNtAmount", asNtAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("asItAmount", asItAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("asDtAmount", asDtAmount.setScale(2, BigDecimal.ROUND_HALF_UP));
            obj.put("receiveNum", storageQuantity);
            obj.put("asQuantity", statementQuantity);
            footer.add(obj);
            PageView pageView = PageUtil.getPV(list, list.size());
            pageView.setFooter(footer);
            return pageView;
        }else {
            return null;
        }
    }

    /**
     * 提供创建开票申请时获取对账单明细数据
     *
     * @param query 查询条件
     * @return 结果
     */
    @Override
    public PageView provideCreateInvoicedApply(CreateInvoicedApplyQuery query) {
        List<Long> excludeAsdIdList = Lists.newArrayList();
        if(null != query.getExcludeAsdIds() && StringUtils.isNotEmpty(query.getExcludeAsdIds())){
            final String[] excludeAsdIdArr = StringUtils.split(query.getExcludeAsdIds(), ",");
            for(String id: excludeAsdIdArr){
                excludeAsdIdList.add(Long.parseLong(id));
            }
        }
        if (StringUtils.isNotEmpty(query.getPoTypes())){
            query.setPoTypeList(Arrays.asList(query.getPoTypes().split(",")));
        }
        // 获取已经创建的开票申请的对账单明细ID
        final List<Long> existAsdIdList = invoicedApplyDetailLogic.findExistAsdIdByQuery(query.getSupplierCode(), query.getCompanyCode());
        if(CollectionUtils.isNotEmpty(existAsdIdList)){
            excludeAsdIdList.addAll(existAsdIdList);
        }
        query.setExcludeAsdIdList(excludeAsdIdList);

        List<InvoicedApplyItemDTO> itemList = accountStatementDetailConvert.invoicedApplyItemPO2DTOList(accountStatementDetailService.provideCreateInvoicedApply(query));


        BasePageQuery basePageQuery = new BasePageQuery();
        basePageQuery.setPage(1);
        basePageQuery.setRows(itemList.size());
        final Page<InvoicedApplyItemDTO> toPage = PageUtil.toPage(basePageQuery);
        toPage.setRecords(itemList);
        PageView pageView = PageUtil.getPV(itemList, toPage.getTotal());
        BigDecimal notTaxAmount = BigDecimal.ZERO, taxAmount = BigDecimal.ZERO, diffTaxAmount = BigDecimal.ZERO, statementNum = BigDecimal.ZERO;
        for(InvoicedApplyItemDTO dto: itemList){
            notTaxAmount = notTaxAmount.add(dto.getAsNotTaxAmount());
            taxAmount = taxAmount.add(dto.getAsTaxAmount());
            diffTaxAmount = diffTaxAmount.add(dto.getAsDiffTaxAmount());
            statementNum = statementNum.add(dto.getStatementNum());
        }

        JSONArray footer = new JSONArray();
        JSONObject obj = new JSONObject();
        obj.put("asNotTaxAmount", notTaxAmount);
        obj.put("asTaxAmount", taxAmount);
        obj.put("asDiffTaxAmount", diffTaxAmount);
        obj.put("statementNum", statementNum);
        footer.add(obj);
        pageView.setFooter(footer);
        return pageView;
    }

    /**
     * 提供创建开票申请时获取对账单明细数据(根据对账单id分页)
     *
     * @param query 对账单id
     * @return 结果
     */
    @Override
    public PageView provideCreateInvoicedApplyAsId(CreateInvoicedApplyPageQuery query) {
        final Page<AccountStatementDetail> dbPage = PageUtil.toPage(query);
        List<InvoicedApplyItemPO> inquiryPOS = accountStatementDetailService.provideCreateInvoicedApplyPage(dbPage, query);
        List<InvoicedApplyItemDTO> inquiryDTOS = accountStatementDetailConvert.invoicedApplyItemPO2DTOList(inquiryPOS);
        return PageUtil.getPV(inquiryDTOS, dbPage.getTotal());
    }

    /**
     * 实时获取物料凭证中已开票数量
     *
     * @param query  查询参数
     * @param params 返回数据
     */
    @Override
    public void realTimeReceiveVoucher(ReceiveVoucherQuery query, List<StatementItemDTO> params) {
// 1.创建对账单时, 对账数量 = 剩余可对账数量
        // 2.编辑对账单时, 对账数量不可变动, 除非剩余对账数量小于对账数量
        // 3.SAP的凭证入库数量等于凭证已过账数量时的凭证也能查询到
//        if(CollectionUtils.isNotEmpty(params)){
//            final Map<String, ReceiveVoucher> result = materialVoucherService.realTimeFindData(
//                    query.getCompanyCode(), query.getSupplierCode(), query.getPostTimeStart(), query.getPostTimeEnd(), query.getReceiveType()
//            );
//
//            for(int i = params.size() - 1; i >= 0; i--){
//                StatementItemDTO dto = params.get(i);
//                // 供应商编码+凭证类型+物料凭证年度+物料凭证号+行号+SAP客户端
//                String dataKey = query.getSupplierCode() + query.getReceiveType() + dto.getReceiveYear() + dto.getReceiveCode() + dto.getReceiveRowNo() + dto.getSapClient();
//                if(null != result.get(dataKey)){
//                    ReceiveVoucher rv = result.get(dataKey);
//                    if(dto.getReceiveNum().subtract(rv.getInvoicedNum()).compareTo(BigDecimal.ZERO) == 0){
//                        params.remove(dto);
//                        continue;
//                    }
//
//                    BigDecimal surplusNum = rv.getMvNum().subtract(rv.getInvoicedNum());
//                    BigDecimal surplusAmount = dto.getTaxPrice().multiply(surplusNum).setScale(2, BigDecimal.ROUND_HALF_UP);
//                    dto.setInvoicedAmount(dto.getInvoicedAmount().add(rv.getInvoicedTaxAmount()));
//                    dto.setSurplusAmount(surplusAmount.subtract(rv.getInvoicedTaxAmount()));
//                    dto.setSurplusNum(surplusNum);
//
//                    if(dto.getAsQuantity().compareTo(BigDecimal.ZERO) == 0){
//                        dto.setAsQuantity(surplusNum);
//                    }else {
//                        if(dto.getAsQuantity().compareTo(surplusNum) > 0){
//                            dto.setAsQuantity(surplusNum.subtract(dto.getAsQuantity()));
//                        }else {
//                            dto.setAsQuantity(dto.getAsQuantity());
//                        }
//                    }
//                }
//            }
//        }
    }

    /**
     * 快速创建开票申请的对账单明细列表查询
     *
     * @param query 查询条件
     * @return 结果
     */
    @Override
    public PageView selectFastDataByQuery(AccountStatementDetailQuery query) {
        final Page<AccountStatement> dbPage = PageUtil.toPage(query);
        List<FastStatementItemPO> fastStatementItemPOS = accountStatementDetailService.selectFastDataByQuery(dbPage, query);
        List<FastStatementItemDTO> fastStatementItemDTOS = accountStatementDetailConvert.fastStatementItemPOS2DTOList(fastStatementItemPOS);
        return PageUtil.getPV(fastStatementItemDTOS, dbPage.getTotal());
    }

    @Override
    public List<StatementItemDTO> findByStatementId(Long id,String factoryCode) {
        List<StatementItemPO> statementItemPOS = accountStatementDetailService.findByStatementIdAndFactoryCode(id,factoryCode);
        return accountStatementDetailConvert.po2DtoList(statementItemPOS);
    }

    /**
     * 批量修改价格
     *
     * @param ids        对账明细id
     * @param receiveIds 物料凭证ids
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updatePrice(BigDecimal deductionRatio,String ids, String receiveIds,Long asId) {
        final List<String> idList = Arrays.asList(ids.split(StrUtil.COMMA));
        final List<String> receiveIdList = Arrays.asList(receiveIds.split(StrUtil.COMMA));
        receiptVoucherLogic.updateRatio(receiveIdList,deductionRatio);
        List<AccountStatementDetail> accountStatementDetails = accountStatementDetailService.listByIds(idList);
        accountStatementDetails.forEach(accountStatementDetail -> {
            if(deductionRatio.compareTo(BigDecimal.ZERO)==0){
                //不含税金额 不含税单价*数量
                accountStatementDetail.setNotTaxAmount((accountStatementDetail.getNotTaxPrice().multiply(accountStatementDetail.getReceiveNum())));
                //含税金额 原含税单价*数量
                accountStatementDetail.setTaxAmount((accountStatementDetail.getTaxPrice().multiply(accountStatementDetail.getReceiveNum())));
            }else {
                //不含税金额 不含税单价*数量-其他折扣  2024-12-31 保留两位
               accountStatementDetail.setNotTaxAmount((accountStatementDetail.getNotTaxPrice().multiply(accountStatementDetail.getReceiveNum()).subtract(deductionRatio)));
                //不含税单价 不含税金额/数量
//            accountStatementDetail.setNotTaxPrice(accountStatementDetail.getNotTaxAmount().divide(accountStatementDetail.getReceiveNum(), priceHandle.getPrecision(), priceHandle.getCutType()==0?RoundingMode.HALF_UP:RoundingMode.HALF_DOWN));
                BigDecimal taxAdd = accountStatementDetail.getTaxValue().add(new BigDecimal(1));
                //含税单价 未税单价*（1+税率）
//            accountStatementDetail.setTaxPrice(accountStatementDetail.getNotTaxPrice().multiply(taxAdd));
                //含税金额 含税单价*数量
//            accountStatementDetail.setTaxAmount(accountStatementDetail.getReceiveNum().multiply(accountStatementDetail.getTaxPrice()));
                //含税金额 未税金额*（1+税率） 2024-12-31 结果保留两位
                accountStatementDetail.setTaxAmount((accountStatementDetail.getNotTaxAmount().multiply(taxAdd)));
                //税额 含税金额-未税金额
                accountStatementDetail.setDiffTaxAmount(accountStatementDetail.getTaxAmount().subtract(accountStatementDetail.getNotTaxAmount()));
            }

        });
        accountStatementDetailService.updateBatchById(accountStatementDetails);
        this.updateAccountStatementAmount(asId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRES_NEW)
    public void updateAccountStatementAmount(Long asId){
        //重新计算对账总金额
        List<AccountStatementDetail> asdList = accountStatementDetailService.list(Wrappers.lambdaQuery(AccountStatementDetail.class).eq(AccountStatementDetail::getAsId,asId));
        BigDecimal notTaxAmount = BigDecimal.ZERO, taxAmount = BigDecimal.ZERO;
        for(AccountStatementDetail dto: asdList){
            notTaxAmount = notTaxAmount.add(dto.getNotTaxAmount() == null?BigDecimal.ZERO:dto.getNotTaxAmount());
            taxAmount = taxAmount.add(dto.getTaxAmount() == null?BigDecimal.ZERO:dto.getTaxAmount());
        }
        AccountStatement accountStatement = accountStatementService.getById(asId);
        accountStatement.setNotTaxAmount(notTaxAmount);
        accountStatement.setTaxAmount(taxAmount);
        accountStatementService.updateById(accountStatement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @DS(SLAVE)
    public void priceImport(MultipartFile file) {
        try {
            List<Map<String,String>> dataList = EasyExcelImportUtils.parseExcelToData(file.getInputStream(), 2);
            if (CollectionUtils.isNotEmpty(dataList)){
                List<AccountStatementDetail> accountStatementDetails = new ArrayList<>();
                for (Map<String,String> map : dataList){
                    if (StringUtils.isNotEmpty(map.get("receiveId"))&&StringUtils.isNotEmpty(map.get("factoryCode"))&&StringUtils.isNotEmpty(map.get("deductionRatio"))){
                        ReceiveVoucher receiveVoucher = receiveVoucherService.getOne(Wrappers.lambdaQuery(ReceiveVoucher.class)
                                .eq(ReceiveVoucher::getId,map.get("receiveId"))
                                .eq(ReceiveVoucher::getFactoryCode,map.get("factoryCode")).last(" limit 1"));
                        if (ObjectUtil.isNotNull(receiveVoucher)){
                            receiveVoucher.setDeductionRatio((new BigDecimal(map.get("deductionRatio"))));
                            //不含税金额 不含税金额-其他折扣
                            receiveVoucher.setNotTaxAmount(receiveVoucher.getNotTaxAmount().subtract(receiveVoucher.getDeductionRatio()));
                            //不含税单价 不含税金额/数量
                            receiveVoucher.setNotTaxPrice(receiveVoucher.getNotTaxAmount().divide(receiveVoucher.getMvNum(), priceHandle.getPrecision(), priceHandle.getCutType()==0?RoundingMode.HALF_UP:RoundingMode.HALF_DOWN));

                            BigDecimal taxAdd = receiveVoucher.getTaxValue().add(new BigDecimal(1));
                            //含税单价 未税单价*（1+税率）
                            receiveVoucher.setTaxPrice(receiveVoucher.getNotTaxPrice().multiply(taxAdd));
                            //含税金额 含税单价*数量
                            receiveVoucher.setTaxAmount(receiveVoucher.getMvNum().multiply(receiveVoucher.getTaxPrice()));
                            //税额 含税金额-未税金额
                            receiveVoucher.setDiffTaxAmount(receiveVoucher.getTaxAmount().subtract(receiveVoucher.getNotTaxAmount()));
                            receiveVoucherService.update(receiveVoucher,Wrappers.lambdaQuery(ReceiveVoucher.class)
                                    .eq(ReceiveVoucher::getId,receiveVoucher.getId())
                                    .eq(ReceiveVoucher::getFactoryCode,map.get("factoryCode"))
                            );
                        }
                        if (StringUtils.isNotEmpty(map.get("id"))){
                            AccountStatementDetail accountStatementDetail = accountStatementDetailService.getById(map.get("id"));
                            if (ObjectUtil.isNotNull(accountStatementDetail)){
                                //不含税金额 不含税金额-其他折扣
                                accountStatementDetail.setNotTaxAmount(accountStatementDetail.getNotTaxAmount().subtract(new BigDecimal(map.get("deductionRatio"))));
                                //不含税单价 不含税金额/数量
                                accountStatementDetail.setNotTaxPrice(accountStatementDetail.getNotTaxAmount().divide(accountStatementDetail.getReceiveNum(), priceHandle.getPrecision(), priceHandle.getCutType()==0?RoundingMode.HALF_UP:RoundingMode.HALF_DOWN));
                                BigDecimal taxAdd = accountStatementDetail.getTaxValue().add(new BigDecimal(1));
                                //含税单价 未税单价*（1+税率）
                                accountStatementDetail.setTaxPrice(accountStatementDetail.getNotTaxPrice().multiply(taxAdd));
                                //含税金额 含税单价*数量
                                accountStatementDetail.setTaxAmount(accountStatementDetail.getReceiveNum().multiply(accountStatementDetail.getTaxPrice()));
                                //税额 含税金额-未税金额
                                accountStatementDetail.setDiffTaxAmount(accountStatementDetail.getTaxAmount().subtract(accountStatementDetail.getNotTaxAmount()));
                                accountStatementDetails.add(accountStatementDetail);
                            }
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(accountStatementDetails)){
                    this.updateAccountStatementAmount(accountStatementDetails.get(0).getAsId());
                }
            }
        } catch (IOException e) {
            throw new DaoException("读取Excel失败");
        }
    }

    /**
     * 实时获取对账凭证数据
     *
     * @param list 对账单明细数据
     * @param asId 对账单ID
     */
    private void realTimeReceiveData(
            List<StatementItemDTO> list, Long asId, String companyCode, String supplierCode, String postTimeStart,
            String postTimeEnd, Integer receiveType
    ){
        ReceiveVoucherQuery query = new ReceiveVoucherQuery();
        query.setCompanyCode(companyCode);
        query.setSupplierCode(supplierCode);
        query.setPostTimeStart(postTimeStart);
        query.setPostTimeEnd(postTimeEnd);
        query.setReceiveType(receiveType);

        // 实时调取SAP接口获取凭证最新过账金额及数量
//        statementDetailService.realTimeReceiveVoucher(query, list);

        // 获取SRM系统中凭证剩余可用数量
        receiptVoucherLogic.statisticVoucherData(asId, list, 0);

        BigDecimal negOne = new BigDecimal("-1");
        for(StatementItemDTO item: list){
            if("H".equals(item.getVoucherFlag())){
                item.setSurplusAmount(item.getSurplusAmount().multiply(negOne));
                item.setInvoicedAmount(item.getInvoicedAmount().multiply(negOne));
            }
        }
    }

    @Override
    public List<InvoicedApplyItemPO> provideCreateInvoicedApplyPage(Page<AccountStatementDetail> dbPage, CreateInvoicedApplyPageQuery query) {
        List<InvoicedApplyItemPO> inquiryPOS = accountStatementDetailService.provideCreateInvoicedApplyPage(null, query);
        return inquiryPOS;
    }
}
