package com.jwipc.finance.logic.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
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.CostInvoicedApplyConvert;
import com.jwipc.finance.convert.InvoicedApplyConvert;
import com.jwipc.finance.dto.*;
import com.jwipc.finance.entity.*;
import com.jwipc.finance.logic.*;
import com.jwipc.finance.model.po.CostInvoicedApplyPO;
import com.jwipc.finance.model.po.InvoicedApplyItemPO;
import com.jwipc.finance.model.po.InvoicedApplyPO;
import com.jwipc.finance.model.po.InvoicedApplyPrintPO;
import com.jwipc.finance.model.query.CostInvoicedApplyQuery;
import com.jwipc.finance.model.query.InvoicedApplyAttachmentQuery;
import com.jwipc.finance.model.query.InvoicedApplyQuery;
import com.jwipc.finance.service.*;
import com.jwipc.page.PageUtil;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.security.dto.CurrentUserDTO;
import com.jwipc.supplier.clent.dto.SupplierContactsDTO;
import com.jwipc.sys.client.DictClient;
import com.jwipc.sys.client.ESignClient;
import com.jwipc.sys.client.FileClient;
import com.jwipc.sys.client.SequenceClient;
import com.jwipc.sys.client.dto.DictDTO;
import com.jwipc.sys.client.dto.FileResposeCDTO;
import com.jwipc.sys.dto.BusinessAttachmentDTO;
import com.jwipc.sys.dto.DigitalSealBusinessDetailDTO;
import com.jwipc.sys.dto.KingdeeInvoiceCloudImageDTO;
import com.jwipc.sys.entity.Attachment;
import com.jwipc.sys.entity.BusinessAttachment;
import com.jwipc.sys.entity.DigitalSealBusinessDetail;
import com.jwipc.sys.logic.BusinessAttachmentLogic;
import com.jwipc.sys.logic.ESignLogic;
import com.jwipc.sys.logic.KingdeeImageLogic;
import com.jwipc.sys.logic.KingdeeInvoiceCloudLogic;
import com.jwipc.sys.service.IAttachmentService;
import com.jwipc.sys.service.IBusinessAttachmentService;
import com.jwipc.sys.service.IDigitalSealBusinessDetailService;
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.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shenyang.ou
 * @date 2025/11/5 11:50
 * @desc
 */
@Service
@RequiredArgsConstructor
public class CostInvoicedApplyLogicImpl implements CostInvoicedApplyLogic {
    private final ICostInvoicedApplyService costInvoicedApplyService;
    private final IAttachmentManualCheckService attachmentManualCheckService;
    private final ICostInvoicedApplyApproveService costInvoicedApplyApproveService;
    private final ICostInvoicedApplyAttachmentService costInvoicedApplyAttachmentService;
    private final KingdeeImageLogic kingdeeImageLogic;
    private final DictClient dictClient;
    private final IDigitalSealBusinessDetailService digitalSealBusinessDetailService;
    private final IAttachmentService attachmentService;
    private final BusinessAttachmentLogic businessAttachmentLogic;
    private final ESignLogic eSignLogic;
    private final IBusinessAttachmentService businessAttachmentService;
    private final FileClient fileClient;
    private final ICostInvoicedApplyDetailService costInvoicedApplyDetailService;
    private final ICostInvoicedReceiptService costInvoicedReceiptService;
    private final KingdeeInvoiceCloudLogic kingdeeInvoiceCloudLogic;
    private final ICostInvoicedPaymentCertificateService costInvoicedPaymentCertificateService;
    private final CostInvoicedApplyConvert costInvoicedApplyConvert;
    private final SequenceClient sequenceClient;
    private final CostAccountStatementLogic costAccountStatementLogic;
    private final CostInvoicedReceiptLogic costInvoicedReceiptLogic;
    private final CostInvoicedPaymentCertificateLogic costInvoicedPaymentCertificateLogic;
    private final CostInvoicedApplyApproveLogic costInvoicedApplyApproveLogic;
    private final ICostInvoicedApplyPostResultService costInvoicedApplyPostResultService;
    private final ESignClient eSignClient;
    @Override
    public CostInvoicedApply findInvoicedApplyByStatementNo(String accountStatementNo) {
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getOne(Wrappers.lambdaQuery(CostInvoicedApply.class).eq(CostInvoicedApply::getAccountStatementNo,accountStatementNo)
                .eq(CostInvoicedApply::getStatus, 9)
                .eq(CostInvoicedApply::getDeleteFlag, "0")
                .last(" limit 1"));
        return invoicedApply;
    }

    @Override
    public CostInvoicedApplyDTO getById(Long id) {
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getById(id);
        return costInvoicedApplyConvert.entity2DTO(invoicedApply);
    }

    @Override
    public String findInvoiceVoucher(Long id) {
        return costInvoicedApplyService.findInvoiceVoucher(id);
    }

    @Override
    public CostInvoicedApplyPrintDTO selectPrintDataById(Long id) {
        InvoicedApplyPrintPO dto = costInvoicedApplyService.selectPrintDataById(id);
        dto.setDeductionCodeTypeName(dto.getDeductionCodeType()!=null&&dto.getDeductionCodeType()==1?"可抵扣":"不可抵扣");
        return costInvoicedApplyConvert.invoicedApplyPrintPO2DTO(dto);
    }

    @Override
    public PageView selectDataByQuery(CostInvoicedApplyQuery query) {
        //已经删除的不查询 2024-08-26 邓京术
        query.setDelFlg(0);
        final Page<CostInvoicedApply> dbPage = PageUtil.toPage(query);
        List<CostInvoicedApplyPO> invoicedApplyPOS = costInvoicedApplyService.selectDataByQuery(dbPage, query);
        List<CostInvoicedApplyDTO> invoicedApplyDTOS = costInvoicedApplyConvert.po2PageListDTO(invoicedApplyPOS);
        return PageUtil.getPV(invoicedApplyDTOS, dbPage.getTotal());
    }

    /**
     * 开票申请单删除
     *
     * @param ids         开票申请ID
     * @param logicDelete 是否逻辑删除
     */
    @Override
    @Transactional
    public void dataDel(String ids, Boolean logicDelete) {
        if (StringUtils.isEmpty(ids)) {
            throw new DaoException("参数异常, 请重新操作");
        }
        final List<Long> idList = JSONArray.parseArray(ids, Long.class);
        List<CostInvoicedApply> applyList = Lists.newArrayList();

        CostInvoicedApplyQuery query = new CostInvoicedApplyQuery();
        query.setIaIdList(idList);
        final List<CostInvoicedApplyPO> list = costInvoicedApplyService.selectDataByQuery(null,query);

        boolean exceptionFlag = false;
        for (CostInvoicedApplyPO ia : list) {
            CostInvoicedApply updateIa = new CostInvoicedApply();
            updateIa.setId(ia.getId());
            updateIa.setDeleteFlag(1);
            updateIa.setUpdateUserId(StpUtil.isLogin()? LoginUtil.getUserId():1L);
            updateIa.setUpdateUserCode(StpUtil.isLogin()?LoginUtil.getAccount():"admin");
            updateIa.setUpdateUserName(StpUtil.isLogin()?LoginUtil.getName():"admin");
            updateIa.setUpdateTime(LocalDateTime.now());

            // 1:暂存 2:待采购确认 3:采购拒绝 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认 8:财务拒绝 9:确认完成
            if ("1,3,8".contains(ia.getStatus().toString()) ||
                    (9 == ia.getStatus() && ("3,4,5".contains(ia.getPostStatus().toString())))) {
                applyList.add(updateIa);
            } else {
                exceptionFlag = true;
            }

            costAccountStatementLogic.updateInvoiceCompleteFlagByAsId(ia.getAccountStatementId(), 0);
        }

        if (exceptionFlag) {
            throw new DaoException("选中的开票申请存在数据状态不支持删除操作, 请检查");
        }

        if (CollectionUtils.isNotEmpty(applyList)) {
            if (!costInvoicedApplyService.updateBatchById(applyList)) {
                throw new DaoException("删除选中的开票申请失败, 请检查");
            }
        }

        List<CostInvoicedApplyDetail> updateIadList = Lists.newArrayList();
        final List<CostInvoicedApplyDetail> iadList = costInvoicedApplyDetailService.findByInvoiceApplyId(null, idList);
        for (CostInvoicedApplyDetail iad : iadList) {
            CostInvoicedApplyDetail updateIad = new CostInvoicedApplyDetail();
            updateIad.setId(iad.getId());
            updateIad.setDeleteFlag(1);
            updateIad.setUpdateUserId(LoginUtil.getUserId());
            updateIad.setUpdateUserCode(LoginUtil.getAccount());
            updateIad.setUpdateUserName(LoginUtil.getName());
            updateIad.setUpdateTime(LocalDateTime.now());
            updateIadList.add(updateIad);
        }

        if (CollectionUtils.isNotEmpty(updateIadList)) {
            if (!costInvoicedApplyDetailService.updateBatchById(updateIadList)) {
                throw new DaoException("删除选中的开票申请单对应的明细数据失败, 请检查");
            }
        }


//        // 开票未完成
//        List<Long> asdIdList = Lists.newArrayList();
//        //删除明细id
//        List<Long> detailIds = Lists.newArrayList();
//        for (InvoicedApplyDetail delIad : iadList) {
//            asdIdList.add(delIad.getAsdId());
//            detailIds.add(delIad.getId());
//        }
//        accountStatementLogic.updateInvoiceCompleteFlag(asdIdList, 0);

        for (Long asId : idList){
//            //释放扣款信息
//            List<AccountStatementDeduction> accountStatementDeductions = accountStatementDeductionService.selectList(new EntityWrapper<AccountStatementDeduction>().eq("as_id", asId));
//            if (CollectionUtils.isNotEmpty(accountStatementDeductions)){
//                accountStatementDeductions.forEach(accountStatementDeduction -> {
//                    accountStatementDeduction.setDeleteFlag(1);
//                    if (accountStatementDeduction.getUseFlag()==1){
//                        DeductionManage deductionManage = new DeductionManage();
//                        deductionManage.setId(accountStatementDeduction.getDeductionId());
//                        deductionManage.setStatementOrderCode("");
//                        deductionManage.setWhether(0);
//                        deductionManageService.updateById(deductionManage);
//                    }
//                });
//                accountStatementDeductionService.updateBatchById(accountStatementDeductions);
//            }
            //释放发票信息
            List<CostInvoicedReceipt> invoicedReceipts = costInvoicedReceiptService.list(Wrappers.lambdaQuery(CostInvoicedReceipt.class).eq(CostInvoicedReceipt::getIaId,asId));
            if (CollectionUtils.isNotEmpty(invoicedReceipts)){
                if (logicDelete){
                    invoicedReceipts.forEach(invoicedReceipt -> {
                        invoicedReceipt.setDeleteFlag(1);
                        invoicedReceipt.setUpdateTime(LocalDateTime.now());
                        costInvoicedReceiptService.updateById(invoicedReceipt);
                    });
                }else {
                    invoicedReceipts.forEach(costInvoicedReceiptService::removeById);
                }

                //删除发票确认
                List<String> serialNoList = invoicedReceipts.stream()
                        .map(CostInvoicedReceipt::getSerialNo)
                        .filter(StrUtil::isNotEmpty)
                        .toList();
                if (CollUtil.isNotEmpty(serialNoList)) {
                    kingdeeInvoiceCloudLogic.deleteInvoice(String.join(",", serialNoList));
                }
            }

            //释放海关缴款书
            List<CostInvoicedPaymentCertificate> invoicedPaymentCertificates = costInvoicedPaymentCertificateService.list(Wrappers.lambdaQuery(CostInvoicedPaymentCertificate.class).eq(CostInvoicedPaymentCertificate::getIaId,asId));
            if (CollectionUtils.isNotEmpty(invoicedPaymentCertificates)){
                if (logicDelete){
                    invoicedPaymentCertificates.forEach(invoicedReceipt -> {
                        invoicedReceipt.setDeleteFlag(1);
                        invoicedReceipt.setUpdateTime(LocalDateTime.now());
                        costInvoicedPaymentCertificateService.updateById(invoicedReceipt);
                    });
                }else {
                    invoicedPaymentCertificates.forEach(costInvoicedPaymentCertificateService::removeById);
                }
            }

            //释放预付款信息
//            List<InvoicedApplyPa> invoicedApplyPaList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,asId));
//            if (CollectionUtils.isNotEmpty(invoicedApplyPaList)){
//                if (logicDelete){
//                    invoicedApplyPaList.forEach(invoicedApplyPa -> {
//                        invoicedApplyPa.setDeleteFlag(1);
//                        invoicedApplyPaService.updateById(invoicedApplyPa);
//                    });
//                }else {
//                    invoicedApplyPaList.forEach(invoicedApplyPaService::removeById);
//                }
//
//                invoicedApplyPaList.forEach(invoicedApplyPa -> {
//                    //更新预付款已冲账金额
//                    PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = paymentAdvanceApplyDetailService.getById(invoicedApplyPa.getPaId());
//                    if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                        paymentAdvanceApplyDetail.setReversalMoney(paymentAdvanceApplyDetail.getReversalMoney().subtract(invoicedApplyPa.getStrikePrice()).compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:paymentAdvanceApplyDetail.getReversalMoney().subtract(invoicedApplyPa.getStrikePrice()));
//                        paymentAdvanceApplyDetailService.updateById(paymentAdvanceApplyDetail);
//                    }
////                    invoicedApplyPaService.removeById(invoicedApplyPa.getId());
//                });
//
//            }
        }
    }

