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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.AmountKindDict;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.InvoiceDict;
import com.sunxung.factoring.dict.impl.SettlementDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.businessmanagement.BusinessBasicInfo;
import com.sunxung.factoring.entity.businessmanagement.BusinessSupplierInfo;
import com.sunxung.factoring.entity.customerinformation.Customer;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.invoicemanage.*;
import com.sunxung.factoring.entity.invoicemanage.vo.SearchGoodsVo;
import com.sunxung.factoring.entity.project.BusinessAssignee;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingTaskVo;
import com.sunxung.factoring.entity.project.vo.SearchBusinessProcessingTask;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractBasicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractManagement;
import com.sunxung.factoring.entity.purchcontractmanagement.vo.PurchContractCompletedVo;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContractBasicInfo;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContract;
import com.sunxung.factoring.entity.settlement.SettlementBasicInfo;
import com.sunxung.factoring.entity.settlement.SettlementGoodsInfo;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.*;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.mapper.invoicemanage.InvoiceBasicInfoMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.invoicemanage.*;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractBasicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractService;
import com.sunxung.factoring.service.salescontractmanagement.ICSalesContractBasicInfoService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.sys.*;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @Description : 销售发票信息service实现类
 * @Author : JiaYf
 * @Date: 2021-10-18 19:15
 */