    @Override
    public void submitConfirm(String ids) {
        if (StringUtils.isEmpty(ids)) {
            throw new DaoException("参数异常, 请重新操作");
        }
        final List<Long> idList = JSONArray.parseArray(ids, Long.class);
        CostInvoicedApplyQuery query = new CostInvoicedApplyQuery();
        query.setIaIdList(idList);
        final List<CostInvoicedApplyPO> oldIaList = costInvoicedApplyService.selectDataByQuery(null, query);
        for (CostInvoicedApplyPO ia : oldIaList) {
            if (1 != ia.getStatus() && 3 != ia.getStatus() && 8 != ia.getStatus()) {
                throw new DaoException("开票申请单号: " + ia.getInvoiceApplyNo() + ", 当前数据状态不支持提交确认, 请检查");

            }
        }
        List<CostInvoicedApply> iaList = Lists.newArrayList();
        for (Long id : idList) {
            CostInvoicedApply ia = new CostInvoicedApply();
            ia.setStatus(2);
            ia.setId(id);
            ia.setUpdateTime(LocalDateTime.now());
            ia.setUpdateUserId(LoginUtil.getUserId());
            ia.setUpdateUserCode(LoginUtil.getAccount());
            ia.setUpdateUserName(LoginUtil.getName());
            iaList.add(ia);

            // 增加控制：必须存在关联发票数据，没有则禁止通过
//            List<InvoiceLeShuiDto> invoice = invoicedLesHuiService.getInvoiceDetail(id);
//            if(bindInvoice && CollectionUtils.isEmpty(invoice)){
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(this.returnMessage("当前开票申请没有关联发票数据，无法提交！"));
//            }
        }

        if (CollectionUtils.isNotEmpty(iaList)) {
            if (!costInvoicedApplyService.updateBatchById(iaList)) {
                throw new DaoException("提交确认失败, 请联系管理员");
            }
        }
    }

    @Override
    public void dataExport(HttpServletRequest request, HttpServletResponse response, Long id) {

    }

    @Override
    public List<CostInvoicedApplyDTO> listAll(CostInvoicedApplyQuery query) {
        //已经删除的不查询 2024-08-26 邓京术
        query.setDelFlg(0);
        List<CostInvoicedApplyPO> invoicedApplyPOS = costInvoicedApplyService.selectDataByQuery(null, query);
        return costInvoicedApplyConvert.po2PageListDTO(invoicedApplyPOS);
    }

    @Override
    public void writeOff(Long id, String writeOff) {
        costInvoicedApplyService.update(new LambdaUpdateWrapper<CostInvoicedApply>()
                .set(CostInvoicedApply::getWriteOff, writeOff)
                .eq(CostInvoicedApply::getId,id)
        );
    }

    @Override
    @Transactional
    public void updateHead(CostInvoicedApplySaveParamDTO params) {
        if (ObjectUtil.isNull(params.getHeadData())) {
            throw new DaoException("开票申请表头数据异常, 请重新操作");
        }
        // 变更的开票申请表头数据
        CostInvoicedApplyDTO head = params.getHeadData();
        final CostInvoicedApply oldHead = costInvoicedApplyService.getById(head.getId());
        if (1 != oldHead.getStatus() && 3 != oldHead.getStatus()&& 8 != oldHead.getStatus()) {
            throw new DaoException("当前开票申请单的数据状态不允许修改, 请检查");
        }
        // 暂存时状态改为暂存
        head.setStatus(1);

        if (!costInvoicedApplyService.updateById(costInvoicedApplyConvert.dto2Entity(head))) {
            throw new DaoException("数据保存失败, 请联系管理员");
        }
        // 附件关系
//        businessAttachmentService.remove(Wrappers.lambdaQuery(BusinessAttachment.class).eq(BusinessAttachment::getBusinessId, head.getId()));
//        List<BusinessAttachmentDTO> businessAttachmentDTOList = params.getBusinessAttachmentDTOList();
//        businessAttachmentDTOList.forEach(item -> {
//            item.setId(null);
//            item.setBusinessId(head.getId());
//            item.setBusinessTypeCode("cost_invoice_apply");
//        });
        // 对接乐税系统，关联或取消关联发票
        costInvoicedReceiptLogic.operateInvoice(params.getInvoicedReceiptData(),head.getId(),LoginUtil.getCurrentUser());
        costInvoicedPaymentCertificateLogic.operateInvoice(params.getInvoicedPaymentCertificateData(),head.getId(),LoginUtil.getCurrentUser());
        this.deleteImg(head.getId());
        this.toImg(head.getId());
    }