@Service("invoiceManagerService")
public class InvoiceBasicInfoServiceImpl extends ServiceImpl<InvoiceBasicInfoMapper, InvoiceBasicInfo>
        implements InvoiceBasicInfoService {
    @Autowired
    private DictionaryService dictService;

    @Autowired
    private BusinessAssigneeService assigneeService;

    @Autowired
    private UserService userService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private InvoiceGoodsInfoService invoiceGoodsInfoService;

    @Autowired
    private InvoicePossessionCostInfoService invoicePossessionCostInfoService;

    @Autowired
    private InvoiceSupplierInfoService invoiceSupplierInfoService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;
    @Autowired
    private FileService fileService;
    @Autowired
    private InvoiceHisInfoService invoiceHisInfoService;

    @Autowired
    private InvoiceHisSupplierInfoService invoiceHisSupplierInfoService;

    @Autowired
    private InvoiceHisPossessionCostInfoService invoiceHisPossessionCostInfoService;

    @Autowired
    private InvoiceHisGoodsInfoService invoiceHisGoodsInfoService;

    @Autowired
    private InvoiceCustomerInfoService invoiceCustomerInfoService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private InvoiceApprovalService invoiceApprovalService;

    @Autowired
    private CUserService cUserService;
    @Autowired
    @Lazy
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private PurchaseInvoiceInfoService purchaseInvoiceInfoService;
    @Autowired
    private PurchaseInvoiceHisInfoService purchaseInvoiceHisInfoService;

    @Override
    public InvoiceBasicInfo get(Long id) {
        InvoiceBasicInfo invoiceBasicInfo = baseMapper.getListInfo(id);
        return invoiceBasicInfo;
    }

    @Override
    public List<BusinessProcessingTaskVo> findMyCompletedList(SearchBusinessProcessingTask search) {
        return baseMapper.findMyCompletedList(search);
    }

    @Override
    public List<BusinessProcessingTaskVo> findAllList(SearchBusinessProcessingTask search) {
        List<BusinessProcessingTaskVo> list = baseMapper.findAllList(search);
        list.removeAll(Collections.singleton(null));
        list.stream().forEach(processingTaskVo -> autoButtonFlag(processingTaskVo));
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(InvoiceBasicInfo invoiceBasicInfo, HttpServletRequest request) throws IOException {
        //保存发票有关信息
        InvoiceBasicInfo savedSaleInvoiceVo = saveSaleInvoice(invoiceBasicInfo, request);
        //开启流程，并使流程转到财务审核
        startFlowable(invoiceBasicInfo, request);
    }

    private InvoiceBasicInfo saveSaleInvoice(InvoiceBasicInfo invoiceBasicInfo, HttpServletRequest request) throws IOException {
//        //保存销售发票信息
//        invoiceBasicInfo.setInvoiceStatus(dictService.getByCode(InvoiceDict.ChildEnum.CREATE.getCode()).getId());
//        save(invoiceBasicInfo);
//
//        // 2023.3.10 add 保存或更新核心企业开票信息
//        // 2023.8.4 开票信息与业务关联 历史数据处理
//        if (invoiceBasicInfo.getEnterpriseCustomerInfoId() != null && invoiceBasicInfo.getBusinessBasicInfoId() != null) {
//            InvoiceCustomerInfo newInvoiceCustomerInfo = new InvoiceCustomerInfo(invoiceBasicInfo);
//            InvoiceCustomerInfo invoiceCustomerInfo = invoiceCustomerInfoService.getOne(new QueryWrapper<InvoiceCustomerInfo>()
//                    .eq("customer_id", invoiceBasicInfo.getEnterpriseCustomerInfoId())
//                    .eq("business_basic_info_id", invoiceBasicInfo.getBusinessBasicInfoId()));
//            if (invoiceCustomerInfo == null) {
//                invoiceCustomerInfo = invoiceCustomerInfoService.getOne(new QueryWrapper<InvoiceCustomerInfo>()
//                        .eq("customer_id", invoiceBasicInfo.getEnterpriseCustomerInfoId())
//                        .last("and business_basic_info_id is null"));
//            }
//            if (invoiceCustomerInfo != null) {
//                newInvoiceCustomerInfo.setId(invoiceCustomerInfo.getId());
//            }
//            invoiceCustomerInfoService.saveOrUpdate(newInvoiceCustomerInfo);
//        }
//
//        //保存销售发票的货物信息
        List<InvoiceGoodsInfo> invoiceGoodsInfoList = invoiceBasicInfo.getInvoiceGoodsInfos();
        Boolean flag = false;
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0) {
            for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfoList) {
                if (invoiceGoodsInfo.getGoodsQuantity() != null) {
                    flag = true;
                }
                //如果是货物判断开票数量
//                if (invoiceBasicInfo.getAmountKind().equals(AmountKindDict.ChildEnum.PAYMENT.getCode())) {
//                    if (-1 == invoiceGoodsInfo.getGoodsQuantity().compareTo(invoiceGoodsInfo.getUsedNum().add(invoiceGoodsInfo.getOpenQuantity()))) {
//                        throw new ValidatorException(CodeUtil.FAIL, "开票数量 + 已开数量 不能大于 数量，请修改 “开票数量”");
//                    }
//                }
//                invoiceGoodsInfo.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
            }
//            invoiceGoodsInfoService.saveBatch(invoiceGoodsInfoList);
        }
//        //保存资金占用费
//        InvoicePossessionCostInfo invoicePossessionCostInfos = invoiceBasicInfo.getInvoicePossessionCostInfos();
//        if (invoicePossessionCostInfos != null) {
//            invoicePossessionCostInfos.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
//            invoicePossessionCostInfoService.save(invoicePossessionCostInfos);
//        }
//        //保存发票供应商信息
//        List<InvoiceSupplierInfo> invoiceSupplierInfos = invoiceBasicInfo.getInvoiceSupplierInfos();
//        if (invoiceSupplierInfos != null && invoiceSupplierInfos.size() > 0) {
//            for (InvoiceSupplierInfo invoiceSupplierInfo : invoiceSupplierInfos) {
//                invoiceSupplierInfo.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
//                invoiceSupplierInfo.setSupplierName(customerService.getById(invoiceSupplierInfo.getSupplierId()).getEnterpriseName());
//            }
//            invoiceSupplierInfoService.saveBatch(invoiceSupplierInfos);
//        }
//        //保存采购发票附件
//        AttachmentDto attachmentDto = AttachmentDto.builder()
//                .setEntityId(invoiceBasicInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE)
//                .build();
//        List<MultipartFile> fileList = sysAttachmentRefService.getMultipartFileFromRequest(request, ConstantUtil.FILE_NAME);
//        sysAttachmentRefService.saveFileAndRef(fileList, attachmentDto);
        // 生成参考的待开发票
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0 && flag) {
            File file = inputData(invoiceBasicInfo);
            AttachmentDto attachmentDtoPendindInvoic = AttachmentDto.builder()
                    .setEntityId(invoiceBasicInfo.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_FILE)
                    .build();
            List<FileStorage> accepyanceFile = new ArrayList<>();
            FileStorage fileStorage = new FileStorage(file.getName(), file.getAbsolutePath(), FileModuleDict.ChildEnum.INVOICE_SALES_FILE);
            accepyanceFile.add(fileStorage);
            sysAttachmentRefService.saveFileAndRefHis(accepyanceFile, attachmentDtoPendindInvoic);
            FileStorageDO fileStorageDO = new FileStorageDO();
            fileStorageDO.setAbsolutePath(fileStorage.getAbsolutePath());
            fileStorageDO.setPath(fileStorage.getPath());
            fileStorageDO.setOriginalName(fileStorage.getOriginalName());
            fileStorageDO.setSize(fileStorage.getSize());
            fileStorageDO.setType(fileStorage.getFileType());
            fileStorageDO.setBusinessType(FileModuleDict.ChildEnum.INVOICE_SALES_FILE.getCode());
            fileStorageDO.setBusinessId(invoiceBasicInfo.getId());
            fileService.save(fileStorageDO);
        }
        return invoiceBasicInfo;
    }

    private File inputData(InvoiceBasicInfo invoiceBasicInfo) throws IOException {
        //创建工作簿
        Workbook workbook = new SXSSFWorkbook();
        //创建表
        Sheet sheet = workbook.createSheet();
        Enterprise enterprise = iEnterpriseService.getById(invoiceBasicInfo.getEnterpriseCustomerInfoId());
        List<InvoiceGoodsInfo> invoiceGoodsInfos = invoiceBasicInfo.getInvoiceGoodsInfos();
        InvoicePossessionCostInfo invoicePossessionCostInfos = invoiceBasicInfo.getInvoicePossessionCostInfos();
        //加价款
        BigDecimal goodsPlusPrice;
        //总开票货物数量
        BigDecimal openQuantitySum = BigDecimal.ZERO;
        for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfos) {
            openQuantitySum = openQuantitySum.add(invoiceGoodsInfo.getOpenQuantity());
        }
        String fileName = FileUtil.getAbsolutePath(invoiceBasicInfo.getTaxIdentifyNumber() + System.currentTimeMillis(), ".xlsx", FileModuleDict.ChildEnum.INVOICE_SALES_FILE);
        File file = new File(fileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        file.deleteOnExit();
        for (int i = 0; i < 14; i++) {
            Row row = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("购方企业名称");
            Cell cell1 = row.createCell(1);
            cell1.setCellValue("购方税号");
            Cell cell2 = row.createCell(2);
            cell2.setCellValue("银行账户");
            Cell cell3 = row.createCell(3);
            cell3.setCellValue("地址电话");
            Cell cell4 = row.createCell(4);
            cell4.setCellValue("备注");
            Cell cell5 = row.createCell(5);
            cell5.setCellValue("商品名称");
            Cell cell6 = row.createCell(6);
            cell6.setCellValue("规格");
            Cell cell7 = row.createCell(7);
            cell7.setCellValue("单位");
            Cell cell8 = row.createCell(8);
            cell8.setCellValue("数量");
            Cell cell9 = row.createCell(9);
            cell9.setCellValue("单价");
            Cell cell10 = row.createCell(10);
            cell10.setCellValue("金额");
            Cell cell11 = row.createCell(11);
            cell11.setCellValue("税率");
            Cell cell12 = row.createCell(12);
            cell12.setCellValue("税额");
            Cell cell13 = row.createCell(13);
            cell13.setCellValue("价税合计");
        }
        for (int i = 0; i < invoiceGoodsInfos.size(); i++) {
            Row row = sheet.createRow(i + 1);
            Cell cell = row.createCell(0);
            cell.setCellValue(enterprise.getCorporateName());
            Cell cell1 = row.createCell(1);
            cell1.setCellValue(invoiceBasicInfo.getTaxIdentifyNumber());
            Cell cell2 = row.createCell(2);
            cell2.setCellValue(invoiceBasicInfo.getAccountBankName() + " " + invoiceBasicInfo.getAccountNumber());
            Cell cell3 = row.createCell(3);
            cell3.setCellValue(invoiceBasicInfo.getAddress() + " " + invoiceBasicInfo.getPhone());
            Cell cell4 = row.createCell(4);
            cell4.setCellValue(invoiceBasicInfo.getRemark());
            Cell cell5 = row.createCell(5);
            cell5.setCellValue(invoiceGoodsInfos.get(i).getGoodsName());
            Cell cell6 = row.createCell(6);
            cell6.setCellValue(invoiceGoodsInfos.get(i).getGoodsType());
            Cell cell7 = row.createCell(7);
            cell7.setCellValue(invoiceGoodsInfos.get(i).getGoodsUnit());
            Cell cell8 = row.createCell(8);
            cell8.setCellValue(invoiceGoodsInfos.get(i).getOpenQuantity().toString());
            Cell cell9 = row.createCell(9);
            Cell cell10 = row.createCell(10);
            //有加价款
            BigDecimal amount;
            if (invoicePossessionCostInfos != null && invoicePossessionCostInfos.getPossessionCostType().equals(1L)) {
                //单价 = 销售单价 + 加价款
                goodsPlusPrice = invoicePossessionCostInfos.getPossessionCost().divide(openQuantitySum, 2, RoundingMode.FLOOR);
                cell9.setCellValue(invoiceGoodsInfos.get(i).getSalesPrice().add(goodsPlusPrice).setScale(2, RoundingMode.FLOOR).toString());
                if (i == invoiceGoodsInfos.size() - 1) {
                    //最后一个货物时货物总价 = 总开票金额 + 剩余加价款
                    BigDecimal subtract = invoicePossessionCostInfos.getPossessionCost().subtract(goodsPlusPrice.multiply(openQuantitySum.subtract(invoiceGoodsInfos.get(i).getOpenQuantity())));
                    amount = invoiceGoodsInfos.get(i).getSalesPrice().multiply(invoiceGoodsInfos.get(i).getOpenQuantity()).add(subtract);
                    cell10.setCellValue(amount.divide(new BigDecimal("1.13"), 2, BigDecimal.ROUND_HALF_UP).toString());
                } else {
                    amount = invoiceGoodsInfos.get(i).getSalesPrice().multiply(invoiceGoodsInfos.get(i).getOpenQuantity()).add(goodsPlusPrice.multiply(invoiceGoodsInfos.get(i).getOpenQuantity()));
                    cell10.setCellValue(amount.divide(new BigDecimal("1.13"), 2, BigDecimal.ROUND_HALF_UP).toString());
                }
                //没有加价款
            } else {
                cell9.setCellValue(invoiceGoodsInfos.get(i).getSalesPrice().setScale(2, RoundingMode.FLOOR).toString());
                amount = invoiceGoodsInfos.get(i).getSalesPrice().multiply(invoiceGoodsInfos.get(i).getOpenQuantity());
                cell10.setCellValue(amount.divide(new BigDecimal("1.13"), 2, BigDecimal.ROUND_HALF_UP).toString());
            }
            Cell cell11 = row.createCell(11);
            cell11.setCellValue(0.13d);
            Cell cell12 = row.createCell(12);
            cell12.setCellValue(new BigDecimal("0.13").multiply(amount).divide(new BigDecimal("1.13"), 2, BigDecimal.ROUND_HALF_UP).toString());
            Cell cell13 = row.createCell(13);
            cell13.setCellValue(amount.setScale(2, RoundingMode.FLOOR).toString());

        }
        FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        workbook.write(fileOutputStream);
        fileOutputStream.close();
        return new File(fileName);
    }

    private void startFlowable(InvoiceBasicInfo invoiceBasicInfo, HttpServletRequest request) {
        User user = userService.getByLoginName("admin");
        ThreadLocalUtil.setUser(user);
        Long oldId = invoiceBasicInfo.getId();
//        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getByBusinessNumber(invoiceBasicInfo.getBusinessNumber());
        //1.新增处理人-- C端用户、业务经理、财务人员
        BusinessAssignee CustmerUser = new BusinessAssignee(invoiceBasicInfo.getId(), ConstantUtil.ASSIGNEE_C_CUSTOMER_USER);
        CustmerUser.setAssigneeId(user.getId());
        CustmerUser.setAssigneeType(ConstantUtil.ASSIGNEE_C_CUSTOMER_USER);
        assigneeService.add(CustmerUser);

        BusinessAssignee projectManager = new BusinessAssignee(invoiceBasicInfo.getId(), ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE);
        List<Long> projectManagers = userService.findUserIdByRole(ConstantUtil.PROJECT_MANAGER);
        projectManager.setCandidateId(StringUtils.join(projectManagers, ","));
        projectManager.setAssigneeType(ConstantUtil.INVOICE);
        assigneeService.add(projectManager);

        // 财务专员
        List<Long> financeStaffLists = userService.findUserIdByRole(ConstantUtil.CASHIER);
        if (financeStaffLists == null || financeStaffLists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.FINANCE_STAFF + "角色内无任何用户！");
        }
        BusinessAssignee financeStaffList = new BusinessAssignee(invoiceBasicInfo.getId(), ConstantUtil.INVOICE);
        financeStaffList.setCandidateId(StringUtils.join(financeStaffLists, ","));
        financeStaffList.setAssigneeType(ConstantUtil.CASHIER);
        assigneeService.add(financeStaffList);

        //2.开启流程实例
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put(ConstantUtil.SALE_INVOICE_CREATE + ConstantUtil.ASSIGNEE,
                assigneeService.getIdByBusiness(invoiceBasicInfo.getId(), ConstantUtil.ASSIGNEE_C_CUSTOMER_USER, ConstantUtil.ASSIGNEE_C_CUSTOMER_USER));
        Map<String, Object> msgVariables = new HashMap<>();
        Enterprise enterprise = iEnterpriseService.getById(invoiceBasicInfo.getEnterpriseCustomerInfoId());
        String queryBusiness = invoiceBasicInfo.getBusinessNumber() + FlowableUtil.splitChar + enterprise.getCorporateName();
        ProcessInstance processInst = flowableService.startProcessInstance(invoiceBasicInfo, procVariables,
                FlowableUtil.generateBusinessKey(invoiceBasicInfo, ConstantUtil.INVOICE, queryBusiness), msgVariables, ConstantUtil.INVOICE);
        if (processInst == null) {
            throw new BusinessException(CodeUtil.FAIL, "销售发票流程启动失败！");
        }
        //3.完成流程第一步提交发票，开启下一步业务审核
        String processInstId = processInst.getId();
        Task task = flowableService.findRuntimeTaskByProcessInstId(processInstId).get(0);
        Map<String, Object> procVariables1 = new HashMap<>();
        procVariables1.put(ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE,
                assigneeService.getCandidateByBusiness(invoiceBasicInfo.getId(), ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE, ConstantUtil.INVOICE));
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName() + "”的发票已进入“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.INVOICE) + "—业务审核阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        Long historyId = addHistorySaleInvoice(invoiceBasicInfo, request);
        invoiceBasicInfo.setId(oldId);
        flowableService.completeMyTask(task.getId(), invoiceBasicInfo, procVariables1, null, historyId, msgVariables, ConstantUtil.INVOICE, projectManagers);
    }

    @Override
    public Long addHistorySaleInvoice(InvoiceBasicInfo oldInvoiceBasicInfo, HttpServletRequest request) {
        //保存销售发票信息的副本
        InvoiceHisInfo invoiceHisInfo = new InvoiceHisInfo();
        BeanUtils.copyProperties(oldInvoiceBasicInfo, invoiceHisInfo, "id");
        invoiceHisInfo.setInvoiceBasicInfoId(oldInvoiceBasicInfo.getId());
        invoiceHisInfoService.save(invoiceHisInfo);
        //保存销售发票的货物信息的副本
        List<InvoiceGoodsInfo> invoiceGoodsInfoList = oldInvoiceBasicInfo.getInvoiceGoodsInfos();
        List goodsList = new ArrayList();
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0) {
            for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfoList) {
                InvoiceHisGoodsInfo invoiceHisGoodsInfo = new InvoiceHisGoodsInfo();
                BeanUtils.copyProperties(invoiceGoodsInfo, invoiceHisGoodsInfo, "id");
                invoiceHisGoodsInfo.setInvoiceHisInfoId(invoiceHisInfo.getId());
                goodsList.add(invoiceHisGoodsInfo);
            }
        }
        invoiceHisGoodsInfoService.saveBatch(goodsList);
        //保存资金占用费历史
        InvoicePossessionCostInfo invoicePossessionCostInfos = oldInvoiceBasicInfo.getInvoicePossessionCostInfos();
        if (invoicePossessionCostInfos != null) {
            InvoiceHisPossessionCostInfo invoiceHisPossessionCostInfo = new InvoiceHisPossessionCostInfo();
            BeanUtils.copyProperties(invoicePossessionCostInfos, invoiceHisPossessionCostInfo, "id");
            invoiceHisPossessionCostInfo.setInvoiceHisInfoId(invoiceHisInfo.getId());
            invoiceHisPossessionCostInfoService.save(invoiceHisPossessionCostInfo);
        }
        //保存发票提供供应商历史
        List<InvoiceSupplierInfo> invoiceSupplierInfos = oldInvoiceBasicInfo.getInvoiceSupplierInfos();
        if (invoiceSupplierInfos != null && invoiceSupplierInfos.size() > 0) {
            List hisSupplier = new ArrayList();
            for (InvoiceSupplierInfo invoiceSupplierInfo : invoiceSupplierInfos) {
                InvoiceHisSupplierInfo invoiceHisSupplierInfo = new InvoiceHisSupplierInfo();
                BeanUtils.copyProperties(invoiceSupplierInfo, invoiceHisSupplierInfo, "id");
                invoiceHisSupplierInfo.setInvoiceHisInfoId(invoiceHisInfo.getId());
                hisSupplier.add(invoiceHisSupplierInfo);
            }
            invoiceHisSupplierInfoService.saveBatch(hisSupplier);
        }
        //List<PurchaseInvoiceInfo> purchaseInvoiceInfos = oldInvoiceBasicInfo.getPurchaseInvoiceInfos();