    @Override
    @Transactional
    public void dataSave(CostInvoicedApplySaveParamDTO params) {
        if (ObjectUtil.isNull(params.getHeadData())) {
            throw new DaoException("开票申请表头数据异常, 请重新操作");
        }
//        if (CollectionUtils.isEmpty(params.getDetailDate())) {
//            throw new DaoException("新增的明细数据异常, 请重新操作");
//        }

        CostInvoicedApplyDTO headDto = params.getHeadData();
        CostInvoicedApply head = costInvoicedApplyConvert.dto2Entity(headDto);
        if (head.getId()==null){
            CostInvoicedApply oldHead = costInvoicedApplyService.getOne(new LambdaQueryWrapper<>(CostInvoicedApply.class)
                    .eq(CostInvoicedApply::getAccountStatementNo,head.getAccountStatementNo())
                    .eq(CostInvoicedApply::getDeleteFlag,0).last(" limit 1"));
            if (ObjectUtil.isNotNull(oldHead)){
                throw new DaoException("该对账单已经创建开票，不可重复创建");
            }
            head.setInvoiceApplyNo(sequenceClient.createSequenceNo("cost_invoiced_apply_code"));
            head.setId(null);
            head.setCreateTime(LocalDateTime.now());
            head.setCreateUserId(LoginUtil.getUserId());
            head.setCreateUserCode(LoginUtil.getAccount());
            head.setCreateUserName(LoginUtil.getName());
            if (!costInvoicedApplyService.save(head)) {
                throw new DaoException("保存开票申请表头数据失败, 前联系管理员");
            }
//            if (CollectionUtils.isNotEmpty(params.getBusinessAttachmentDTOList())) {
//                List<BusinessAttachmentDTO> insertList = Lists.newArrayList();
//                // 新建时，如果有上传附件的场景
//                for (BusinessAttachmentDTO businessAttachment : params.getBusinessAttachmentDTOList()) {
//                    if (!Objects.isNull(businessAttachment.getId())) {
//                        businessAttachment.setId(null);
//                    }
//                    // 初始化值
//                    businessAttachment.setRemark(null);
//                    businessAttachment.setDeleteFlag(Integer.valueOf(0));
//                    businessAttachment.setImageCode(null);
//                    businessAttachment.setImagePath(null);
//                    // id 统一使用开票申请单的id
//                    businessAttachment.setBusinessId(head.getId());
//                    businessAttachment.setBusinessTypeCode("invoice_apply");
//                    if (Objects.isNull(businessAttachment.getBusinessCode())) {
//                        // 新上传直接用开票申请单的编号
//                        businessAttachment.setBusinessCode(head.getInvoiceApplyNo());
//                    } else {
//                        // 从对账单过来的继续沿用
//                        businessAttachment.setBusinessCode(businessAttachment.getBusinessCode());
//                    }
//                    insertList.add(businessAttachment);
//                }
//                businessAttachmentLogic.saveAttachment(insertList);
//            }
        }else {
            head.setUpdateTime(LocalDateTime.now());
            head.setUpdateUserId(LoginUtil.getUserId());
            head.setUpdateUserCode(LoginUtil.getAccount());
            head.setUpdateUserName(LoginUtil.getName());
            if (!costInvoicedApplyService.updateById(head)) {
                throw new DaoException("保存开票申请表头数据失败, 前联系管理员");
            }
            CostInvoicedApply old = costInvoicedApplyService.getById(head.getId());
            //取消完成标识
//            accountStatementLogic.updateInvoiceCompleteFlagByAsId(old.getAccountStatementId(),0);
            costInvoicedApplyDetailService.remove(Wrappers.lambdaQuery(CostInvoicedApplyDetail.class).eq(CostInvoicedApplyDetail::getIaId,head.getId()));
        }
        // 附件关系
//        businessAttachmentService.remove(Wrappers.lambdaQuery(BusinessAttachment.class).eq(BusinessAttachment::getBusinessId, head.getId()));
//        List<BusinessAttachmentDTO> businessAttachmentDTOList = params.getBusinessAttachmentDTOList();
//        businessAttachmentDTOList.forEach(item -> {
//            item.setId(null);
//            item.setBusinessId(head.getId());
//            item.setBusinessTypeCode("cost_invoice_apply");
//        });
//        businessAttachmentLogic.saveAttachment(businessAttachmentDTOList);
//        List<InvoicedApplyAttachmentDTO> businessAttachmentDTOList = params.getBusinessAttachmentDTOList();
//        if (CollUtil.isNotEmpty(businessAttachmentDTOList)){
//            List<InvoicedApplyAttachment> insetInvoicedApplyAttachmentList = Lists.newArrayList();
//            // businessAttachmentDTOList中过滤出id为空的数据list
//            businessAttachmentDTOList = businessAttachmentDTOList.stream().filter(item -> item.getId() == null).toList();
//            for (InvoicedApplyAttachmentDTO invoicedApplyAttachmentDTO : businessAttachmentDTOList) {
//                InvoicedApplyAttachment invoicedApplyAttachment = invoicedApplyAttachmentConvert.dto2Entity(invoicedApplyAttachmentDTO);
//                invoicedApplyAttachment.setIaId(head.getId());
//                invoicedApplyAttachment.setCreateTime(LocalDateTime.now());
//                invoicedApplyAttachment.setCreateUser(LoginUtil.getUserId());
//                invoicedApplyAttachment.setFileType(0);
//                insetInvoicedApplyAttachmentList.add(invoicedApplyAttachment);
//            }
//            if (CollUtil.isNotEmpty(insetInvoicedApplyAttachmentList)){
//                invoicedApplyAttachmentService.saveBatch(insetInvoicedApplyAttachmentList);
//            }
//        }else {
//            //取出siList中的poCode
//            List<String> poCodeList = inquiryPOS.stream().map(InvoicedApplyItemPO::getPoCode).distinct().toList();
//            InvoicedApplyAttachmentQuery query = new InvoicedApplyAttachmentQuery();
//            query.setIaId(head.getId());
//            query.setReloadFlag(1);
//            //poCodeList逗号隔开
//            query.setBusinessCodes(String.join(",", poCodeList));
//            query.setBusinessTypeCodes("purchase_order");
//
//            PageView pageView = invoicedApplyAttachmentLogic.list(query);
//            if (CollUtil.isNotEmpty(pageView.getRows())){
//                List<InvoicedApplyAttachment> saveList = new ArrayList<>();
//                List<InvoicedApplyAttachmentDTO> attachmentDTOList = (List<InvoicedApplyAttachmentDTO>) pageView.getRows();
//                attachmentDTOList.forEach(item -> {
//                    InvoicedApplyAttachment accountStatementAttachment =  new InvoicedApplyAttachment();
//                    accountStatementAttachment.setBusinessAttachmentId(item.getId());
//                    accountStatementAttachment.setIaId(head.getId());
//                    accountStatementAttachment.setFileId(item.getFileId());
//                    accountStatementAttachment.setCreateTime(LocalDateTime.now());
//                    accountStatementAttachment.setCreateUser(LoginUtil.getUserId());
//                    accountStatementAttachment.setFileType(0);
//                    saveList.add(accountStatementAttachment);
//                });
//                invoicedApplyAttachmentService.saveBatch(saveList);
//            }
//        }

        //保存签署附件
//        List<InvoicedApplyAttachmentDTO> signAttachmentDTOList = params.getSignAttachmentDTOList();
//        if (CollUtil.isNotEmpty(signAttachmentDTOList)){
//            List<InvoicedApplyAttachment> invoicedApplyAttachments = invoicedApplyAttachmentService.list(new LambdaQueryWrapper<InvoicedApplyAttachment>()
//                    .eq(InvoicedApplyAttachment::getIaId,head.getId()).eq(InvoicedApplyAttachment::getFileType,1).eq(InvoicedApplyAttachment::getDeleteFlag,0));
//            if (CollUtil.isNotEmpty(invoicedApplyAttachments)){
//                signAttachmentDTOList.forEach(signAttachmentDTO -> {
//                    invoicedApplyAttachments.forEach(invoicedApplyAttachmentDTO -> {
//                        if (invoicedApplyAttachmentDTO.getFileId().equals(signAttachmentDTO.getFileId())){
//                            signAttachmentDTO.setId(invoicedApplyAttachmentDTO.getId());
//                        }
//                    });
//                });
//            }
//            signAttachmentDTOList = signAttachmentDTOList.stream().filter(item -> item.getId() == null).toList();
//            List<InvoicedApplyAttachment> insetInvoicedApplyAttachmentList = Lists.newArrayList();
//            for (InvoicedApplyAttachmentDTO invoicedApplyAttachmentDTO : signAttachmentDTOList) {
//                InvoicedApplyAttachment invoicedApplyAttachment = invoicedApplyAttachmentConvert.dto2Entity(invoicedApplyAttachmentDTO);
//                invoicedApplyAttachment.setIaId(head.getId());
//                invoicedApplyAttachment.setCreateTime(LocalDateTime.now());
//                invoicedApplyAttachment.setCreateUser(LoginUtil.getUserId());
//                invoicedApplyAttachment.setFileType(1);
//                insetInvoicedApplyAttachmentList.add(invoicedApplyAttachment);
//            }
//            if (CollUtil.isNotEmpty(insetInvoicedApplyAttachmentList)){
//                invoicedApplyAttachmentService.saveBatch(insetInvoicedApplyAttachmentList);
//            }
//        }

//        List<InvoicedApplyItemDTO> detailList = params.getDetailDate();

//        CreateInvoicedApplyPageQuery query = new CreateInvoicedApplyPageQuery();
//        query.setFactoryCode(head.getFactoryCode());
//        query.setAsId(head.getAccountStatementId());
        //分库分表查询不生效，需要把这个方法提到外面先行查询，邓京术 2025-06-29
//        List<InvoicedApplyItemPO> inquiryPOS = accountStatementDetailService.provideCreateInvoicedApplyPage(null, query);
//        List<InvoicedApplyItemDTO> detailList = accountStatementDetailConvert.invoicedApplyItemPO2DTOList(inquiryPOS);
//        for (InvoicedApplyItemDTO invoicedApplyItemDTO : detailList){
//            invoicedApplyItemDTO.setTaxCode(invoicedApplyItemDTO.getAsTaxCode());
//            invoicedApplyItemDTO.setTaxValue(invoicedApplyItemDTO.getAsTaxValue());
//            invoicedApplyItemDTO.setNotTaxPrice(invoicedApplyItemDTO.getAsNotTaxPrice());
//            invoicedApplyItemDTO.setTaxPrice(invoicedApplyItemDTO.getAsTaxPrice());
//            invoicedApplyItemDTO.setNotTaxAmount(invoicedApplyItemDTO.getAsNotTaxAmount());
//            invoicedApplyItemDTO.setTaxAmount(invoicedApplyItemDTO.getAsTaxAmount());
//            invoicedApplyItemDTO.setDiffTaxAmount(invoicedApplyItemDTO.getAsDiffTaxAmount());
//        }
//        List<InvoicedApplyDetail> iadList = Lists.newArrayList();
//        int i = 1;
//        for (InvoicedApplyItemDTO dto : detailList) {
//            InvoicedApplyDetail iad = dto.toIad();
//            //判断对账明细中是否存在已经使用过的物料凭证
////            InvoicedApplyDetail detail = invoicedApplyDetailService.getOne(Wrappers.lambdaQuery(InvoicedApplyDetail.class).eq(InvoicedApplyDetail::getAsdId,iad.getAsdId()).eq(InvoicedApplyDetail::getDeleteFlag,0).last(" limit 1"));
////            if (ObjectUtil.isNotNull(detail)){
////                throw new DaoException("对账单号："+detail.getAsNo()+",已创建过开票申请单，无法继续创建");
////            }
//            iad.setIaId(head.getId());
//            iad.setIaNo(head.getInvoiceApplyNo());
//            iad.setId(null);
//            iad.setCreateTime(LocalDateTime.now());
//            iad.setCreateUserId(LoginUtil.getUserId());
//            iad.setCreateUserCode(LoginUtil.getAccount());
//            iad.setCreateUserName(LoginUtil.getName());
//            iad.setItemNo(StringUtils.leftPad(String.valueOf(i*10), 6, "0"));
//            iadList.add(iad);
//            i++;
//        }
//
//        // 校验开票明细中反向凭证对应的正向是否也在其中
//        final String checkResult = this.checkInvoicedApplyDetail(head.getSupplierCode(), iadList, head.getOrderType());
//        if (StringUtils.isNotEmpty(checkResult)) {
//            throw new DaoException(checkResult);
//        }

        // 保存开票申请明细数据
//        if (CollectionUtils.isNotEmpty(iadList)) {
//            if (!this.invoicedApplyDetailService.saveBatch(iadList)) {
//                throw new DaoException("保存开票申请明细数据失败, 前联系管理员");
//            }
//        }

        // 保存开票申请单的返利和扣款信息
//        this.addSdAndSr(head, sdIdList, srIdList);
//        this.addPa(head, params.getAddPaIds());

        // 更新对账单及明细的开票完成标识
//        List<Long> asdIdList = Lists.newArrayList();
//        for (InvoicedApplyDetail detail : iadList) {
//            asdIdList.add(detail.getAsdId());
//        }
//        accountStatementLogic.updateInvoiceCompleteFlag(asdIdList, 1);
        costAccountStatementLogic.updateInvoiceCompleteFlagByAsId(head.getAccountStatementId(),1);

//        invoicedApplyOptLogic.addContentRecord(1, null, head, Lists.newArrayList(), Lists.newArrayList(), LoginUtil.getCurrentUser());

        // 对接乐税系统，关联或取消关联发票
        costInvoicedReceiptLogic.operateInvoice(params.getInvoicedReceiptData(),head.getId(),LoginUtil.getCurrentUser());
        costInvoicedPaymentCertificateLogic.operateInvoice(params.getInvoicedPaymentCertificateData(),head.getId(),LoginUtil.getCurrentUser());
        this.deleteImg(head.getId());
        this.toImg(head.getId());
    }