//        if(purchaseInvoiceInfos != null && purchaseInvoiceInfos.size() > 0){
//            List hisSupplier = new ArrayList();
//            for (PurchaseInvoiceInfo purchaseInvoiceInfo : purchaseInvoiceInfos) {
//                PurchaseInvoiceHisInfo purchaseInvoiceHisInfo = new PurchaseInvoiceHisInfo();
//                BeanUtils.copyProperties(purchaseInvoiceInfo, purchaseInvoiceHisInfo, "id");
//                purchaseInvoiceHisInfo.setInvoiceHisInfoId(invoiceHisInfo.getId());
//                hisSupplier.add(purchaseInvoiceHisInfo);
//            }
//            purchaseInvoiceHisInfoService.saveBatch(hisSupplier);
//        }
        //保存销售发票附件的副本
//        AttachmentDto attachmentDto1 = AttachmentDto.builder()
//                .setEntityId(oldInvoiceBasicInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_FILE)
//                .build();
//        List<FileStorage> files1 = sysAttachmentRefService.getCfiles(attachmentDto1);
//        AttachmentDto attachmentDtoHis1 = AttachmentDto.builder()
//                .setEntityId(invoiceHisInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_HIS_FILE)
//                .build();
//        sysAttachmentRefService.saveFileAndRefHis(files1, attachmentDtoHis1);
        List<Long> purchaseInvoiceFiles = oldInvoiceBasicInfo.getPurchaseInvoiceFiles();
        if(CollectionUtil.isNotEmpty(purchaseInvoiceFiles)){
            List<FileStorage> fileStorageList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(purchaseInvoiceFiles)){
                List<FileStorageDO> fileStorageDOList = fileService.listByIds(purchaseInvoiceFiles);
                for (FileStorageDO fileStorageDO:fileStorageDOList ) {
                    File file = new File(fileStorageDO.getAbsolutePath());
                    FileStorage fileStorage = new FileStorage(file.getName(),fileStorageDO.getOriginalName(),fileStorageDO.getAbsolutePath(),FileModuleDict.ChildEnum.INVOICE_PURCHASE_HIS_FILE);
                    fileStorageList.add(fileStorage);
                }
            }
            AttachmentDto attachmentDtoHis = AttachmentDto.builder()
                    .setEntityId(invoiceHisInfo.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_HIS_FILE)
                    .build();
            sysAttachmentRefService.saveFileAndRefHis(fileStorageList, attachmentDtoHis);
        }
        //保存开票明细历史
        List<Long> invoiceDetailFiles = oldInvoiceBasicInfo.getInvoiceDetailFiles();
        if(CollectionUtil.isNotEmpty(invoiceDetailFiles)){
            List<FileStorage> fileStorageList = new ArrayList<>();
            if(CollectionUtil.isNotEmpty(invoiceDetailFiles)){
                List<FileStorageDO> fileStorageDOList = fileService.listByIds(invoiceDetailFiles);
                for (FileStorageDO fileStorageDO:fileStorageDOList ) {
                    File file = new File(fileStorageDO.getAbsolutePath());
                    FileStorage fileStorage = new FileStorage(file.getName(),fileStorageDO.getOriginalName(),fileStorageDO.getAbsolutePath(),FileModuleDict.ChildEnum.INVOICE_DETAIL_HIS_FILE);
                    fileStorageList.add(fileStorage);
                }
            }
            AttachmentDto attachmentDtoHis = AttachmentDto.builder()
                .setEntityId(invoiceHisInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_DETAIL_HIS_FILE)
                .build();
            sysAttachmentRefService.saveFileAndRefHis(fileStorageList, attachmentDtoHis);
        }

        return invoiceHisInfo.getId();
    }

    @Override
    public void c_doUpdate(InvoiceBasicInfo invoiceBasicInfo, String taskId, HttpServletRequest request) throws IOException {
        User user = userService.getByLoginName("admin");
        ThreadLocalUtil.setUser(user);
        // 财务专员
        List<Long> financeStaffLists = userService.findUserIdByRole(ConstantUtil.CASHIER);
        if (financeStaffLists == null || financeStaffLists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.FINANCE_STAFF + "角色内无任何用户！");
        }
        //1.新增处理人-- C端用户、业务经理、财务人员
        Long oldId = invoiceBasicInfo.getId();
        invoiceBasicInfo = updateSaleInvoice(invoiceBasicInfo, request);
        //保存历史记录供getView方法使用
        Long historyId = addHistorySaleInvoice(invoiceBasicInfo, request);
        Enterprise enterprise = iEnterpriseService.getById(invoiceBasicInfo.getEnterpriseCustomerInfoId());
        //完成修改后，流程转到下一流程财务审核
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName() + "”的发票已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.INVOICE) + "—财务审核阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        invoiceBasicInfo.setId(oldId);
//        flowableService.completeMyTask(taskId, invoiceBasicInfo, null, null, historyId, msgVariables, ConstantUtil.INVOICE, financeStaffLists);
        Map<String, Object> procVariables = new HashMap<>();
        List<Long> projectManagers = userService.findUserIdByRole(ConstantUtil.PROJECT_MANAGER);

        procVariables.put(ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE,
                assigneeService.getCandidateByBusiness(invoiceBasicInfo.getId(), ConstantUtil.SALE_INVOICE_APPROVAL_CANDIDATE, ConstantUtil.INVOICE));