    @Override
    public Boolean statementInvoicingCheck(String statementNo) {
        List<CostInvoicedApply> list = costInvoicedApplyService.list(Wrappers.lambdaQuery(CostInvoicedApply.class).eq(CostInvoicedApply::getAccountStatementNo, statementNo).ne(CostInvoicedApply::getDeleteFlag, 1));
        if(CollectionUtils.isNotEmpty(list)){
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void purchaseConfirm(CostInvoicedApplySaveParamDTO params) {
        if (ObjectUtil.isNull(params.getHeadData())) {
            throw new DaoException("参数异常, 请重新操作");
        }

//        if (CollectionUtils.isEmpty(params.getDetailDate())) {
//            throw new DaoException("明细数据异常, 请重新操作");
//        }
        CostInvoicedApplyDTO headDto = params.getHeadData();
        CostInvoicedApply head = costInvoicedApplyConvert.dto2Entity(headDto);
        // 变更的开票明细数据
//        List<InvoicedApplyItemDTO> detailList = params.getDetailDate();
        //roleType 1 采购确认 2 财务确认   ApproveStatus 1 同意 0 拒绝
        if(1 == params.getRoleType() && 1 == params.getApproveStatus()){
//            if(head.getInvoiceTotalAmount().compareTo(head.getInvoiceNetAmount())!=0){
//                throw new RuntimeException("金额不符，请重新关联发票，修改开票金额!");
//            }
//            if(head.getInvoiceTaxTotalAmount().compareTo(head.getInvoiceTaxAmount())!=0){
//                throw new RuntimeException("金额不符，请重新关联发票，修改开票金额!");
//            }

            //判断发票上传的供应商是否一致
//            List<InvoiceLeShuiDto> invoiceDetail = invoicedLesHuiService.getInvoiceDetail(head.getId());
//            Optional<InvoiceLeShuiDto> cartOptional = invoiceDetail.stream().filter(item -> !item.getSellerTaxName().equals(head.getSupplierName())).findFirst();
//            if (cartOptional.isPresent()) {
//                throw new RuntimeException("发票明细关联了其他供应商的发票,请检查!");
//            }

            //开票申请单校验预付款是否被使用
//            if (CollectionUtils.isNotEmpty(params.getAddAdvances())){
//                invoicedApplyPaLogic.checkAdvanceUse(params.getAddAdvances(),head.getId());
                //2025-09-06增加采购审核通过保存时，当实际未付金额大于0，判定对账明细中所有订单行是否有未抵扣的预付款金额逻辑校验
//                if(head.getActualUnpaidAmount().compareTo(BigDecimal.ZERO) > 0){
//                    paymentAdvanceApplyDetailLogic.hasUnappliedPrepaymentBalance(head,params.getAddAdvances());
//                }
//            }
            //2025-07-31 增加预付款变更单管理订单 已冲账金额反写逻辑
            //2025-08-02 开票申请中预付款明细保存和删除场景
            //1. 正常保存，还没有和主键进行关联的
            //2. 正常删除一行已保存过有主键id的数据，剩下没有保存过的
            //3. 删除一行已保存过的，再新增一行没有保存过的，还有两行已保存过的
            //4. 全部删除,分前台传过来就没有预付款明细，后台通过查询已报存的明细也返回无

            //先按照正常逻辑来
            /**
             * 全部新增反写金额
             */
//            List<InvoicedApplyPa> addAdvances = params.getAddAdvances();//前台传过来的预付款明细列表
//            //根据开票id查找是否已存在绑定的表里的预付款信息
//            List<InvoicedApplyPa> existInvoicedApplyPaList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,head.getId()));
//            if(CollectionUtils.isNotEmpty(existInvoicedApplyPaList) && CollectionUtils.isNotEmpty(addAdvances)){
//                //1.对比出，没有在库里新增过的，进行累加，库里新增过的则跳过不管（因为已经增加过了），库里有页面传过来没有的则是被删除的，需要再减回去
//                List<String> existPaList = existInvoicedApplyPaList.stream()//表里已存在的变更单号
//                        .filter(item -> item.getPaymentChangeNumber() != null && !item.getPaymentChangeNumber().isEmpty())
//                        .filter(item -> item.getPaymentChangeItemNo() != null && !item.getPaymentChangeItemNo().isEmpty())
//                        .map(item -> item.getPaymentChangeNumber() + "_" + item.getPaymentChangeItemNo())
//                        .collect(Collectors.toList());
//
//                List<String> paramList =addAdvances.stream()  //前台预付款传值列表
//                        .filter(item -> item.getPaymentChangeNumber() != null && !item.getPaymentChangeNumber().isEmpty())
//                        .filter(item -> item.getPaymentChangeItemNo() != null && !item.getPaymentChangeItemNo().isEmpty())
//                        .map(item -> item.getPaymentChangeNumber() + "_" + item.getPaymentChangeItemNo())
//                        .collect(Collectors.toList());
//                if(CollectionUtils.isNotEmpty(existPaList) && CollectionUtils.isNotEmpty(paramList)){
//                    //比较出 e有 p没有的 减回去  比较出e没有 p有的 加上去
//                    Set<String> existSet = new HashSet<>(existPaList);//表里已存在的
//                    Set<String> paramSet = new HashSet<>(paramList);//页面最新传值
//
//                    List<String> onlyInList = existSet.stream()//表里有，页面已经没有了，被删除，需要将金额减回去
//                            .filter(e -> !paramSet.contains(e))
//                            .collect(Collectors.toList());
//
//                    for (String string : onlyInList) {
//                        for (InvoicedApplyPa pa : existInvoicedApplyPaList) {
//                            if(string.equals(pa.getPaymentChangeNumber()+"_"+pa.getPaymentChangeItemNo())){
//                                //表里有，页面已经没有了，被删除，需要将金额减回去
//                                paymentAdvanceApplyDetailLogic.updateReversedAmount(pa.getPaymentChangeNumber(),pa.getPaymentChangeItemNo(),pa.getStrikePrice().negate());
//                            }
//                        }
//                    }
//                    // paramList有而existPaList没有 需要增加
//                    List<String> onlyInList1 = paramSet.stream()
//                            .filter(e -> !existSet.contains(e))
//                            .collect(Collectors.toList());
//                    for (String string : onlyInList1) {
//                        for (InvoicedApplyPa paramApplyPa : addAdvances) {
//                            if(string.equals(paramApplyPa.getPaymentChangeNumber()+"_"+paramApplyPa.getPaymentChangeItemNo())){
//                                //表里没有，页面有，属于新增，需要将金额加上去
//                                paymentAdvanceApplyDetailLogic.updateReversedAmount(paramApplyPa.getPaymentChangeNumber(),paramApplyPa.getPaymentChangeItemNo(),paramApplyPa.getStrikePrice());
//                            }
//                        }
//                    }
//                }
//                if(CollectionUtils.isEmpty(existPaList) && CollectionUtils.isNotEmpty(paramList)){ //表里没变更单号，页面传值有变更单号
//                    //全部加上去
//                    for (InvoicedApplyPa addAdvance : addAdvances) {//页面新绑定的带预付款变更单号的数据
//                        String paymentChangeNumber = addAdvance.getPaymentChangeNumber();
//                        String paymentChangeItemNo = addAdvance.getPaymentChangeItemNo();
//                        if(StringUtils.isNotEmpty(paymentChangeNumber)&&StringUtils.isNotEmpty(paymentChangeItemNo)){
//                            //只存在有变更单的预付款明细需要更新已冲账金额
//                            paymentAdvanceApplyDetailLogic.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,addAdvance.getStrikePrice());
//                        }
//                    }
//                }
//                if(CollectionUtils.isNotEmpty(existPaList) && CollectionUtils.isEmpty(paramList)){
//                    //全部减回去
//                    for (InvoicedApplyPa invoicedApplyPa : existInvoicedApplyPaList) {
//                        String paymentChangeNumber = invoicedApplyPa.getPaymentChangeNumber();
//                        String paymentChangeItemNo = invoicedApplyPa.getPaymentChangeItemNo();
//                        if(StringUtils.isNotEmpty(paymentChangeNumber)&&StringUtils.isNotEmpty(paymentChangeItemNo)){
//                            //页面没有带变更单号的，表里有变更单号，说明已被修改删除更新已冲账金额
//                            paymentAdvanceApplyDetailLogic.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,invoicedApplyPa.getStrikePrice().negate());
//                        }
//                    }
//                }
//
//
//            }else if(CollectionUtils.isNotEmpty(addAdvances) && CollectionUtils.isEmpty(existInvoicedApplyPaList)){
//                for (InvoicedApplyPa addAdvance : params.getAddAdvances()) {//页面新绑定的带预付款变更单号的数据
//                    String paymentChangeNumber = addAdvance.getPaymentChangeNumber();
//                    String paymentChangeItemNo = addAdvance.getPaymentChangeItemNo();
//                    if(StringUtils.isNotEmpty(paymentChangeNumber)&&StringUtils.isNotEmpty(paymentChangeItemNo)){
//                        //更新已冲账金额
//                        paymentAdvanceApplyDetailLogic.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,addAdvance.getStrikePrice());
//                    }
//                }
//            }else if(CollectionUtils.isEmpty(params.getAddAdvances()) && CollectionUtils.isNotEmpty(existInvoicedApplyPaList)){
//                //找出存在的预付款变更单号把金额减掉
//                for (InvoicedApplyPa invoicedApplyPa : existInvoicedApplyPaList) {
//                    String paymentChangeNumber = invoicedApplyPa.getPaymentChangeNumber();
//                    String paymentChangeItemNo = invoicedApplyPa.getPaymentChangeItemNo();
//                    if(StringUtils.isNotEmpty(paymentChangeNumber)&&StringUtils.isNotEmpty(paymentChangeItemNo)){
//                        //页面预付款明细为空，数据库有关联预付款变更单需要更新已冲账金额
//                        paymentAdvanceApplyDetailLogic.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,invoicedApplyPa.getStrikePrice().negate());
//                    }
//                }
//            }
        }

        // 本次变更可能存在新增的明细数据
//        List<InvoicedApplyDetail> newDetailList = Lists.newArrayList();
//        List<InvoicedApplyDetail> currDetailList = Lists.newArrayList();
//        for (InvoicedApplyItemDTO detail : detailList) {
//            if (0 == detail.getId()) {
//                newDetailList.add(detail.toIad());
//            } else {
//                currDetailList.add(detail.toIad());
//            }
//        }

        // 变更前的开票申请明细数据
//        final List<InvoicedApplyDetail> oldIadList = invoicedApplyDetailService.findByInvoiceApplyId(head.getId(), Lists.newArrayList());
        // 变更前开票申请表头数据
        final CostInvoicedApply oldHead = costInvoicedApplyService.getById(head.getId());
//        if (BigDecimal.ZERO.compareTo(head.getStrikePriceAmount())==0){
//            oldHead.setActualUnpaidAmount(head.getInvoiceTaxAmount());
//        }
        //采购审批
        if (1 == params.getRoleType()) {
            // 数据状态 2:待采购确认 3:采购拒绝 6:OA审批不通过 8:财务拒绝
            if (2 != oldHead.getStatus() && 3 != oldHead.getStatus() && 6 != oldHead.getStatus() && 8 != oldHead.getStatus()) {
                throw new DaoException("当前开票申请单的数据状态不允许修改, 请检查");
            }
            // 将有可能变更的数据放到原开票申请对象中
//            oldHead.setInvoiceNo(head.getInvoiceNo());
//            oldHead.setInvoiceNum(head.getInvoiceNum());
            oldHead.setInvoiceNetAmount(head.getInvoiceNetAmount());
            oldHead.setInvoiceTaxAmount(head.getInvoiceTaxAmount());
//            oldHead.setRebateAmount(head.getRebateAmount());
//            oldHead.setRntAmount(head.getRntAmount());
//            oldHead.setDeductionAmount(head.getDeductionAmount());
//            oldHead.setDntAmount(head.getDntAmount());
//            oldHead.setInvoiceTotalAmount(head.getInvoiceTotalAmount());
//            oldHead.setAllBudInnerMoney(head.getAllBudInnerMoney());
//            oldHead.setInvoiceTaxTotalAmount(head.getInvoiceTaxTotalAmount());
            oldHead.setRemark(head.getRemark());
//            oldHead.setTaxCode(head.getTaxCode());
            oldHead.setStrikePriceAmount(head.getStrikePriceAmount());
            oldHead.setActualUnpaidAmount(head.getActualUnpaidAmount());
//            if (null!=head.getStrikePriceAmount()){
//                if (BigDecimal.ZERO.compareTo(head.getStrikePriceAmount())==0){
//                    oldHead.setActualUnpaidAmount(head.getInvoiceTaxAmount());
//                }
//            }
//            oldHead.setDeductionAmountTotal(head.getDeductionAmountTotal());
            oldHead.setStrikeStatus(CollectionUtils.isNotEmpty(params.getAddAdvances())?0:3);

            oldHead.setLocalCurrency(head.getLocalCurrency());
            oldHead.setOriginalCurrency(head.getOriginalCurrency());
            oldHead.setAdvanceLocalCurrency(head.getAdvanceLocalCurrency());
            oldHead.setAdvanceOriginalCurrency(head.getAdvanceOriginalCurrency());
            this.purchaseConfirm(
                    oldHead, params.getApproveRemark(), params.getApproveStatus(), LoginUtil.getCurrentUser(),params.getManualCheckList()
            );
//            if (CollectionUtils.isNotEmpty(params.getAddAdvances())&&0 == params.getApproveStatus()){
//                List<InvoicedApplyPa> invoicedApplyPaList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,head.getId()));
//                invoicedApplyPaList.forEach(invoicedApplyPa -> {
//                    //2025-09-03 如果预付款里关联了变更单，则不更新预付款里的已冲账金额
//                    if(StringUtils.isEmpty(invoicedApplyPa.getPaymentChangeNumber()) && StringUtils.isEmpty(invoicedApplyPa.getPaymentChangeItemNo())){
//                        //更新预付款已冲账金额
//                        PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = paymentAdvanceApplyDetailService.getById(invoicedApplyPa.getPaId());
//                        if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                            paymentAdvanceApplyDetail.setReversalMoney(paymentAdvanceApplyDetail.getReversalMoney().subtract(invoicedApplyPa.getStrikePrice()).compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:paymentAdvanceApplyDetail.getReversalMoney().subtract(invoicedApplyPa.getStrikePrice()));
//                            paymentAdvanceApplyDetailService.updateById(paymentAdvanceApplyDetail);
//                        }
//                    }
//                });
//            }
//            invoicedApplyPaService.remove(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,head.getId()));
//            if (CollectionUtils.isNotEmpty(params.getAddAdvances())&&1 == params.getApproveStatus()){
//                List<InvoicedApplyPa> paList = Lists.newArrayList();
//                List<PaymentAdvanceApplyDetail> paymentAdvanceApplyDetailList = Lists.newArrayList();
//                for (InvoicedApplyPa ipa : params.getAddAdvances()) {
//                    ipa.setInvoiceApplyId(head.getId());
//                    ipa.setId(null);
//                    ipa.setDeleteFlag(0);
////                    ipa.setPaId(paId);
//                    paList.add(ipa);
////
////                    PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = new PaymentAdvanceApplyDetail();
////                    paymentAdvanceApplyDetail.setId(paId);
////                    //发票申请消费标识 0：未消费 1；已消费
////                    paymentAdvanceApplyDetail.setInvoicedFlag(1);
////                    paymentAdvanceApplyDetailList.add(paymentAdvanceApplyDetail);
//                    //2025-09-03增加如果预付款里关联了变更单，则不更新预付款里的已冲账金额
//                    PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = paymentAdvanceApplyDetailService.getById(ipa.getPaId());
//                    if(StringUtils.isEmpty(ipa.getPaymentChangeNumber()) && StringUtils.isEmpty(ipa.getPaymentChangeItemNo())){
//                        //更新预付款已冲账金额
//                        if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                            paymentAdvanceApplyDetail.setReversalMoney(paymentAdvanceApplyDetail.getReversalMoney().add(ipa.getStrikePrice()));
//                        }
//                    }
//                    paymentAdvanceApplyDetailList.add(paymentAdvanceApplyDetail);
//                }
//
//                if (!this.invoicedApplyPaService.saveBatch(paList)) {
//                    throw new DaoException("保存预付款申请明细失败, 前联系管理员");
//                }
//                if (!this.paymentAdvanceApplyDetailService.updateBatchById(paymentAdvanceApplyDetailList)) {
//                    throw new DaoException("更新预付款申请明细失败, 前联系管理员");
//                }
//
//            }

//            invoicedApplyOptLogic.addContentRecord(1, null, null, Lists.newArrayList(), null, LoginUtil.getCurrentUser());
//            invoicedApplyOptLogic.addContentRecord(2, oldHead, head, oldIadList, null, LoginUtil.getCurrentUser());

        } else {//财务审批 roleType = 2  通过1 拒绝是0
            // 数据状态 7:待财务确认
            if (7 != oldHead.getStatus()) {
                throw new DaoException("当前开票申请单的数据状态不允许修改, 请检查");
            }
//            oldHead.setStrikePriceAmount(head.getStrikePriceAmount());
//            oldHead.setActualUnpaidAmount(head.getActualUnpaidAmount());
//            if (null!=head.getStrikePriceAmount()){
//                if (BigDecimal.ZERO.compareTo(head.getStrikePriceAmount())==0){
//                    oldHead.setActualUnpaidAmount(head.getInvoiceTaxAmount());
//                }
//            }
//            oldHead.setDeductionAmountTotal(head.getDeductionAmountTotal());
            oldHead.setRemark(head.getRemark());
            this.financeConfirm(oldHead, params.getApproveRemark(), params.getApproveStatus(), LoginUtil.getCurrentUser(),params.getManualCheckList());
        }

        // 保存关联发票信息
        costInvoicedReceiptLogic.operateInvoice(params.getInvoicedReceiptData(),head.getId(),LoginUtil.getCurrentUser());
    }


    public void financeConfirm(CostInvoicedApply head, String approveRemark, Integer approveStatus, CurrentUserDTO user,List<AttachmentManualCheck> manualCheckList) {
        CostInvoicedApply updateHead = new CostInvoicedApply();
        updateHead.setId(head.getId());
        updateHead.setRemark(head.getRemark());
        updateHead.setUpdateTime(LocalDateTime.now());
        updateHead.setUpdateUserId(user.getUserId());
        updateHead.setUpdateUserCode(user.getLoginName());
        updateHead.setUpdateUserName(user.getName());

        // 数据状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
        if (1 == approveStatus) {
            //查询发票
            List<CostInvoicedReceipt> invoicedReceipts = costInvoicedReceiptService.list(new LambdaQueryWrapper<>(CostInvoicedReceipt.class).eq(CostInvoicedReceipt::getIaId, head.getId()));
            if (CollUtil.isNotEmpty(invoicedReceipts)) {
                //提取serialNo不为空的数据为list<String>
                List<String> serialNoList = invoicedReceipts.stream()
                        .map(CostInvoicedReceipt::getSerialNo)
                        .filter(StrUtil::isNotEmpty)
                        .toList();
                if (CollUtil.isNotEmpty(serialNoList)) {
                    kingdeeInvoiceCloudLogic.billSign(String.valueOf(head.getId()), "01", String.join(",", serialNoList));
                }
            }
            updateHead.setFinanceConfirmTime(LocalDateTime.now());
            updateHead.setFinanceConfirmUserId(LoginUtil.getUserId());
            updateHead.setStatus(9);
            updateHead.setPostStatus(2);
            CostInvoicedApply old = costInvoicedApplyService.getById(head.getId());
            //美金对账单，到票申请交接-财务确认后，无需“财务过账”
            if (!"CNY".equals(old.getCurrencyCode())||old.getForeignCurrencyAddFlag()==1){
                updateHead.setPostStatus(6);
            }
            if (CollUtil.isNotEmpty(manualCheckList)){
                manualCheckList.forEach(manualCheck -> {
                    if (manualCheck.getId() == null){
                        manualCheck.setCreateUser(LoginUtil.getUserId());
                        manualCheck.setCreateTime(LocalDateTime.now());
                    }else {
                        manualCheck.setUpdateUser(LoginUtil.getUserId());
                        manualCheck.setUpdateTime(LocalDateTime.now());
                    }
                });
                attachmentManualCheckService.saveOrUpdateBatch(manualCheckList);
            }
        } else {
            updateHead.setStatus(8);
            updateHead.setPostStatus(1);

            //查询已经关联预付款数据，如果有就减去上次冲账金额且删除
//            List<InvoicedApplyPa> invoicedApplyPaList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,head.getId()));
//            if (CollectionUtils.isNotEmpty(invoicedApplyPaList)){
//                List<PaymentAdvanceApplyDetail> paymentAdvanceApplyDetailList = Lists.newArrayList();
//                invoicedApplyPaList.forEach(ipa->{
//                    PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = paymentAdvanceApplyDetailService.getById(ipa.getPaId());
//
//                    //2025-09-03增加如果开票申请关联的预付款申请单上关联了变更单，则不更新该条预付款已冲账金额
//                    if(StringUtils.isEmpty(ipa.getPaymentChangeNumber()) && StringUtils.isEmpty(ipa.getPaymentChangeItemNo())){
//                        if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                            paymentAdvanceApplyDetail.setReversalMoney(paymentAdvanceApplyDetail.getReversalMoney().subtract(ipa.getStrikePrice()).compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:paymentAdvanceApplyDetail.getReversalMoney().subtract(ipa.getStrikePrice()));
//                        }
//                    }else{
//                        String paymentChangeNumber = ipa.getPaymentChangeNumber();
//                        String paymentChangeItemNo = ipa.getPaymentChangeItemNo();
//                        if(StringUtils.isNotEmpty(paymentChangeNumber)&&StringUtils.isNotEmpty(paymentChangeItemNo)){
//                            //页面预付款明细为空，数据库有关联预付款变更单需要更新已冲账金额
//                            paymentAdvanceApplyDetailLogic.updateReversedAmount(paymentChangeNumber,paymentChangeItemNo,ipa.getStrikePrice().negate());
//                        }
//                    }
//                    if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                        paymentAdvanceApplyDetailList.add(paymentAdvanceApplyDetail);
//                    }
//                });
//                if(CollectionUtils.isNotEmpty(paymentAdvanceApplyDetailList)){
//                    paymentAdvanceApplyDetailService.updateBatchById(paymentAdvanceApplyDetailList);
//                }
//                invoicedApplyPaService.remove(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,head.getId()));
//            }
//            CostInvoicedApply invoicedApply = invoicedApplyService.getById(head.getId());
            //1，财务驳回发票交接，增加邮件提醒，  邮件收件人：供应商（(4)财务人员、(12)业务接口人、(5)业务经理）、对账采购组窗口
//            SupplierContactsDTO emailBis = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "12");
//            SupplierContactsDTO emailFin = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "4");
//            SupplierContactsDTO emailJl = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "5");
//
//            if (Objects.nonNull(emailBis) && StringUtils.isNotEmpty(emailBis.getEmail())) {
//                sendEmailToSupplier("JW_POST_160", emailBis.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),approveRemark);
//            }
//            if (Objects.nonNull(emailFin) && StringUtils.isNotEmpty(emailFin.getEmail())) {
//                sendEmailToSupplier("JW_POST_160", emailFin.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),approveRemark);
//            }
//            //增加业务经理
//            if (Objects.nonNull(emailJl) && StringUtils.isNotEmpty(emailJl.getEmail())) {
//                sendEmailToSupplier("JW_POST_160", emailJl.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),approveRemark);
//            }
        }
        if (!costInvoicedApplyService.updateById(updateHead)) {
            throw new DaoException("更新对账单主表数据失败, 请联系管理员");
        }


        if (!costInvoicedApplyApproveLogic.addApproveRecord(head.getId(), head.getInvoiceApplyNo(), approveStatus, approveRemark, 2, user)) {
            throw new DaoException("添加开票申请单审批记录失败, 请联系管理员");
        }

        // 财务通过后, 生成SRM开票申请过账数据
        if (2 == updateHead.getPostStatus()) {
            CostInvoicedApplyPostResult pr1 = new CostInvoicedApplyPostResult();
            pr1.setCreateTime(LocalDateTime.now());
            pr1.setInvoiceApplyId(head.getId());
            pr1.setInvoiceApplyNo(head.getInvoiceApplyNo());
            //查找不包含贷项的凭证 161 162
//            List<InvoicedApplyDetail> details = invoicedApplyDetailLogic.findByInvoiceNo(head.getInvoiceApplyNo());
//            if (CollectionUtils.isNotEmpty(details)) {
//                // 凭证发票
//                pr1.setPostInvoiceType(1);
//            } else {
//                // 贷项凭证
//                pr1.setPostInvoiceType(4);
//            }
            if (!costInvoicedApplyPostResultService.save(pr1)) {
                throw new DaoException("添加开票申请单待过账记录失败, 请联系管理员");
            }
//            InvoicedApply invoicedApply = invoicedApplyService.getById(head.getId());
//            //异步邮件通知 供应商 12业务接口人 4财务人员 2024-11-13 邓京术
//            SupplierContactsDTO emailBis = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "12");
//            SupplierContactsDTO emailFin = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "4");
//            SupplierContactsDTO emailJl = supplierClient.getDefaultContact(invoicedApply.getSupplierCode(), "5");
//
//            if (Objects.nonNull(emailBis) && StringUtils.isNotEmpty(emailBis.getEmail())) {
//                sendEmailToSupplier("JW_POST_113", emailBis.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),"");
//            }
//            if (Objects.nonNull(emailFin) && StringUtils.isNotEmpty(emailFin.getEmail())) {
//                sendEmailToSupplier("JW_POST_113", emailFin.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),"");
//            }
//            //增加业务经理
//            if (Objects.nonNull(emailJl) && StringUtils.isNotEmpty(emailJl.getEmail())) {
//                sendEmailToSupplier("JW_POST_113", emailJl.getEmail(), invoicedApply.getSupplierName(), invoicedApply.getAccountStatementNo(),"");
//            }
        }
    }


    /**
     * 采购确认开票申请
     *
     * @param head 变更的开票申请表头数据
     * @param approveRemark 审批备注
     * @param approveStatus 确认结果 0:拒绝 1:通过
     * @param user 当前操作人
     */
    private void purchaseConfirm(
            CostInvoicedApply head, String approveRemark, Integer approveStatus, CurrentUserDTO user,List<AttachmentManualCheck> manualCheckList
    ){
        // 保存开票申请单审批确认记录
        if (!costInvoicedApplyApproveLogic.addApproveRecord(head.getId(), head.getInvoiceApplyNo(), approveStatus, approveRemark, 1, user)) {
            throw new DaoException("添加开票申请单审批记录失败, 请联系管理员");
        }

        if (1 == approveStatus) {
            head.setStatus(7);
            //计算开票税额
//            head.setInvoiceDiffAmount(head.getInvoiceTaxAmount().subtract(head.getInvoiceNetAmount()));
            // 先变更开票申请相关数据
//            this.dataEdit(head, detailList, delDidList, delSdIdList, delSrIdList, addSdIdList, addSrIdList,null, user);

            // 开票申请单采购确认出现总金额差异超过±1 则需要推送OA审批
//            BigDecimal diffAmount = BigDecimal.ZERO;
//            for (InvoicedApplyItemDto dto : detailList) {
//                diffAmount = dto.getIaDiffAmount().add(diffAmount);
//            }
//
//            // 默认单价差异范围
//            BigDecimal difRang = BigDecimal.ONE;
//            // 获取字典配置中的单价差异范围
//            final DictItemDto item = dictService.getDictDataByTypeAndItemCode("statement_invoiced_difference", "invoiced_difference_amount");
//            if (null != item) {
//                difRang = new BigDecimal(item.getItemDescription());
//            }
//
//            // 采购确认后需要推送OA审批
//            if (diffAmount.abs().compareTo(difRang) >= 0) {
//                final OaReturnResult result = this.invoicedApplyPushOa(head, detailList, diffAmount, user);
//                if (0 == result.getCode()) {
//                    // 数据状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
//                    head.setStatus(5);
//                    head.setOaProcessNo(result.getData());
//                    head.setPushOaNum(head.getPushOaNum() + 1);
//                    head.setPushOaUserCode(user.getLoginName());
//                    head.setPushOaUserName(user.getName());
//                } else {
//                    head.setStatus(4);
//                }
//            }

            // 开票申请表头添加采购确认人相关信息
            head.setPcTime(LocalDateTime.now());
            head.setPcUserId(user.getUserId());
            head.setPcUserCode(user.getLoginName());
            head.setPcUserName(user.getName());

//            if ("CNY".equals(head.getCurrencyCode())){
//                head.setActualUnpaidAmount(head.getInvoiceTaxTotalAmount().subtract(head.getStrikePriceAmount()==null?BigDecimal.ZERO:head.getStrikePriceAmount()));
//            }else {
//                head.setActualUnpaidAmount(head.getInvoiceTaxTotalAmount().add(head.getPaymentCertificateTaxAmount()).subtract(head.getStrikePriceAmount()==null?BigDecimal.ZERO:head.getStrikePriceAmount()));
//            }

            //判断是否有签署附件
            Boolean su = eSignClient.checkList(head.getAccountStatementId());

//            if(head.getActualUnpaidAmount() ==  null){
//                throw new DaoException("实际未付金额不能为空");
//            }

//            if(head.getActualUnpaidAmount().compareTo(BigDecimal.ZERO) != 0 ){
//                if (head.getPaperlessFlag()==1&&!su){
//                    throw new DaoException("请签署电子签章");
//                }
//            }


            //影像化
            this.toImg(head.getId());
            if (CollUtil.isNotEmpty(manualCheckList)){
                manualCheckList.forEach(manualCheck -> {
                    if (manualCheck.getId() == null){
                        manualCheck.setCreateUser(LoginUtil.getUserId());
                        manualCheck.setCreateTime(LocalDateTime.now());
                    }else {
                        manualCheck.setUpdateUser(LoginUtil.getUserId());
                        manualCheck.setUpdateTime(LocalDateTime.now());
                    }
                });
                attachmentManualCheckService.saveOrUpdateBatch(manualCheckList);
            }
        } else {
            head.setStatus(3);

            this.deleteImg(head.getId());
//            attachmentManualCheckService.remove(new LambdaQueryWrapper<AttachmentManualCheck>()
//                    .eq(AttachmentManualCheck::getBusinessType,1)
//                    .eq(AttachmentManualCheck::getBusinessId,head.getId())
//            );
        }

        if (!costInvoicedApplyService.updateById(head)) {
            throw new DaoException("更新开票申请表头数据失败, 前联系管理员");
        }

        // 采购到票确认后状态变更为7, 则清空OA相关字段值
        if (7 == head.getStatus()) {
            CostInvoicedApply oldHead = costInvoicedApplyService.getById(head.getId());
            oldHead.setPushOaUserCode(null);
            oldHead.setUpdateUserName(null);
            oldHead.setPushOaNum(0);
            oldHead.setOaProcessId(null);
            oldHead.setOaProcessNo(null);
            costInvoicedApplyService.updateById(oldHead);
        }
    }


    /**
     * 删除影像化
     * @param iaId 开票申请ID
     */
    @Override
    public void deleteImg(Long iaId){
        //删除影像化
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getById(iaId);
        if (ObjectUtil.isEmpty(invoicedApply.getImgTime())){
            return;
        }
        KingdeeInvoiceCloudImageDTO kingdeeInvoiceCloudImageDTO = new KingdeeInvoiceCloudImageDTO();
        kingdeeInvoiceCloudImageDTO.setImageCode(invoicedApply.getImgCode());
        kingdeeImageLogic.deleteAllImage(kingdeeInvoiceCloudImageDTO);

        List<BusinessAttachment> businessAttachments = businessAttachmentService.list(new LambdaQueryWrapper<BusinessAttachment>().eq(BusinessAttachment::getBusinessId, iaId));
        //获取对账单签署附件
        List<DigitalSealBusinessDetailDTO> digitalSealBusinessDetailDTOS = eSignLogic.fileList(invoicedApply.getAccountStatementId(), "cost_account_statement,cost_purchase_sale_contract,cost_purchase_sale_process_contract", "1,2",null);
        if (CollUtil.isNotEmpty(digitalSealBusinessDetailDTOS)) {
            digitalSealBusinessDetailDTOS.forEach(digitalSealBusinessDetailDTO -> {
                BusinessAttachment businessAttachmentDTO = new BusinessAttachment();
                businessAttachmentDTO.setBusinessId(iaId);
                businessAttachmentDTO.setBusinessTypeCode("cost_account_statement");
                businessAttachmentDTO.setImageFileId(digitalSealBusinessDetailDTO.getImageFileId());
                businessAttachmentDTO.setImageCode(digitalSealBusinessDetailDTO.getImageCode());
                businessAttachmentDTO.setFileId(digitalSealBusinessDetailDTO.getFileId());
                businessAttachments.add(businessAttachmentDTO);
            });
        }
        //获取发票附件
        List<CostInvoicedReceipt> invoicedReceipts = costInvoicedReceiptService.list(Wrappers.lambdaQuery(CostInvoicedReceipt.class).eq(CostInvoicedReceipt::getIaId, iaId));
        List<BusinessAttachment> invoicedReceiptFiles = new ArrayList<>();
        if (CollUtil.isNotEmpty(invoicedReceipts)){
            //提取invoicedReceipts中的附件id
            List<Long> invoicedReceiptFileIds = invoicedReceipts.stream().map(CostInvoicedReceipt::getFileId).collect(Collectors.toList());
            List<FileResposeCDTO> fileResposeCDTOList = fileClient.getFileInfos(invoicedReceiptFileIds);
            if (CollUtil.isNotEmpty(fileResposeCDTOList)){
                fileResposeCDTOList.forEach(file -> {
                    BusinessAttachment businessAttachmentDTO = new BusinessAttachment();
                    businessAttachmentDTO.setBusinessId(iaId);
                    businessAttachmentDTO.setBusinessTypeCode("cost_invoice_apply");
                    businessAttachmentDTO.setImageFileId(file.getImageFileId());
                    businessAttachmentDTO.setImageCode(file.getImageCode());
                    businessAttachmentDTO.setFileId(file.getId());
                    businessAttachments.add(businessAttachmentDTO);
                    invoicedReceiptFiles.add(businessAttachmentDTO);
                });
            }

        }

        //获取缴款书附件
        List<CostInvoicedPaymentCertificate> invoicedPaymentCertificates = costInvoicedPaymentCertificateService.list(Wrappers.lambdaQuery(CostInvoicedPaymentCertificate.class).eq(CostInvoicedPaymentCertificate::getIaId, iaId));
        if (CollUtil.isNotEmpty(invoicedPaymentCertificates)){
            //提取invoicedReceipts中的附件id
            List<Long> invoicedReceiptFileIds = invoicedPaymentCertificates.stream().map(CostInvoicedPaymentCertificate::getFileId).collect(Collectors.toList());
            List<FileResposeCDTO> fileResposeCDTOList = fileClient.getFileInfos(invoicedReceiptFileIds);
            if (CollUtil.isNotEmpty(fileResposeCDTOList)){
                fileResposeCDTOList.forEach(file -> {
                    BusinessAttachment businessAttachmentDTO = new BusinessAttachment();
                    businessAttachmentDTO.setBusinessId(iaId);
                    businessAttachmentDTO.setBusinessTypeCode("customs_payment_voucher");
                    businessAttachmentDTO.setImageFileId(file.getImageFileId());
                    businessAttachmentDTO.setImageCode(file.getImageCode());
                    businessAttachmentDTO.setFileId(file.getId());
                    businessAttachments.add(businessAttachmentDTO);
                    invoicedReceiptFiles.add(businessAttachmentDTO);
                });
            }

        }

        costInvoicedApplyService.update(new LambdaUpdateWrapper<CostInvoicedApply>()
//                        .set(InvoicedApply::getImgCode,null)
                .set(CostInvoicedApply::getImgTime, null)
                .set(CostInvoicedApply::getImgUserId, null)
                .eq(CostInvoicedApply::getId, iaId));
        if (CollUtil.isNotEmpty(digitalSealBusinessDetailDTOS)) {
            digitalSealBusinessDetailDTOS.forEach(digitalSealBusinessDetailDTO -> {
                digitalSealBusinessDetailService.update(new LambdaUpdateWrapper<DigitalSealBusinessDetail>()
                        .set(DigitalSealBusinessDetail::getImageCode, null)
                        .set(DigitalSealBusinessDetail::getImagePath, null)
                        .set(DigitalSealBusinessDetail::getImageFileId, null)
                        .eq(DigitalSealBusinessDetail::getId, digitalSealBusinessDetailDTO.getId()));
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void revokeFinConfirm(Long iaId, String revokeReason) {
        if (null == iaId) {
            throw new DaoException("参数错误");
        }
        final CostInvoicedApply apply = costInvoicedApplyService.getById(iaId);
        if (null == apply) {
            throw new DaoException("系统未找到相应的开票申请信息");
        }
        if (7 != apply.getStatus()) {
            throw new DaoException("开票申请不能进行撤销操作, 请检查开票申请状态");
        }

        CostInvoicedApply updateHead = new CostInvoicedApply();
        updateHead.setId(apply.getId());
        updateHead.setStatus(2);
        updateHead.setUpdateUserId(LoginUtil.getUserId());
        updateHead.setUpdateUserCode(LoginUtil.getAccount());
        updateHead.setUpdateUserName(LoginUtil.getName());
        updateHead.setUpdateTime(LocalDateTime.now());
        costInvoicedApplyService.updateById(updateHead);

        //查询已经关联预付款数据，如果有就减去上次冲账金额且删除
//        List<InvoicedApplyPa> invoicedApplyPaList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,apply.getId()));
//        if (CollectionUtils.isNotEmpty(invoicedApplyPaList)){
//            List<PaymentAdvanceApplyDetail> paymentAdvanceApplyDetailList = Lists.newArrayList();
//            invoicedApplyPaList.forEach(ipa->{
//                PaymentAdvanceApplyDetail paymentAdvanceApplyDetail = paymentAdvanceApplyDetailService.getById(ipa.getPaId());
//
//                //查询预付款转单变更信息
//                if(StringUtils.isNotEmpty(ipa.getPaymentChangeNumber()) && StringUtils.isNotEmpty(ipa.getPaymentChangeItemNo())){
//                    //撤回时，更新金额会去（减去相应的申请金额）
//                    paymentAdvanceApplyDetailLogic.updateReversedAmount(ipa.getPaymentChangeNumber(),ipa.getPaymentChangeItemNo(),ipa.getStrikePrice().negate());
//                }else{
//                    paymentAdvanceApplyDetail.setReversalMoney(paymentAdvanceApplyDetail.getReversalMoney().subtract(ipa.getStrikePrice()).compareTo(BigDecimal.ZERO)<0?BigDecimal.ZERO:paymentAdvanceApplyDetail.getReversalMoney().subtract(ipa.getStrikePrice()));
//                }
//                if (ObjectUtil.isNotNull(paymentAdvanceApplyDetail)){
//                    paymentAdvanceApplyDetailList.add(paymentAdvanceApplyDetail);
//                }
//            });
//            paymentAdvanceApplyDetailService.updateBatchById(paymentAdvanceApplyDetailList);
//            invoicedApplyPaService.remove(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,apply.getId()));
//
//
//
//        }

        // 2.记录撤销原因
        CostInvoicedApplyApprove approve = new CostInvoicedApplyApprove();
        approve.setIaId(apply.getId());
        approve.setIaNo(apply.getInvoiceApplyNo());
        approve.setApproveResult(2);
        approve.setApproveOpinion(revokeReason);
        approve.setApproveUserId(LoginUtil.getUserId());
        approve.setApproveUserCode(LoginUtil.getAccount());
        approve.setApproveUserName(LoginUtil.getName());
        // 撤销只能由采购操作
        approve.setApproveNode(1);
        approve.setApproveTime(LocalDateTime.now());
        costInvoicedApplyApproveService.save(approve);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void financeConfirmCancel(String ids) {
        final List<Long> idList = JSONArray.parseArray(ids, Long.class);
        for (Long invoiceApplyId : idList){
            CostInvoicedApply updateHead = new CostInvoicedApply();
            updateHead.setId(invoiceApplyId);
            updateHead.setUpdateTime(LocalDateTime.now());
            updateHead.setUpdateUserId(LoginUtil.getUserId());
            updateHead.setUpdateUserCode(LoginUtil.getAccount());
            updateHead.setUpdateUserName(LoginUtil.getName());
            // 数据状态 1:暂存发票 2:待采购确认发票 3:采购拒绝发票 4:待推送OA审批 5:OA审批中 6:OA审批不通过 7:待财务确认发票 8:财务驳回发票 9:发票已确认
            updateHead.setStatus(7);
            updateHead.setPostStatus(1);
            if (!costInvoicedApplyService.updateById(updateHead)) {
                throw new DaoException("更新对账单主表数据失败, 请联系管理员");
            }
            if (!costInvoicedApplyPostResultService.remove(Wrappers.lambdaQuery(CostInvoicedApplyPostResult.class).eq(CostInvoicedApplyPostResult::getInvoiceApplyId,invoiceApplyId))) {
                throw new DaoException("删除开票申请单待过账记录失败, 请联系管理员");
            }
            //取消发票确认
            List<CostInvoicedReceipt> invoicedReceipts = costInvoicedReceiptService.list(new LambdaQueryWrapper<>(CostInvoicedReceipt.class).eq(CostInvoicedReceipt::getIaId, invoiceApplyId));
            if (CollUtil.isNotEmpty(invoicedReceipts)) {
                //提取serialNo不为空的数据为list<String>
                List<String> serialNoList = invoicedReceipts.stream()
                        .map(CostInvoicedReceipt::getSerialNo)
                        .filter(StrUtil::isNotEmpty)
                        .toList();
                if (CollUtil.isNotEmpty(serialNoList)) {
                    kingdeeInvoiceCloudLogic.billSign(String.valueOf(invoiceApplyId), "02", String.join(",", serialNoList));
                }
            }
            // 2.记录撤销原因

            CostInvoicedApply old = costInvoicedApplyService.getById(invoiceApplyId);
            CostInvoicedApplyApprove approve = new CostInvoicedApplyApprove();
            approve.setIaId(old.getId());
            approve.setIaNo(old.getInvoiceApplyNo());
            approve.setApproveResult(3);
            approve.setApproveOpinion("财务取消确认");
            approve.setApproveUserId(LoginUtil.getUserId());
            approve.setApproveUserCode(LoginUtil.getAccount());
            approve.setApproveUserName(LoginUtil.getName());
            // 撤销只能由采购操作
            approve.setApproveNode(2);
            approve.setApproveTime(LocalDateTime.now());
            costInvoicedApplyApproveService.save(approve);
        }
    }
    /**
     * 影像化
     *
     * @param iaId 开票申请ID
     */
    @Override
    public void toImg(Long iaId) {
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getById(iaId);
        //影像化
        List<BusinessAttachmentDTO> accountStatementAttachments = this.getImgList(iaId);
        if (CollUtil.isNotEmpty(accountStatementAttachments)) {
            KingdeeInvoiceCloudImageDTO kingdeeInvoiceCloudImageDTO = new KingdeeInvoiceCloudImageDTO();
            kingdeeInvoiceCloudImageDTO.setImageCode(StrUtil.isNotEmpty(invoicedApply.getImgCode()) ? invoicedApply.getImgCode() : sequenceClient.createSequenceNo("image_code"));
            if (CollUtil.isNotEmpty(accountStatementAttachments)) {
                kingdeeInvoiceCloudImageDTO.setBusinessAttachmentList(accountStatementAttachments);
                KingdeeInvoiceCloudImageDTO result = kingdeeImageLogic.pushImage(kingdeeInvoiceCloudImageDTO);
                //更新签署附件的影像
                accountStatementAttachments.forEach(businessAttachmentDTO -> {
                    if (businessAttachmentDTO.getType().equals("account")) {
                        digitalSealBusinessDetailService.update(new LambdaUpdateWrapper<DigitalSealBusinessDetail>()
                                .set(DigitalSealBusinessDetail::getImageCode, result.getImageCode())
                                .set(DigitalSealBusinessDetail::getImagePath, result.getImagePath())
                                .set(DigitalSealBusinessDetail::getImageFileId, businessAttachmentDTO.getImageFileId())
                                .eq(DigitalSealBusinessDetail::getId, businessAttachmentDTO.getFileId()));
                    }
                });
                //发票附件的影像
                accountStatementAttachments.forEach(businessAttachmentDTO -> {
                    if (businessAttachmentDTO.getType().equals("invoice")) {
                        attachmentService.update(new LambdaUpdateWrapper<Attachment>()
                                .set(Attachment::getImageCode, result.getImageCode())
                                .set(Attachment::getImagePath, result.getImagePath())
                                .set(Attachment::getImageFileId, businessAttachmentDTO.getImageFileId())
                                .eq(Attachment::getId, businessAttachmentDTO.getFileId()));
                    }
                });
                //缴款书附件的影像
                accountStatementAttachments.forEach(businessAttachmentDTO -> {
                    if (businessAttachmentDTO.getType().equals("customs_payment_voucher")) {
                        attachmentService.update(new LambdaUpdateWrapper<Attachment>()
                                .set(Attachment::getImageCode, result.getImageCode())
                                .set(Attachment::getImagePath, result.getImagePath())
                                .set(Attachment::getImageFileId, businessAttachmentDTO.getImageFileId())
                                .eq(Attachment::getId, businessAttachmentDTO.getFileId()));
                    }
                });
                costInvoicedApplyService.update(new LambdaUpdateWrapper<CostInvoicedApply>().set(CostInvoicedApply::getImgCode, result.getImageCode()).set(CostInvoicedApply::getImgTime, LocalDateTime.now()).set(CostInvoicedApply::getImgUserId, LoginUtil.getUserId())
                        .eq(CostInvoicedApply::getId, iaId));
            }

        }
    }

    @Override
    public List<BusinessAttachmentDTO>  getImgList(Long id) {
        CostInvoicedApply invoicedApply = costInvoicedApplyService.getById(id);
        //影像化
//        List<BusinessAttachmentDTO> accountStatementAttachments = businessAttachmentLogic.getListByBusinessId(id);
        List<BusinessAttachmentDTO> accountStatementAttachments = new ArrayList<>();
        //获取对账单签署附件
        List<DigitalSealBusinessDetailDTO> digitalSealBusinessDetailDTOS = eSignLogic.fileList(invoicedApply.getAccountStatementId(), "cost_account_statement,cost_purchase_sale_contract,cost_purchase_sale_process_contract", "1,2",1);
        if (CollUtil.isNotEmpty(digitalSealBusinessDetailDTOS)) {
            DictDTO dictDTO = dictClient.getDictByTypeAndCode("businessFileType", "account");
            digitalSealBusinessDetailDTOS.forEach(digitalSealBusinessDetailDTO -> {
                BusinessAttachmentDTO businessAttachmentDTO = new BusinessAttachmentDTO();
                Attachment attachment = attachmentService.getById(digitalSealBusinessDetailDTO.getFileId());
                businessAttachmentDTO.setFileName(attachment.getFileName());
                businessAttachmentDTO.setBusinessId(id);
                businessAttachmentDTO.setType("account");
                businessAttachmentDTO.setBusinessTypeCode("cost_account_statement");
                businessAttachmentDTO.setSort(ObjectUtil.isNotNull(dictDTO)?dictDTO.getSort():null);
                businessAttachmentDTO.setImageFileId(digitalSealBusinessDetailDTO.getImageFileId());
                businessAttachmentDTO.setImageCode(digitalSealBusinessDetailDTO.getImageCode());
                businessAttachmentDTO.setFileId(digitalSealBusinessDetailDTO.getFileId());
                accountStatementAttachments.add(businessAttachmentDTO);
            });
        }
        //获取发票附件
        List<CostInvoicedReceipt> invoicedReceipts = costInvoicedReceiptService.list(Wrappers.lambdaQuery(CostInvoicedReceipt.class).eq(CostInvoicedReceipt::getIaId, id));
        if (CollUtil.isNotEmpty(invoicedReceipts)){
            //提取invoicedReceipts中的附件id
            List<Long> invoicedReceiptFileIds = invoicedReceipts.stream().map(CostInvoicedReceipt::getFileId).collect(Collectors.toList());
            List<FileResposeCDTO> fileResposeCDTOList = fileClient.getFileInfos(invoicedReceiptFileIds);
            if (CollUtil.isNotEmpty(fileResposeCDTOList)){
                DictDTO dictDTO = dictClient.getDictByTypeAndCode("businessFileType", "invoice");
                fileResposeCDTOList.forEach(file -> {
                    BusinessAttachmentDTO businessAttachmentDTO = new BusinessAttachmentDTO();
                    businessAttachmentDTO.setFileId(file.getId());
                    businessAttachmentDTO.setImageFileId(file.getImageFileId());
                    businessAttachmentDTO.setType("invoice");
                    businessAttachmentDTO.setFileName(file.getFileName());
                    businessAttachmentDTO.setSort(ObjectUtil.isNotNull(dictDTO)?dictDTO.getSort():null);
                    accountStatementAttachments.add(businessAttachmentDTO);
                });
            }
        }
        List<CostInvoicedPaymentCertificate> invoicedPaymentCertificates = costInvoicedPaymentCertificateService.list(Wrappers.lambdaQuery(CostInvoicedPaymentCertificate.class).eq(CostInvoicedPaymentCertificate::getIaId, id));
        if (CollUtil.isNotEmpty(invoicedPaymentCertificates)){
            //提取invoicedReceipts中的附件id
            List<Long> invoicedReceiptFileIds = invoicedPaymentCertificates.stream().map(CostInvoicedPaymentCertificate::getFileId).collect(Collectors.toList());
            List<FileResposeCDTO> fileResposeCDTOList = fileClient.getFileInfos(invoicedReceiptFileIds);
            if (CollUtil.isNotEmpty(fileResposeCDTOList)){
                DictDTO dictDTO = dictClient.getDictByTypeAndCode("businessFileType", "customs_payment_voucher");
                fileResposeCDTOList.forEach(file -> {
                    BusinessAttachmentDTO businessAttachmentDTO = new BusinessAttachmentDTO();
                    businessAttachmentDTO.setFileId(file.getId());
                    businessAttachmentDTO.setImageFileId(file.getImageFileId());
                    businessAttachmentDTO.setType("customs_payment_voucher");
                    businessAttachmentDTO.setFileName(file.getFileName());
                    businessAttachmentDTO.setSort(ObjectUtil.isNotNull(dictDTO)?dictDTO.getSort():null);
                    accountStatementAttachments.add(businessAttachmentDTO);
                });
            }
        }
        //accountStatementAttachments中按照sort从小到大排序
        accountStatementAttachments.sort(
                Comparator.nullsLast(Comparator.comparing(BusinessAttachmentDTO::getSort)));

        return accountStatementAttachments;
    }

}