//        flowableService.completeMyTaskCustomer(taskId, invoiceBasicInfo, procVariables, null, historyId, msgVariables, ConstantUtil.BILL_UNIT_PRICE_ADJUST, userDO.getId());
        flowableService.completeMyTask(taskId, invoiceBasicInfo, procVariables, null, historyId, msgVariables, ConstantUtil.INVOICE, projectManagers);
    }

    @Override
    public InvoiceHisInfo getDetail(Long businessKey) {
        //销售发票信息
        InvoiceHisInfo invoiceHisInfo = invoiceHisInfoService.getById(businessKey);
        PurchContractCompletedVo purchContractCompletedVo = purchContractService.getCompletedPurchContractByBusinessNumber(invoiceHisInfo.getBusinessNumber());
        invoiceHisInfo.setPurchContractCompletedVo(purchContractCompletedVo);
        //字典项
        invoiceHisInfo.setAmountKindDic(dictService.getByCode(invoiceHisInfo.getAmountKind()));
        invoiceHisInfo.setInvoiceTypeDic(dictService.getByCode(invoiceHisInfo.getInvoiceType()));
        //核心企业
        Enterprise enterprise = iEnterpriseService.getById(invoiceHisInfo.getEnterpriseCustomerInfoId());
        invoiceHisInfo.setEnterpriseCorporateName(enterprise.getCorporateName());
        invoiceHisInfo.setCompanyName(enterprise.getCorporateName());
        //业务信息 TODO
//        invoiceHisInfo.setBusinessBasicInfo(businessBasicInfo);
        //发票货物信息
        List<InvoiceHisGoodsInfo> invoiceHisGoodsInfos = invoiceHisGoodsInfoService.list(new QueryWrapper<InvoiceHisGoodsInfo>().eq("invoice_his_info_id", invoiceHisInfo.getId()));
        invoiceHisInfo.setInvoiceGoodsInfos(invoiceHisGoodsInfos);
        //资金占用费信息
        InvoiceHisPossessionCostInfo invoiceHisPossessionCostInfo = invoiceHisPossessionCostInfoService.getOne(new QueryWrapper<InvoiceHisPossessionCostInfo>().eq("invoice_his_info_id", invoiceHisInfo.getId()));
        invoiceHisInfo.setInvoicePossessionCostInfos(invoiceHisPossessionCostInfo);
        //供应商信息
        List<InvoiceHisSupplierInfo> invoiceHisSupplierInfos = invoiceHisSupplierInfoService.list(new QueryWrapper<InvoiceHisSupplierInfo>().eq("invoice_his_info_id", invoiceHisInfo.getId()));
        invoiceHisInfo.setInvoiceSupplierInfos(invoiceHisSupplierInfos);
        //发票附件信息
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(invoiceHisInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_HIS_FILE)
                .build();
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        invoiceHisInfo.setFiles(files);

        //开票明细附件
        AttachmentDto attachmentDto2 = AttachmentDto.builder()
            .setEntityId(invoiceHisInfo.getId())
            .setChildEnum(FileModuleDict.ChildEnum.INVOICE_DETAIL_HIS_FILE)
            .build();
        List<FileStorage> files2 = sysAttachmentRefService.getFiles(attachmentDto2);
        invoiceHisInfo.setInvoiceDetailList(files2);

        //采购发票信息
        List<PurchaseInvoiceHisInfo> purchaseInvoiceInfos = purchaseInvoiceHisInfoService.list(new QueryWrapper<PurchaseInvoiceHisInfo>().eq("invoice_his_info_id", invoiceHisInfo.getId()));
        invoiceHisInfo.setPurchaseInvoiceHisInfos(purchaseInvoiceInfos);
        return invoiceHisInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doUpdate(InvoiceBasicInfo invoiceBasicInfo, String taskId, HttpServletRequest request) throws IOException {
        // 财务专员
        List<Long> financeStaffLists = userService.findUserIdByRole(ConstantUtil.CASHIER);
        if (financeStaffLists == null || financeStaffLists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.FINANCE_STAFF + "角色内无任何用户！");
        }
        Long oldId = invoiceBasicInfo.getId();
        invoiceBasicInfo = updateSaleInvoice(invoiceBasicInfo, request);
        //保存历史记录供getView方法使用
        Long historyId = addHistorySaleInvoice(invoiceBasicInfo, request);
        Enterprise enterprise = iEnterpriseService.getById(invoiceBasicInfo.getEnterpriseCustomerInfoId());
        //完成修改后，流程转到下一流程财务审核
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为：" + invoiceBasicInfo.getBusinessNumber() + "核心企业为：" + enterprise.getCorporateName() + "”的发票已inOut“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.INVOICE) + "—财务审核阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        invoiceBasicInfo.setId(oldId);
        flowableService.completeMyTask(taskId, invoiceBasicInfo, null, null, historyId, msgVariables, ConstantUtil.INVOICE, financeStaffLists);

    }

    private InvoiceBasicInfo updateSaleInvoice(InvoiceBasicInfo invoiceBasicInfo, HttpServletRequest request) throws IOException {
        //修改销售发票信息
        //修改销售状态置为：已创建
//        invoiceBasicInfo.setInvoiceStatus(dictService.getByCode(InvoiceDict.ChildEnum.CREATE.getCode()).getId());
//        updateById(invoiceBasicInfo);
//        //修改销售发票的货物信息  先删除，再修改
//        invoiceGoodsInfoService.remove(new QueryWrapper<InvoiceGoodsInfo>().eq("invoice_basic_info_id", invoiceBasicInfo.getId()));
        Boolean flag = false;
        List<InvoiceGoodsInfo> invoiceGoodsInfoList = invoiceBasicInfo.getInvoiceGoodsInfos();
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0) {
            for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfoList) {
                if (invoiceGoodsInfo.getGoodsQuantity() != null) {
                    flag = true;
                }
                //如果是货物判断开票数量
//                if (invoiceBasicInfo.getAmountKind().equals(AmountKindDict.ChildEnum.PAYMENT.getCode())) {
//                    if (-1 == invoiceGoodsInfo.getGoodsQuantity().compareTo(invoiceGoodsInfo.getUsedNum().add(invoiceGoodsInfo.getOpenQuantity()))) {
//                        throw new ValidatorException(CodeUtil.FAIL, "开票数量 + 已开数量 不能大于 数量，请修改 “开票数量”");
//                    }
//                }
//                invoiceGoodsInfo.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
            }
//            invoiceGoodsInfoService.saveBatch(invoiceGoodsInfoList);
        }
//        //保存资金占用费 先删除，再修改
//        invoicePossessionCostInfoService.remove(new QueryWrapper<InvoicePossessionCostInfo>().eq("invoice_basic_info_id", invoiceBasicInfo.getId()));
//        InvoicePossessionCostInfo invoicePossessionCostInfos = invoiceBasicInfo.getInvoicePossessionCostInfos();
//        if (invoicePossessionCostInfos != null) {
//            invoicePossessionCostInfos.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
//            invoicePossessionCostInfoService.save(invoicePossessionCostInfos);
//        }
//        //保存发票供应商信息 先删除，再修改
//        invoiceSupplierInfoService.remove(new QueryWrapper<InvoiceSupplierInfo>().eq("invoice_basic_info_id", invoiceBasicInfo.getId()));
//        List<InvoiceSupplierInfo> invoiceSupplierInfos = invoiceBasicInfo.getInvoiceSupplierInfos();
//        if (invoiceSupplierInfos != null && invoiceSupplierInfos.size() > 0) {
//            for (InvoiceSupplierInfo invoiceSupplierInfo : invoiceSupplierInfos) {
//                invoiceSupplierInfo.setInvoiceBasicInfoId(invoiceBasicInfo.getId());
//                invoiceSupplierInfo.setSupplierName(customerService.getById(invoiceSupplierInfo.getSupplierId()).getEnterpriseName());
//            }
//            invoiceSupplierInfoService.saveBatch(invoiceSupplierInfos);
//        }
//        //先删除所有需要删除的文件
//        List<Long> deleteFileIds = invoiceBasicInfo.getDeleteIds();
//        if (deleteFileIds != null && deleteFileIds.size() > 0) {
//            sysAttachmentRefService.removeFilestorageAndRef(deleteFileIds);
//        }
//        //保存采购发票附件
//        AttachmentDto attachmentDto = AttachmentDto.builder()
//                .setEntityId(invoiceBasicInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE)
//                .build();
//        List<MultipartFile> fileList = sysAttachmentRefService.getMultipartFileFromRequest(request, ConstantUtil.FILE_NAME);
//        if (!fileList.isEmpty()) {
//            sysAttachmentRefService.saveFileAndRef(fileList, attachmentDto);
//        }
        //先删除旧的
        AttachmentDto attachmentDtoPendindInvoic = AttachmentDto.builder()
                .setEntityId(invoiceBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_FILE)
                .build();
        sysAttachmentRefService.removeFilestorageAndRef(attachmentDtoPendindInvoic);
        //先删除C端旧的
        List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(invoiceBasicInfo.getId(), FileModuleDict.ChildEnum.INVOICE_SALES_FILE.getCode());
        for (FileStorageDO fileStorageDO:fileStorageDOS) {
            fileService.updateBusinessId(fileStorageDO.getId(),null);
        }
        if (invoiceGoodsInfoList != null && invoiceGoodsInfoList.size() > 0 && flag) {
            File file = inputData(invoiceBasicInfo);
            List<FileStorage> accepyanceFile = new ArrayList<>();
            FileStorage fileStorage = new FileStorage(file.getName(), file.getAbsolutePath(), FileModuleDict.ChildEnum.INVOICE_SALES_FILE);
            accepyanceFile.add(fileStorage);
            sysAttachmentRefService.saveFileAndRefHis(accepyanceFile, attachmentDtoPendindInvoic);
            FileStorageDO fileStorageDO = new FileStorageDO();
            fileStorageDO.setAbsolutePath(fileStorage.getAbsolutePath());
            fileStorageDO.setFilePath(fileStorage.getPath());
            fileStorageDO.setOriginalName(fileStorage.getOriginalName());
            fileStorageDO.setSize(fileStorage.getSize());
            fileStorageDO.setBusinessType(FileModuleDict.ChildEnum.INVOICE_SALES_FILE.getCode());
            fileStorageDO.setBusinessId(invoiceBasicInfo.getId());
            fileService.save(fileStorageDO);
        }
        return invoiceBasicInfo;
    }


    @Override
    public GridPage saleSelectGoodsOfPayment(SearchGoodsVo searchGoodsVo) {
        Page<SearchGoodsVo> page = PageHelper.startPage(searchGoodsVo.getPage(), searchGoodsVo.getRows());
        //获取符合条件结算单
        List<SettlementBasicInfo> settlementBasicInfos = baseMapper.saleSelectSettlementOfPayment(searchGoodsVo);
        //获取符合条件的货物
        List<InvoiceGoodsInfo> invoiceGoodsInfoList = baseMapper.saleSelectSettlementOfPaymentGoods(searchGoodsVo.getBusinessNumber());
        //将货物放入对应的结算单
        for (SettlementBasicInfo settlementBasicInfo : settlementBasicInfos) {
            settlementBasicInfo.setSupplier(customerService.getById(settlementBasicInfo.getSupplierId()));
            List<InvoiceGoodsInfo> invoiceGoodsInfos = new ArrayList<>();
            for (InvoiceGoodsInfo invoiceGoodsInfo : invoiceGoodsInfoList) {
                //前端显示用  预填充开票数量
                invoiceGoodsInfo.setOpenQuantity(invoiceGoodsInfo.getGoodsQuantity().subtract(invoiceGoodsInfo.getUsedNum()));
                if (invoiceGoodsInfo.getSettlementBasicInfoId().equals(settlementBasicInfo.getId())) {
                    invoiceGoodsInfos.add(invoiceGoodsInfo);
                }
            }
            settlementBasicInfo.setInvoiceGoodsInfos(invoiceGoodsInfos);
        }
        return new GridPage<>(searchGoodsVo.getRows(), searchGoodsVo.getPage(), page.getTotal(), settlementBasicInfos);
    }

    @Override
    public GridPage<SettlementGoodsInfo> saleSelectGoodsOfDiscount(SearchGoodsVo searchGoodsVo) {
        Page<SearchGoodsVo> page = PageHelper.startPage(searchGoodsVo.getPage(), searchGoodsVo.getRows());
        List<SettlementGoodsInfo> settlementGoodsInfoList = baseMapper.saleSelectGoodsOfDiscount(searchGoodsVo.getBusinessNumber());
        return new GridPage<>(searchGoodsVo.getRows(), searchGoodsVo.getPage(), page.getTotal(), settlementGoodsInfoList);
    }

    @Override
    public InvoiceBasicInfo getUpdateDetail(Long businessKey) {
        //销售发票信息
        InvoiceBasicInfo invoiceBasicInfo = getById(businessKey);
        //贸易平台
        invoiceBasicInfo.setTradingPlatformName(platformService.getById(invoiceBasicInfo.getTradingPlatformId()).getPlatformName());
        //字典项
        invoiceBasicInfo.setAmountKindDic(dictService.getByCode(invoiceBasicInfo.getAmountKind()));
        //销售发票货物信息
        List<InvoiceGoodsInfo> invoiceGoodInfos = invoiceGoodsInfoService.findListGoods(invoiceBasicInfo.getId());
        invoiceBasicInfo.setInvoiceGoodsInfos(invoiceGoodInfos);
        //资金占用费
        InvoicePossessionCostInfo invoicePossessionCostInfos = invoicePossessionCostInfoService.getOne(new QueryWrapper<InvoicePossessionCostInfo>().eq("invoice_basic_info_id", invoiceBasicInfo.getId()));
        invoiceBasicInfo.setInvoicePossessionCostInfos(invoicePossessionCostInfos);
        //发票供应商信息
        List<InvoiceSupplierInfo> invoiceSupplierInfosuppliers = invoiceSupplierInfoService.list(new QueryWrapper<InvoiceSupplierInfo>().eq("invoice_basic_info_id", invoiceBasicInfo.getId()));
        invoiceBasicInfo.setInvoiceSupplierInfos(invoiceSupplierInfosuppliers);
        //采购发票附件
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(invoiceBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE)
                .build();
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        invoiceBasicInfo.setFiles(files);

        //开票详细附件
        AttachmentDto attachmentDto2 = AttachmentDto.builder()
            .setEntityId(invoiceBasicInfo.getId())
            .setChildEnum(FileModuleDict.ChildEnum.INVOICE_DETAIL_FILE)
            .build();
        List<FileStorage> files2 = sysAttachmentRefService.getFiles(attachmentDto2);
        invoiceBasicInfo.setInvoiceDetailList(files2);

        //参考的待开发票
        AttachmentDto attachmentDtoPendindInvoic = AttachmentDto.builder()
                .setEntityId(invoiceBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_SALES_FILE)
                .build();
        List<FileStorage> pendingFiles = sysAttachmentRefService.getFiles(attachmentDtoPendindInvoic);
        invoiceBasicInfo.setPendingInvoice(pendingFiles);
        BusinessBasicInfo byBusinessNumber = businessBasicInfoService.getByBusinessNumber(invoiceBasicInfo.getBusinessNumber());
        Customer customer = customerService.getById(invoiceBasicInfo.getEnterpriseCustomerInfoId());
        invoiceBasicInfo.setBusinessName(byBusinessNumber.getName());
        invoiceBasicInfo.setCustomerName(customer.getEnterpriseName());
        return invoiceBasicInfo;
    }

    @Override
    public void init(Long businessBasicId, Model model) {
        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getById(businessBasicId);
        //采购合同
        List<PurchContractManagement> purchContractManagements = purchContractService.list(
                new QueryWrapper<PurchContractManagement>()
                        .eq("business_number", businessBasicInfo.getBusinessNumber()));
        List purchContractFiles = new ArrayList<>();
        for (PurchContractManagement purchContractManagement : purchContractManagements) {
            PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getOne(
                    new QueryWrapper<PurchContractBasicInfo>().eq("purch_contract_management_id", purchContractManagement.getId()).orderByDesc("gmt_create").last("LIMIT 1"));
            if (purchContractBasicInfo != null) {
                //采购合同文件
                List<FileStorage> contractFileStorage = fileStorageService.findByBelongIdAndBelongType(purchContractBasicInfo.getContractNumber(), FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE.getCode());
                //采购合同文件线上出证
                List<FileStorage> reportFileStorage = fileStorageService.findByBelongIdAndBelongType(purchContractBasicInfo.getContractNumber(), FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_FILE.getCode());
                if (!contractFileStorage.isEmpty()) {
                    for (FileStorage fileStorage : contractFileStorage) {
                        purchContractFiles.add(fileStorage);
                    }
                }
                if (!reportFileStorage.isEmpty()) {
                    for (FileStorage fileStorage : reportFileStorage) {
                        purchContractFiles.add(fileStorage);
                    }
                }
            }

        }
        model.addAttribute("purchContractFiles", purchContractFiles);
        //销售合同
        List salesContractFiles = new ArrayList();
        CSalesContract salesContractManagement = salesContractService.getOne(
                new QueryWrapper<CSalesContract>()
                        .eq("business_number", businessBasicInfo.getBusinessNumber())
                        .last("LIMIT 1"));
        CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.getOne(
                new QueryWrapper<CSalesContractBasicInfo>().eq("c_sales_contract_management_id", salesContractManagement.getId())
                        .orderByDesc("gmt_create").last("LIMIT 1"));
//        List<SalesContractFileRef> salesContractFileRefs = salesContractFileRefService.list(
//                new QueryWrapper<SalesContractFileRef>().eq("sales_contract_basic_info_id", salesContractBasicInfo.getId()));
//        if (!salesContractFileRefs.isEmpty()) {
//            for (SalesContractFileRef salesContractFileRef : salesContractFileRefs) {
//                FileStorage fileStorage = fileStorageService.get(salesContractFileRef.getFileStorageId());
//                salesContractFiles.add(fileStorage);
//            }
//        }
        //供应商信息
        Map map = new HashMap<>();
        map.put("businessNumber", businessBasicInfo.getBusinessNumber());
        Long status = dictService.getByCode(SettlementDict.ChildEnum.SIGN.getCode()).getId();
        map.put("status", status);
        List<BusinessSupplierInfo> suppliers = new ArrayList<>();


        model.addAttribute("suppliers", suppliers);
        model.addAttribute("salesContractFiles", salesContractFiles);
    }

    @Override
    public InvoiceCustomerInfo findByCustomer(Long customerId, Long businessBasicInfoId) {

        InvoiceCustomerInfo invoiceCustomerInfo = invoiceCustomerInfoService.getOne(new QueryWrapper<InvoiceCustomerInfo>()
                .eq("customer_id", customerId).eq("business_basic_info_id", businessBasicInfoId));
        if (invoiceCustomerInfo == null) {
            invoiceCustomerInfo = invoiceCustomerInfoService.getOne(new QueryWrapper<InvoiceCustomerInfo>()
                    .eq("customer_id", customerId)
                    .last("and business_basic_info_id is null"));
        }
        if (invoiceCustomerInfo == null) {
            Customer customer = customerService.getById(customerId);
            if (customer != null) {
                invoiceCustomerInfo = new InvoiceCustomerInfo(customer);
            }
        }

        return invoiceCustomerInfo;
    }

    @Override
    public void downloadAllInvoiceFile(Long id, HttpServletResponse response) {
        List<FileStorage> allInvoiceFiles = new ArrayList<>();
        InvoiceApproval invoiceApproval = invoiceApprovalService.getFileList(id);
        //待开发票
        allInvoiceFiles.addAll(invoiceApproval.getPendingInvoice());
        //下游结算单附件
        allInvoiceFiles.addAll(invoiceApproval.getSettlementFile());
        //上游结算单附件
        allInvoiceFiles.addAll(invoiceApproval.getSettlementUpstreamSignedFile());
        //采购合同附件
        allInvoiceFiles.addAll(invoiceApproval.getPurchContract());
        //销售合同附件
        allInvoiceFiles.addAll(invoiceApproval.getSalesContract());

        //采购发票附件
        List<FileStorage> invoicePurchaseFiles = sysAttachmentRefService.getCfiles(AttachmentDto.builder()
                .setChildEnum(FileModuleDict.ChildEnum.INVOICE_PURCHASE_FILE).setEntityId(id).build());
        allInvoiceFiles.addAll(invoicePurchaseFiles);
        //发票明细附件
        List<FileStorage> invoiceDetailFiles = sysAttachmentRefService.getCfiles(AttachmentDto.builder()
            .setChildEnum(FileModuleDict.ChildEnum.INVOICE_DETAIL_FILE).setEntityId(id).build());
        allInvoiceFiles.addAll(invoiceDetailFiles);

        fileStorageService.renameFileStorageList(allInvoiceFiles);
        fileStorageService.downloadZipFile(allInvoiceFiles, FileModuleDict.ChildEnum.INVOICE_ZIP_FILE.getCname(),
                FileModuleDict.ChildEnum.INVOICE_ZIP_FILE, response);
    }

    //填充是否展示下载文件按钮
    private void autoButtonFlag(BusinessProcessingTaskVo processingTaskVo) {
        if (processingTaskVo != null) {
            Dictionary approvalDict = dictService.getByCode(InvoiceDict.ChildEnum.PASS.getCode());
            processingTaskVo.setDownloadFileFlag(false);
            if (approvalDict.getId().equals(processingTaskVo.getStatus().getId())) {
                processingTaskVo.setDownloadFileFlag(true);
            }
        }

    }
}
