package com.inkasso.factoring.settlement.service.Impl;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.BorderStyle;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.inkasso.adapter.bean.AbstractUser;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.adapter.util.CollectionUtil;
import com.inkasso.adapter.util.ValidatorUtil;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceBasicInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceSignConfirmationGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceBasicInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceGoodsInfoService;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceSignConfirmationGoodsInfoService;
import com.inkasso.factoring.common.constant.ConstantUtil;
import com.inkasso.factoring.common.dict.impl.FileModuleDict;
import com.inkasso.factoring.common.dict.impl.SettlementDict;
import com.inkasso.factoring.common.entity.BusinessHistoricDetailVo;
import com.inkasso.factoring.common.entity.BusinessProcessingLogVo;
import com.inkasso.factoring.common.entity.GridPage;
import com.inkasso.factoring.common.entity.ValidatorEntity;
import com.inkasso.factoring.common.enums.ProjectInitiationStatusEnum;
import com.inkasso.factoring.common.enums.SalesContractPersonTypeEnum;
import com.inkasso.factoring.common.service.SerialNumberGenerator;
import com.inkasso.factoring.common.util.DateUtil;
import com.inkasso.factoring.common.util.ElectronicSignatureUtil;
import com.inkasso.factoring.common.util.PoitlToDocx;
import com.inkasso.factoring.common.util.excel.ExcelLogs;
import com.inkasso.factoring.common.util.excel.ExcelUtil;
import com.inkasso.factoring.common.util.onlineConverter.OfficeConverterUtil;
import com.inkasso.factoring.creditmanagement.entity.Enterprise;
import com.inkasso.factoring.creditmanagement.entity.SupplierInfo;
import com.inkasso.factoring.creditmanagement.service.IEnterpriseService;
import com.inkasso.factoring.creditmanagement.service.ISupplierInfoService;
import com.inkasso.factoring.dict.entity.Dictionary;
import com.inkasso.factoring.dict.service.DictionaryService;
import com.inkasso.factoring.electronicSignature.entity.FddSignData;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.file.util.FileStorageUtil;
import com.inkasso.factoring.invoicemanage.entity.InvoiceGoodsInfo;
import com.inkasso.factoring.invoicemanage.service.InvoiceGoodsInfoService;
import com.inkasso.factoring.purchManagement.entity.*;
import com.inkasso.factoring.purchManagement.service.*;
import com.inkasso.factoring.salesManagement.entity.CSalesContractBasicInfo;
import com.inkasso.factoring.salesManagement.entity.CSalesContractManagement;
import com.inkasso.factoring.salesManagement.entity.CSalesContractPersonInfo;
import com.inkasso.factoring.salesManagement.service.ICSalesContractBasicInfoService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractManagementService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractPersonInfoService;
import com.inkasso.factoring.settlement.dao.SettlementBasicInfoMapper;
import com.inkasso.factoring.settlement.entity.*;
import com.inkasso.factoring.settlement.model.dto.BusinessProcessingTaskDTO;
import com.inkasso.factoring.settlement.model.request.BillSignRequest;
import com.inkasso.factoring.settlement.service.*;
import com.inkasso.factoring.system.user.model.dto.UserDTO;
import com.inkasso.factoring.tradingPlatform.entity.Platform;
import com.inkasso.factoring.tradingPlatform.service.ITradingPlatformService;
import jodd.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SettlementManagementServiceImpl extends ServiceImpl<SettlementBasicInfoMapper, SettlementBasicInfo> implements SettlementManagementService {

    @Autowired
    private DictionaryService dictService;
    @Autowired
    private SerialNumberGenerator serialNumberGenerator;
    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;
    @Autowired
    private SettlementElectronicInfoService settlementElectronicInfoService;
    @Autowired
    private SettlementRepaymentPlanService settlementRepaymentPlanService;
    @Autowired
    private SettlementGoodsInfoService settlementGoodsInfoService;
    @Autowired
    private ICPurchContractBuyerSellerService icPurchContractBuyerSellerService;
    @Autowired
    private IPurchContractNeedUserRelService iPurchContractNeedUserRelService;
    @Autowired
    private PurchContractApprovalService purchContractApprovalService;
    @Autowired
    private ICPurchContractManagementService icPurchContractManagementService;
    @Autowired
    private ICPurchContractBasicInfoService icPurchContractBasicInfoService;
    @Autowired
    private ICPurchContractPriceRuleService purchContractPriceRuleService;
    @Autowired
    private ISupplierInfoService iSupplierInfoService;
    @Autowired
    private IEnterpriseService iEnterpriseService;
    @Autowired
    private ICAcceptanceBasicInfoService icAcceptanceBasicInfoService;

    @Autowired
    private ICAcceptanceSignConfirmationGoodsInfoService icAcceptanceSignConfirmationGoodsInfoService;
    @Autowired
    private ICSalesContractBasicInfoService icSalesContractBasicInfoService;
    @Autowired
    private ICSalesContractManagementService icSalesContractManagementService;
    @Autowired
    private ICSalesContractPersonInfoService icSalesContractPersonInfoService;

    @Autowired
    private ICAcceptanceGoodsInfoService icAcceptanceGoodsInfoService;
    @Autowired
    private ICPurchContractElectronicInfoService icPurchContractElectronicInfoService;
    @Autowired
    private ITradingPlatformService platformService;
    @Autowired
    private GoodsCalculateService goodsCalculateService;
    @Autowired
    private FileService fileService;
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private InvoiceGoodsInfoService invoiceGoodsInfoService;
    @Value("${trade.billUnitPriceAdjust}")
    private String billUnitPriceAdjust;
    @Value("${trade.addBillBasicInformation}")
    private String addBillBasicInformation;
    @Value("${trade.updateBillBasicInformation}")
    private String updateBillBasicInformation;
    @Value("${trade.getExpectedSettlementDate}")
    private String getExpectedSettlementDate;
    @Value("${trade.finalStatementsign}")
    private String finalStatementsign;
    @Value("${trade.billAutoSign}")
    private String billAutoSign;
    @Value("${trade.getAcceptanceGoods}")
    private String getAcceptanceGoods;
    @Value("${trade.calculation}")
    private String calculation;
    @Value("${trade.downloadPdf}")
    private String downloadPdf;
    @Value("${trade.doBusinessHistoryView}")
    private String doBusinessHistoryView;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SettlementBasicInfo settlementBasicInfo, HttpServletRequest request) throws Exception {
        //保存结算单相关信息
        SettlementBasicInfo saveSettlementBasicInfo = addSettlement(settlementBasicInfo, request);
        //调用B端 新增结算单
        if (settlementBasicInfo.getSubmit()) {
            ResponseEntity<String> response = restTemplate.postForEntity(addBillBasicInformation,
                    saveSettlementBasicInfo, String.class);
            if (response.getStatusCode().value() != HttpStatus.OK.value()) {
                throw new BusinessException(CodeUtil.FAIL, "结算单新增异常！");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SettlementBasicInfo getDetail(Long businessKey) {
        SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(businessKey);
        //回款计划
        settlementBasicInfo.setSettlementRepaymentPlans(settlementRepaymentPlanService.list(
                new QueryWrapper<SettlementRepaymentPlan>().eq("c_settlement_basic_info_id", settlementBasicInfo.getId()))
        );
        //结算单相关货物信息
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementGoodsInfoService.list(
                new QueryWrapper<SettlementGoodsInfo>().eq("c_settlement_basic_info_id", settlementBasicInfo.getId()));
        if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                CAcceptanceBasicInfo acceptanceBasicInfo = icAcceptanceBasicInfoService.getById(settlementGoodsInfo.getcAcceptanceBasicInfoId());
                CAcceptanceGoodsInfo acceptanceGoodsInfo = icAcceptanceGoodsInfoService.getById(settlementGoodsInfo.getAcceptanceGoodsInfoId());
                settlementGoodsInfo.setAcceptanceNumber(acceptanceBasicInfo.getAcceptanceNumber());
                settlementGoodsInfo.setAcceptanceDate(acceptanceGoodsInfo.getAcceptanceDate());
                settlementGoodsInfo.setGoodsName(acceptanceGoodsInfo.getGoodsName());
                settlementGoodsInfo.setGoodsFactory(acceptanceGoodsInfo.getGoodsFactory());
                settlementGoodsInfo.setGoodsType(acceptanceGoodsInfo.getGoodsType());
                settlementGoodsInfo.setGoodsUnit(acceptanceGoodsInfo.getGoodsUnit());
//                settlementGoodsInfo.setGoodsQuantity(acceptanceGoodsInfo.getGoodsQuantity());
            }
        }
        settlementBasicInfo.setSettlementGoodsInfos(settlementGoodsInfos);
        //下游结算清单附件
        List<FileStorageDO> files = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_FILE.getCode());
        settlementBasicInfo.setFiles(files);
        //再新增结算单说明附件
        List<FileStorageDO> additionalFiles = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_SUPPLEMENT_FILE.getCode());
        settlementBasicInfo.setAdditionalFiles(additionalFiles);
        //再新增结算单网价附件
        List<FileStorageDO> netPriceFiles = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_NET_PRICE_FILE.getCode());
        settlementBasicInfo.setNetPriceFiles(netPriceFiles);
        return settlementBasicInfo;
    }

    @Override
    public List<SettlementGoodsInfo> getGoodsInfoList(Long settlementBasicInfoId) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //结算单相关货物信息
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementGoodsInfoService.list(
                new QueryWrapper<SettlementGoodsInfo>().eq("c_settlement_basic_info_id", settlementBasicInfoId));
        if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                CAcceptanceBasicInfo acceptanceBasicInfo = icAcceptanceBasicInfoService.getById(settlementGoodsInfo.getcAcceptanceBasicInfoId());
                CAcceptanceSignConfirmationGoodsInfo acceptanceGoodsInfo = icAcceptanceSignConfirmationGoodsInfoService.getById(settlementGoodsInfo.getAcceptanceGoodsInfoId());
                settlementGoodsInfo.setAcceptanceNumber(acceptanceBasicInfo.getAcceptanceNumber());
                Date acceptanceDate = acceptanceGoodsInfo.getAcceptanceDate();
                settlementGoodsInfo.setAcceptanceDate(acceptanceDate);

                settlementGoodsInfo.setGoodsName(acceptanceGoodsInfo.getGoodsName());
                settlementGoodsInfo.setGoodsFactory(acceptanceGoodsInfo.getGoodsFactory());
                settlementGoodsInfo.setGoodsType(acceptanceGoodsInfo.getGoodsType());
                settlementGoodsInfo.setGoodsUnit(acceptanceGoodsInfo.getGoodsUnit());
                settlementGoodsInfo.setGoodsQuantity(acceptanceGoodsInfo.getGoodsQuantity());
            }
        }
        return settlementGoodsInfos;
    }


    @Override
    public List<SettlementGoodsInfo> findGoodsInfoList(String businessNumber) {
        List<SettlementBasicInfo> settlementBasicInfos = settlementBasicInfoService.findByBusinessNumber(businessNumber);
        if (CollectionUtil.isNotEmpty(settlementBasicInfos)) {
            List<Long> collect = settlementBasicInfos.stream().map(SettlementBasicInfo::getId).collect(Collectors.toList());
            //结算单相关货物信息
            List<SettlementGoodsInfo> settlementGoodsInfos = settlementGoodsInfoService.list(
                    new QueryWrapper<SettlementGoodsInfo>().in("c_settlement_basic_info_id", collect));
            return settlementGoodsInfos;
        }
        return null;
    }

    @Override
    public Object billSign(BillSignRequest billSignRequest) {
        SettlementElectronicInfo settlementElectronicInfo = settlementElectronicInfoService.getById(billSignRequest.getElectronicInfoId());
        settlementElectronicInfo.setSignComment(billSignRequest.getSignComment());
        settlementElectronicInfo.setSignConclusion(billSignRequest.getSignConclusion());
        //获取最新签署信息，更新签署状态
        settlementElectronicInfoService.updateById(settlementElectronicInfo);
        JSONObject json = new JSONObject();
        json.put("electronicInfoId", billSignRequest.getElectronicInfoId());
        json.put("taskId", billSignRequest.getTaskId());
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);
        ResponseEntity<String> response = restTemplate.postForEntity(finalStatementsign,
                json, String.class);
        if (response.getStatusCode().value() != HttpStatus.OK.value()) {
            throw new BusinessException(CodeUtil.FAIL, "流程处理失败，请联系管理员！");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object getCanBeBillGoodsInformation(ConditionVo conditionVo) {
        //调用B端 新增结算单
//        ResponseEntity<Object> response = restTemplate.postForEntity(getAcceptanceGoods,
//                conditionVo,Object.class);
//        if (response.getStatusCode().value() != HttpStatus.OK.value()) {
//            throw new BusinessException(CodeUtil.FAIL, "获取业务相关验收单未结算的货物！");
//        }
//        Map<Object, Object>  body = (Map<Object, Object>) response.getBody();
//        body.put("code",200);
//        return body;
        String businessNumber = conditionVo.getCondition();
        Long supplierId = conditionVo.getConditionLong();
//        Long status = dictService.getByCode(ProjectInitiationStatusEnum.COMPLETED.getCode()).getId();
        Page<CAcceptanceBasicInfo> page = PageHelper.startPage(conditionVo.getPage(), conditionVo.getRows());
        //存在的该业务下该供应商未结算验收单
//        QueryWrapper<CAcceptanceBasicInfo> queryWrapper = new QueryWrapper<CAcceptanceBasicInfo>();
//        queryWrapper.eq("business_number",businessNumber);
//        queryWrapper.eq("c_supplier_info_id",supplierId);
//        queryWrapper.eq("acceptance_status",ProjectInitiationStatusEnum.COMPLETED.getCode());
//        List<CAcceptanceBasicInfo> acceptanceBasicInfos = icAcceptanceBasicInfoService.list(queryWrapper);
        CAcceptanceBasicInfo basicInfo = new CAcceptanceBasicInfo();
        basicInfo.setBusinessNumber(businessNumber);
        basicInfo.setAcceptanceStatus(ProjectInitiationStatusEnum.COMPLETED.getCode());
        List<CAcceptanceBasicInfo> acceptanceBasicInfos = icAcceptanceBasicInfoService.findByCondition(basicInfo, null);
        acceptanceBasicInfos = acceptanceBasicInfos.stream().filter(r -> !CollectionUtil.isNotEmpty(settlementGoodsInfoService.list(new QueryWrapper<SettlementGoodsInfo>().eq("acceptance_goods_number", r.getAcceptanceGoodsNumber())))).collect(Collectors.toList());
        //验收单货物做过底层的话价格信息从底层取
        if (CollectionUtil.isNotEmpty(acceptanceBasicInfos)) {
            for (CAcceptanceBasicInfo acceptanceBasicInfo : acceptanceBasicInfos) {
                List<CAcceptanceGoodsInfo> acceptanceGoodsInfos = icAcceptanceGoodsInfoService.list(new QueryWrapper<CAcceptanceGoodsInfo>().eq("acceptance_goods_number", acceptanceBasicInfo.getAcceptanceGoodsNumber()));
                for (CAcceptanceGoodsInfo acceptanceGoodsInfo : acceptanceGoodsInfos) {
                    BigDecimal salesPrice = acceptanceGoodsInfo.getSalesPrice() == null ? BigDecimal.ZERO : acceptanceGoodsInfo.getSalesPrice();
                    BigDecimal purchasePrice = acceptanceGoodsInfo.getPurchasePrice() == null ? BigDecimal.ZERO : acceptanceGoodsInfo.getPurchasePrice();
                    acceptanceGoodsInfo.setSalesPrice(salesPrice);
                    acceptanceGoodsInfo.setPurchasePrice(purchasePrice);
                    acceptanceGoodsInfo.setSalesTotalPrice(salesPrice.multiply(acceptanceGoodsInfo.getGoodsQuantity()).setScale(4, RoundingMode.HALF_UP));
                    acceptanceGoodsInfo.setSalesGuaranteeMoney(BigDecimal.ZERO);
                    acceptanceGoodsInfo.setPurchaseTotalPrice(purchasePrice.multiply(acceptanceGoodsInfo.getGoodsQuantity()).setScale(4, RoundingMode.HALF_UP));
                    acceptanceGoodsInfo.setPurchGuaranteeMoney(BigDecimal.ZERO);
                }
                acceptanceBasicInfo.setAcceptanceGoodInfos(acceptanceGoodsInfos);
                String acceptanceStatus = acceptanceBasicInfo.getAcceptanceStatus();
                if (acceptanceStatus != null) {
                    acceptanceBasicInfo.setAcceptanceStatusDict(dictService.getByCode(acceptanceStatus));
                }

            }
        }
        return new GridPage<>(conditionVo.getRows(), conditionVo.getPage(), page.getTotal(), acceptanceBasicInfos);
    }


    @Override
    public Object getExpectedSettlementDate(SettlementBasicInfo settlementBasicInfo) {
        //调用B端 新增结算单
        ResponseEntity<Object> response = restTemplate.postForEntity(getExpectedSettlementDate,
                settlementBasicInfo, Object.class);
        if (response.getStatusCode().value() != HttpStatus.OK.value()) {
            throw new BusinessException(CodeUtil.FAIL, "计算对账日期异常！");
        }
        Map<String, Object> body = (Map<String, Object>) response.getBody();
        Map<String, Object> data = (Map<String, Object>) body.get("data");
        return data;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object calculation(SettlementBasicInfo settlementBasicInfo) {
        BigDecimal occupationSalesRetention = BigDecimal.ZERO;
        BigDecimal occupationPurchRetention = BigDecimal.ZERO;
        List<Long> acceptanceBasicInfoIds = new ArrayList<>();
        //需要计算的货物
//        List<CAcceptanceGoodsInfo> acceptanceGoodsInfos = settlementBasicInfo.getAcceptanceGoodsInfos();
        //计算现有的采购质保金
        //该业务下该供应商的所有验收单
        List<CAcceptanceBasicInfo> acceptanceBasicInfoList = icAcceptanceBasicInfoService.list(new QueryWrapper<CAcceptanceBasicInfo>()
                .eq("business_number", settlementBasicInfo.getBusinessNumber())
//                .eq("c_supplier_info_id", settlementBasicInfo.getSupplierId())
                .eq("acceptance_status", ProjectInitiationStatusEnum.COMPLETED.getCode()));
        if (acceptanceBasicInfoList != null && acceptanceBasicInfoList.size() > 0) {
            acceptanceBasicInfoIds = acceptanceBasicInfoList.stream().map(CAcceptanceBasicInfo::getId).collect(Collectors.toList());
            for (CAcceptanceBasicInfo acceptanceBasicInfo : acceptanceBasicInfoList) {
//                settlementBasicInfo.setAcceptanceGoodsInfos(icAcceptanceGoodsInfoService.list(new QueryWrapper<CAcceptanceGoodsInfo>().eq("c_acceptance_basic_info_id",acceptanceBasicInfo.getId())));
                //验收单下做过结算的货物
                List<SettlementGoodsInfo> settlementGoodsInfoList = settlementGoodsInfoService.listByAcceptanceId(acceptanceBasicInfo.getId());
                if (settlementGoodsInfoList != null && settlementGoodsInfoList.size() > 0) {
                    for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                        occupationPurchRetention = occupationPurchRetention.add(settlementGoodsInfo.getPurchaseGuaranteeMoney() == null ? BigDecimal.ZERO : settlementGoodsInfo.getPurchaseGuaranteeMoney());
                    }
                }
            }
        }
        //计算现有的销售质保金
        //该业务下的所有验收单
        List<CAcceptanceBasicInfo> acceptanceBasicInfos = icAcceptanceBasicInfoService.list(new QueryWrapper<CAcceptanceBasicInfo>()
                .eq("business_number", settlementBasicInfo.getBusinessNumber())
                .eq("acceptance_status", ProjectInitiationStatusEnum.COMPLETED.getCode()));
        if (acceptanceBasicInfos != null && acceptanceBasicInfos.size() > 0) {
            for (CAcceptanceBasicInfo acceptanceBasicInfo : acceptanceBasicInfos) {
                //验收单下做过结算的货物
                List<SettlementGoodsInfo> settlementGoodsInfoList = settlementGoodsInfoService.listByAcceptanceId(acceptanceBasicInfo.getId());
                if (settlementGoodsInfoList != null && settlementGoodsInfoList.size() > 0) {
                    for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfoList) {
                        occupationSalesRetention = occupationSalesRetention.add(settlementGoodsInfo.getSalesGuaranteeMoney() == null ? BigDecimal.ZERO : settlementGoodsInfo.getSalesGuaranteeMoney());
                    }
                }
            }
        }
//        List<CAcceptanceGoodsInfo> cAcceptanceGoodsInfos = icAcceptanceGoodsInfoService
//            .list(new QueryWrapper<CAcceptanceGoodsInfo>()
//                .in("c_acceptance_basic_info_id", acceptanceBasicInfoIds));
        List<CAcceptanceGoodsInfo> acceptanceGoodsInfos = settlementBasicInfo.getAcceptanceGoodsInfos();
        List<Long> collect = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(acceptanceGoodsInfos)) {
            collect = acceptanceGoodsInfos.stream().map(CAcceptanceGoodsInfo::getId).collect(Collectors.toList());
        }
        //一键计算质保金
        List<SettlementGoodsInfo> calculateResult = new ArrayList<>();
        List<SettlementGoodsInfo> calculate = goodsCalculateService.calculateGoodsAmount(settlementBasicInfo.getBusinessNumber(),
                settlementBasicInfo.getSupplierId(), acceptanceGoodsInfos, occupationSalesRetention, occupationPurchRetention);
        List<Long> finalCollect = collect;
        calculate.forEach(goodsInfo -> {
            BigDecimal salesGuaranteeMoney = goodsInfo.getSalesGuaranteeMoney() == null ? BigDecimal.ZERO : goodsInfo.getSalesGuaranteeMoney();
            goodsInfo.setSalesGuaranteeMoney(salesGuaranteeMoney.setScale(2, RoundingMode.HALF_UP));

            goodsInfo.setSalesTotalPrice(goodsInfo.getSalesTotalPrice().setScale(2, RoundingMode.HALF_UP));
            goodsInfo.setPurchasePrice(goodsInfo.getPurchasePrice().setScale(2, RoundingMode.HALF_UP));
            goodsInfo.setPurchaseTotalPrice(goodsInfo.getPurchaseTotalPrice().setScale(2, RoundingMode.HALF_UP));

            BigDecimal purchaseGuaranteeMoney = goodsInfo.getPurchaseGuaranteeMoney() == null ? BigDecimal.ZERO : goodsInfo.getPurchaseGuaranteeMoney();
            goodsInfo.setPurchaseGuaranteeMoney(purchaseGuaranteeMoney.setScale(2, RoundingMode.HALF_UP));
            if (finalCollect.contains(goodsInfo.getAcceptanceGoodsInfoId())) {
                calculateResult.add(goodsInfo);
            }
        });
        return calculateResult;
        //调用B端 一键计算质保金
//        ResponseEntity<Object> response = restTemplate.postForEntity(calculation,
//                settlementBasicInfo,Object.class);
//        if (response.getStatusCode().value() != HttpStatus.OK.value()) {
//            throw new BusinessException(CodeUtil.FAIL, "一键计算质保金异常！");
//        }
//        Map<Object, Object>  body = (Map<Object, Object>) response.getBody();
//        body.put("code",200);
//        return body;
    }

    @Override
    public ResponseEntity<Object> downloadReport(Long id, HttpServletResponse res) {
        List<FileStorageDO> files = fileService.findByBusinessId(id, FileModuleDict.ChildEnum.SETTLEMENT_CONTRACT_REPORT.getCode());
        return fileService.downloadFile(files.get(0).getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Object> downloadPdfSign(Long settlementBasicInfoId, HttpServletResponse res) {
        List<FileStorageDO> files = fileService.findByBusinessId(settlementBasicInfoId, FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE.getCode());
        if (CollectionUtil.isNotEmpty(files)) {
            //return fileService.downloadFile(files.get(0).getId());
            FileStorageDO fileStorage = fileService.getById(files.get(0).getId());
            if (fileStorage != null) {
                String fileName = fileStorage.getOriginalName();
                String fileNameEncodeStr = "null";
                try {
                    fileNameEncodeStr = java.net.URLEncoder.encode(fileName, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    fileNameEncodeStr = "";
                }
                String path = fileStorage.getAbsolutePath();
                File file = new File(path);
                try {
                    FileInputStream fis = new FileInputStream(file);

                    res.setHeader("Content-Disposition", "attachment; filename=" + fileNameEncodeStr);
                    res.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
                    res.setHeader("Pragma", "no-cache");
                    res.setHeader("Expires", "0");

                    res.setContentLength((int) file.length());
                    ServletOutputStream outputStream = res.getOutputStream();
                    res.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                    byte[] b = new byte[1000];
                    int read = fis.read(b);
                    while (read > 0) {
                        outputStream.write(b, 0, read);
                        read = fis.read(b);
                    }
                    fis.close();
                    outputStream.flush();
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    public List<FileStorageDO> showPdfSign(Long settlementBasicInfoId) {
        List<FileStorageDO> files = fileService.findByBusinessId(settlementBasicInfoId, FileModuleDict.ChildEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE.getCode());
        return files;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String downloadPdf(SettlementBasicInfo settlementBasicInfo, HttpServletResponse response) {
        try {
            //模板中填充数据
            File file = inputData(settlementBasicInfo);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return "data:application/pdf;base64," + Base64.encodeBase64String(buffer);
        } catch (Exception e) {
            throw new BusinessException(CodeUtil.FAIL, "生成结算单出错" + e.getMessage());
        }
    }

    @Override
    public Object findAllList(SearchBusiness search) {
        UserDTO abstractUser = (UserDTO) LoginUserHolder.get();
        if (abstractUser != null) {
            List<Long> userIds = new ArrayList<>();
            userIds.add(abstractUser.getId());
            search.setUserIds(userIds);
        }
        Page<SearchBusiness> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<BusinessProcessingTaskDTO> list = baseMapper.findAllList(search);
        if (CollectionUtil.isNotEmpty(list)) {
            for (BusinessProcessingTaskDTO businessProcessingTaskDTO : list) {
                List<InvoiceGoodsInfo> invoiceGoodsInfos = invoiceGoodsInfoService.list(new QueryWrapper<InvoiceGoodsInfo>().eq("settlement_number", businessProcessingTaskDTO.getModuleNumber()));
                if (CollectionUtil.isNotEmpty(invoiceGoodsInfos)) {
                    businessProcessingTaskDTO.setButtonFlag(false);
                } else {
                    businessProcessingTaskDTO.setButtonFlag(true);
                }
            }
        }
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SettlementElectronicInfo autoSign(Long businessKey, String taskId) {
        AbstractUser abstractUser = LoginUserHolder.get();
        SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(businessKey);
        SettlementElectronicInfo settlementElectronicInfo = settlementElectronicInfoService.getOne(new QueryWrapper<SettlementElectronicInfo>().eq("c_settlement_basic_info_id", businessKey)
                .orderByDesc("gmt_create").last("LIMIT 1"));
        if (settlementElectronicInfo == null || (settlementElectronicInfo.getSignConclusion().equals(ConstantUtil.PASS) && settlementBasicInfo.getSettlementStatus().equals(ProjectInitiationStatusEnum.PROCESSING.getCode()))) {
            settlementElectronicInfo = new SettlementElectronicInfo();
            settlementElectronicInfo.setSettlementBasicInfoId(businessKey);
            Platform platform = platformService.getById(settlementBasicInfo.getTradingPlatformId());
            SupplierInfo supplierInfo = iSupplierInfoService.getById(settlementBasicInfo.getSupplierId());
            Enterprise enterprise = iEnterpriseService.getById(supplierInfo.getcEnterpriseId());
            //认证状态  签署状态初始化
            if (!enterprise.getAuthStatus()) {
                String result = ElectronicSignatureUtil.getAuthInfo(enterprise.getSocialCreditCode(), "2");
                if ("1".equals(result)) {
                    enterprise.setAuthStatus(true);
                    icPurchContractElectronicInfoService.lambdaUpdate()
                            .eq(CPurchContractElectronicInfo::getFddCustomerId, enterprise.getFddCustomerId())
                            .set(CPurchContractElectronicInfo::getCertifyStatus, 1)
                            .update();
                } else {
                    throw new BusinessException(CodeUtil.FAIL, "请先前往企业信息管理模块下的供应商，打开认证链接，进行认证操作再返回此处进行后续操作");
                }
            }
            settlementElectronicInfo.setCertifyStatus(enterprise.getAuthStatus() ? 1 : 0);
            settlementElectronicInfo.setCertifyLink(enterprise.getShortAuthUrl());
            settlementElectronicInfo.setSignStatus(0);
            settlementElectronicInfoService.save(settlementElectronicInfo);
            //获取制作好的结算单(未签署)
            List<FileStorageDO> fileStorages = fileService.findByBusinessId(businessKey, FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE.getCode());
            File pdfFile = new File(fileStorages.get(0).getAbsolutePath());
            //上传合同
            String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
            settlementBasicInfo.setContractId(contractId);
            settlementBasicInfoService.updateById(settlementBasicInfo);
            String docTitle = "上游验收单" + settlementBasicInfo.getSettlementNumber();
            String transactionId = "settlementFDD" + settlementElectronicInfo.getId() + settlementBasicInfo.getSettlementNumber();
            ElectronicSignatureUtil.uploadContract(contractId, docTitle, pdfFile);
            //采购合同自动签署
            String signKeyword = "mypt";
            ElectronicSignatureUtil.autoSign(transactionId, contractId, platform.getFddCustomerId(), docTitle, signKeyword);
            //批量手动签署 此处只有一个合同
            List<FddSignData> fddSignDataList = new ArrayList<FddSignData>();
            FddSignData fddSignData = new FddSignData();
            fddSignData.setContractId(contractId);
            fddSignData.setContractType("settlement");
            fddSignData.setSignKeyword("gys");
            fddSignData.setTransactionId("signSettlementFDD" + settlementElectronicInfo.getId() + businessKey + "FDD" + taskId + "FDD" + abstractUser.getId());
            fddSignDataList.add(fddSignData);
            String contractLink = ElectronicSignatureUtil.manualBatchSign(enterprise.getFddCustomerId(), fddSignDataList, settlementBasicInfo.getSettlementNumber());
            //合同链接
            String shortUrl = ElectronicSignatureUtil.shortUrl(null, contractLink);
            settlementElectronicInfo.setTransactionId(fddSignData.getTransactionId());
            settlementElectronicInfo.setShortContractLink(shortUrl);
            settlementElectronicInfo.setShortContractLinkCreate(new Date());
            settlementElectronicInfo.setContractLink(contractLink);
            settlementElectronicInfoService.updateById(settlementElectronicInfo);
        }
        return settlementElectronicInfo;
    }

    @Override
    public Object importGoodsInfo(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(CodeUtil.FAIL, "导入Excel文件不能为空");
        }
        try {
            InputStream inputStream = file.getInputStream();
            Collection<SettlementGoodsInfo> acceptanceGoodsInfo = ExcelUtil.importExcel(SettlementGoodsInfo.class, inputStream, "yyyy-MM-dd", new ExcelLogs(), 0);
            for (SettlementGoodsInfo goodsInfo : acceptanceGoodsInfo) {
                int salesPriceLength = 0;
                if (goodsInfo.getSalesPrice() != null) {
                    salesPriceLength = goodsInfo.getSalesPrice().stripTrailingZeros().scale();
                }
                int goodsQuantityLength = goodsInfo.getGoodsQuantity().stripTrailingZeros().scale();
                if ((salesPriceLength != 0 && salesPriceLength > 4) || goodsQuantityLength > 4) {
                    throw new ValidatorException(CodeUtil.FAIL, "导入失败，销售单价或数量小数位数过长！");
                }
//                goodsInfo.setSalesPriceStr(goodsInfo.getSalesPrice() != null ? goodsInfo.getSalesPrice().toString() : "");
            }

            inputStream.close();
            return acceptanceGoodsInfo;
        } catch (IOException e) {
            throw new BusinessException(CodeUtil.FAIL, "导入失败，请确认文件模板格式是否符合要求");
        }
    }

    @Override
    public void downloadFile(HttpServletResponse response) {
        OutputStream out = null;
//        BufferedInputStream缓冲输入流
        BufferedInputStream inputStream = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("templateFiles/结算单货物模板.xlsx");
            response.setHeader("Content-Type", "application/vnd.ms-exce");
            response.setHeader("Content-Length", String.valueOf(classPathResource.contentLength()));
            response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(classPathResource.getFilename(), "UTF-8"));
            out = response.getOutputStream();
            inputStream = new BufferedInputStream(classPathResource.getInputStream());
            byte[] buffer = new byte[1024];
            while ((inputStream.read(buffer)) > 0) {
                out.write(buffer);
                out.flush();
            }

        } catch (Exception e) {
            throw new BusinessException(CodeUtil.FAIL, "下载模板失败!");
        } finally {
            try {
                inputStream.close();
                out.close();
            } catch (IOException e) {
                log.error("关闭文件流失败!");
            }
        }
    }

    @Override
    @Transactional
    public void billUnitPriceAdjust(SettlementBasicInfo settlementBasicInfo) {
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementBasicInfo.getSettlementGoodsInfos();
        if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                if (settlementGoodsInfo.getId() != null) {
                    SettlementGoodsInfo oldSettlementGoodsInfo = settlementGoodsInfoService.getById(settlementGoodsInfo.getId());
                    settlementGoodsInfo.setAcceptanceGoodsInfoId(oldSettlementGoodsInfo.getAcceptanceGoodsInfoId());
                    settlementGoodsInfo.setcAcceptanceBasicInfoId(oldSettlementGoodsInfo.getcAcceptanceBasicInfoId());
                    settlementGoodsInfoService.updateById(settlementGoodsInfo);
                } else {
                    settlementGoodsInfoService.save(settlementGoodsInfo);
                }
            }
            //调用B端接口 开启 单价变更流程
            settlementBasicInfo.setSubmit(true);
            settlementBasicInfo.setSettlementStatus(ProjectInitiationStatusEnum.PROCESSING.getCode());
            settlementBasicInfoService.updateById(settlementBasicInfo);

            SettlementBasicInfo oldSettlement = settlementBasicInfoService.getById(settlementBasicInfo.getId());
            settlementBasicInfo.setSupplierId(oldSettlement.getSupplierId());
            settlementBasicInfo.setEnterpriseCustomerInfoId(oldSettlement.getEnterpriseCustomerInfoId());
            settlementBasicInfo.setSettlementDate(oldSettlement.getSettlementDate());
            settlementBasicInfo.setSettlementAmount(oldSettlement.getSettlementAmount());
            settlementBasicInfo.setSettlementEndDate(oldSettlement.getSettlementEndDate());
            settlementBasicInfo.setSettleTotalSalesPrice(oldSettlement.getSettleTotalSalesPrice());
            settlementBasicInfo.setTradingPlatformId(oldSettlement.getTradingPlatformId());
            settlementBasicInfo.setSettlementNumber(oldSettlement.getSettlementNumber());
            //补充说明文件
            List<Long> additionalFileIds = settlementBasicInfo.getAdditionalFileIds();
            if (CollectionUtil.isNotEmpty(additionalFileIds)) {
                List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_SUPPLEMENT_FILE.getCode());
                for (FileStorageDO fileStorageDO : fileStorageDOS) {
                    fileService.updateBusinessId(fileStorageDO.getId(), null);
                }
                //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
                for (Long id : additionalFileIds) {
                    fileService.updateBusinessId(id, settlementBasicInfo.getId());
                }
            }
//            List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE.getCode());
//            for (FileStorageDO fileStorageDO:fileStorageDOS) {
//                fileService.updateBusinessId(fileStorageDO.getId(),null);
//            }
//            File file = inputData(settlementBasicInfo);
//            FileStorageDO fileStorage = FileStorageUtil.createFileStorage3(settlementBasicInfo.getId()+"",FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE,file.getName(),".pdf");
//            fileStorage.setBusinessId(settlementBasicInfo.getId());
//            fileService.save(fileStorage);
            ResponseEntity<String> response = restTemplate.postForEntity(billUnitPriceAdjust,
                    settlementBasicInfo, String.class);
            if (response.getStatusCode().value() != HttpStatus.OK.value()) {
                throw new BusinessException(CodeUtil.FAIL, "流程处理失败，请联系管理员！");
            }

        }
    }


    private SettlementBasicInfo addSettlement(SettlementBasicInfo settlementBasicInfo, HttpServletRequest request) {
        if (settlementBasicInfo.getBusinessNumber() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "请锁定业务编号后保存");
        }
        AbstractUser abstractUser = LoginUserHolder.get();
//        ArrayList<String> additional = new ArrayList<>();
//        if (request instanceof MultipartHttpServletRequest) {
//            MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request)
//                    .getMultiFileMap();
//            Set<String> keys = multiValueMap.keySet();
//            for (String key : keys) {
//                if (key.startsWith("additional")) {
//                    additional.add(key);
//                }
//            }
//        }
        //保存结算单基础信息
        String billInformationNumber = serialNumberGenerator.nextValue(ConstantUtil.BILL_CODE);
        settlementBasicInfo.setSettlementNumber(billInformationNumber);
        settlementBasicInfo.setSettlementStatus(ProjectInitiationStatusEnum.PROCESSING.getCode());
        if (settlementBasicInfo.getSubmit()) {
            ValidatorUtil.validator(ValidatorEntity.ValidatorType.ADD, settlementBasicInfo);
            settlementBasicInfoService.save(settlementBasicInfo);
        } else {
            settlementBasicInfoService.save(settlementBasicInfo);
        }
        //保存回款计划
        List<SettlementRepaymentPlan> settlementRepaymentPlans = settlementBasicInfo.getSettlementRepaymentPlans();
        if (settlementRepaymentPlans != null && settlementRepaymentPlans.size() > 0) {
            for (SettlementRepaymentPlan settlementRepaymentPlan : settlementRepaymentPlans) {
                settlementRepaymentPlan.setSettlementBasicInfoId(settlementBasicInfo.getId());
            }
        }
        settlementRepaymentPlanService.saveBatch(settlementRepaymentPlans);
        //下游结算清单附件
        List<Long> fileIds = settlementBasicInfo.getFileIds();
        if (CollectionUtil.isNotEmpty(fileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : fileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }

        //再新增结算单说明附件
        List<Long> additionalFileIds = settlementBasicInfo.getAdditionalFileIds();
        if (CollectionUtil.isNotEmpty(additionalFileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : additionalFileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }
        //再新增结算单网价附件
        List<Long> netPriceFileIds = settlementBasicInfo.getNetPriceFileIds();
        if (CollectionUtil.isNotEmpty(netPriceFileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : netPriceFileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }

        //新增结算单货物信息
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementBasicInfo.getSettlementGoodsInfos();
        if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                settlementGoodsInfo.setSettlementBasicInfoId(settlementBasicInfo.getId());
            }
            settlementGoodsInfoService.saveBatch(settlementGoodsInfos);
            //校验验收单货物
            List<Long> acceptanceBasicInfoIds = settlementGoodsInfos.stream().map(SettlementGoodsInfo::getcAcceptanceBasicInfoId)
                    .distinct().collect(Collectors.toList());
            acceptanceBasicInfoIds.forEach(id -> {
                CAcceptanceBasicInfo basicInfo = icAcceptanceBasicInfoService.getById(id);
                if (basicInfo.getSettlement()) {
                    throw new BusinessException(CodeUtil.FAIL, "存在已结算或者正在结算的货物");
                } else {
                    if (settlementBasicInfo.getSubmit()) {
                        basicInfo.setSettlement(true);
                        icAcceptanceBasicInfoService.updateById(basicInfo);
                    }
                }
            });
        }

        if (settlementBasicInfo.getSubmit()) {
            //保存结算单相关货物信息
            if (settlementGoodsInfos != null) {
                for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                    if (settlementGoodsInfo.getSalesPrice() != null && settlementGoodsInfo.getSalesPrice().compareTo(BigDecimal.ZERO) <= 0) {
                        throw new BusinessException(CodeUtil.FAIL, "请填写销售单价并进行质保金计算");
                    }
                }
            }
            settlementBasicInfo.setSettlementStatus(ProjectInitiationStatusEnum.PROCESSING.getCode());
            settlementBasicInfoService.updateById(settlementBasicInfo);
            //验证经办人和销售合同经办人是否一致
            //销售合同
//            CSalesContractManagement salesContractManagement = icSalesContractManagementService.getOne(
//                    new QueryWrapper<CSalesContractManagement>()
//                            .eq("business_number", settlementBasicInfo.getBusinessNumber())
//                            .last("LIMIT 1"));
//            CSalesContractBasicInfo salesContractBasicInfo = icSalesContractBasicInfoService.getOne(
//                    new QueryWrapper<CSalesContractBasicInfo>().eq("c_sales_contract_management_id", salesContractManagement.getId())
//                            .orderByDesc("gmt_create").last("LIMIT 1"));
//            List<CSalesContractPersonInfo> contractPersonInfos = icSalesContractPersonInfoService.lambdaQuery().eq(CSalesContractPersonInfo::getcSalesContractBasicInfoId, salesContractBasicInfo.getId()).eq(CSalesContractPersonInfo::getType, "结算经办人").list();
//            boolean contains = false;
//            for (CSalesContractPersonInfo contractPersonInfo : contractPersonInfos) {
//                contains = settlementBasicInfo.getOperatorEnterprise().contains(contractPersonInfo.getName());
//                if (contains) {
//                    break;
//                }
//            }
//            if (!contains && additional.size() == 0) {
//                throw new ValidatorException(CodeUtil.FAIL, "结算单经办人和销售合同规定经办人不一致需要上传说明附件！");
//            }
            //生成结算单
//            File file = inputData(settlementBasicInfo);
//            FileStorageDO fileStorage =FileStorageUtil.createFileStorage3(settlementBasicInfo.getId()+"",FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE,file.getName(),".pdf");
//            fileStorage.setBusinessId(settlementBasicInfo.getId());
//            fileService.save(fileStorage);
        }

        return settlementBasicInfo;
    }

    private File inputData(SettlementBasicInfo settlementBasicInfo) {
        //货物相关
        //货物信息
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementBasicInfo.getSettlementGoodsInfos();

        //合同信息 采购合同
        CPurchContractManagement cPurchContractManagement = icPurchContractManagementService.getOne(
                new QueryWrapper<CPurchContractManagement>()
                        .eq("business_number", settlementBasicInfo.getBusinessNumber())
                        .eq("c_supplier_info_id", settlementBasicInfo.getSupplierId()));
        CPurchContractBasicInfo cPurchContractBasicInfo = icPurchContractBasicInfoService.getOne(
                new QueryWrapper<CPurchContractBasicInfo>().eq("c_purch_contract_management_id", cPurchContractManagement.getId()).orderByDesc("gmt_create").last("LIMIT 1")
        );

//        List<CPurchContractBuyerSeller> cPurchContractBuyerSellers = icPurchContractBuyerSellerService.list(new QueryWrapper<CPurchContractBuyerSeller>().eq("c_purch_contract_basic_info_id", cPurchContractBasicInfo.getId()).eq("buyer_or_seller", 1));

        //最后一次审核的信息
        PurchContractApproval purchContractApproval = purchContractApprovalService.getOne(
                new LambdaQueryWrapper<PurchContractApproval>()
                        .eq(PurchContractApproval::getPurchContractBasicInfoId,
                                cPurchContractBasicInfo.getId())
                        .orderByDesc(PurchContractApproval::getGmtCreate).last("LIMIT 1"));
        List<PurchContractNeedUserRel> buyers = iPurchContractNeedUserRelService.list(
                new LambdaQueryWrapper<PurchContractNeedUserRel>()
                        .eq(PurchContractNeedUserRel::getPurchContractApprovalId,
                                purchContractApproval.getId()));
        StringBuffer names = new StringBuffer();
        for (PurchContractNeedUserRel purchContractNeedUserRel : buyers) {
            String name = purchContractNeedUserRel.getName() + ",";
            names.append(name);
        }
        String name = names.toString();
        name = name.substring(0, names.length() - 1);
        //供货单位
        SupplierInfo supplierInfo = iSupplierInfoService.getById(settlementBasicInfo.getSupplierId());
        Enterprise enterprise = iEnterpriseService.getById(supplierInfo.getcEnterpriseId());
        //收货单位
        Platform receiver = platformService.getById(settlementBasicInfo.getTradingPlatformId());
        //填充数据开始
        try {
            Map<String, Object> dataMap = new HashMap<>();
            //供货单位
            dataMap.put("supplierName", enterprise.getCorporateName());
            //合同编号
            dataMap.put("contractNumber", cPurchContractBasicInfo.getContractNumber());
            //结算日期
            dataMap.put("settlementDate", DateUtil.dateToString(settlementBasicInfo.getSettlementDate(), DateUtil.dayFormat));
            //收货单位 贸易平台
            dataMap.put("platformName", receiver.getPlatformName());
            //经办人 需方收货人姓名
            dataMap.put("manager", name);
            //供货单位
            dataMap.put("supplierName", enterprise.getCorporateName());
            //经办人（供应商）
            dataMap.put("settlementManager", settlementBasicInfo.getOperatorSupplier());
            //填充货物信息
//            TableRenderData tableRenderData = makeGoddsList(settlementGoodsInfos, dataMap);
//            dataMap.put("dealGoodsList", tableRenderData);
            List<Map<String, Object>> dealGoodsList = new ArrayList<>();
            if (cn.hutool.core.collection.CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
                int i = 0;
                BigDecimal amountSum = BigDecimal.ZERO, num = BigDecimal.ZERO;
                for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                    Map<String, Object> map = new HashMap<>();
                    CAcceptanceGoodsInfo acceptanceGoodsInfo = icAcceptanceGoodsInfoService.getById(settlementGoodsInfo.getAcceptanceGoodsInfoId());
                    amountSum = amountSum.add(settlementGoodsInfo.getPurchaseTotalPrice());
                    i = i + 1;
                    map.put("id", i);
                    map.put("goodsName", acceptanceGoodsInfo.getGoodsName());
                    map.put("goodsFactory", acceptanceGoodsInfo.getGoodsFactory());
                    map.put("goodsType", acceptanceGoodsInfo.getGoodsType());
                    map.put("goodsUnit", acceptanceGoodsInfo.getGoodsUnit());
                    map.put("goodsQuantity", acceptanceGoodsInfo.getGoodsQuantity().toString());
                    map.put("purchasePrice", settlementGoodsInfo.getPurchasePrice().setScale(2, RoundingMode.HALF_UP).toString());
                    map.put("purchaseTotalPrice", settlementGoodsInfo.getPurchaseTotalPrice().setScale(2, RoundingMode.HALF_UP).toString());
                    dealGoodsList.add(map);
                    num = num.add(settlementGoodsInfo.getGoodsQuantity());
                }
                dataMap.put("num", num);
                dataMap.put("amountSum", amountSum);
            }
            dataMap.put("dealGoodsList", dealGoodsList);
            File docxFile = null;
            String fileName;
            AbstractUser abstractUser = LoginUserHolder.get();
            if (settlementBasicInfo.getSettlementNumber() == null) {
                fileName = "settlement" + settlementBasicInfo.getBusinessNumber() + DateUtil.getCurrentDate()
                        .replace("-", "").replace(":", "") + abstractUser.getId();
            } else {
                BigDecimal allPurchaseTotalPrice = settlementGoodsInfos.stream().map(SettlementGoodsInfo::getPurchaseTotalPrice)
                        .reduce(BigDecimal::add).orElse(new BigDecimal(0));
                fileName = settlementBasicInfo.getSettlementNumber() + "-" + allPurchaseTotalPrice.toString() + "-上游结算";
            }
            docxFile = savesettleFile(settlementBasicInfo.getId(), fileName, ".docx", FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE, dataMap);
//            docxFile = WordWriter.buildSettlementFile(fileName, dataMap);
            String suffix = FileUtil.getSuffix(docxFile.getName());
            String newPath = docxFile.getAbsolutePath().replace(suffix, "pdf");
            File pdfFile = OfficeConverterUtil.office2Pdf(docxFile.getAbsolutePath(), newPath);
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(CodeUtil.FAIL, "下载结算清单错误" + e.getMessage());
        }
    }

    /**
     * 合同保存
     *
     * @param fileName
     * @param fileTypeEnum
     * @param dataMap
     */
    private File savesettleFile(Long businessId, String fileName, String suffix, FileTypeEnum fileTypeEnum, Map<String, Object> dataMap) {
        String docPath = "ftl/bill.export/settlement1.docx";
        ClassPathResource classPathResource = new ClassPathResource(docPath);
        SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
        String docxPath = FileStorageUtil.getAbsolutePath(fileName, suffix, fileTypeEnum);
        /** 指定输出word文件的路径 **/
        File docFile = new File(docxPath);
        if (!docFile.getParentFile().exists()) {
            docFile.getParentFile().mkdirs();
        }
        String name = fileName + suffix;
        String file = PoitlToDocx.createWord(classPathResource, docFile.getParent(), name, dataMap);
        File debtorFile = new File(file);
        // 原文件名称
//				String originalName = debtorFile.getName();
//        String newPath = debtorFile.getAbsolutePath().replace(suffix, ".pdf");
//        File file1 = OfficeConverterUtil
//                .office2Pdf(debtorFile.getAbsolutePath(), newPath);
        List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(businessId, fileTypeEnum.getCode());
        for (FileStorageDO fileStorageDO : fileStorageDOS) {
            fileService.updateBusinessId(fileStorageDO.getId(), null);
        }
//        FileStorageDO fileStorage = new FileStorageDO();
//        fileStorage.setPath(debtorFile.getPath());
//        fileStorage.setType(suffix);
//        fileStorage.setAbsolutePath(debtorFile.getAbsolutePath());
//        fileStorage.setOriginalName(fileName);
//        fileStorage.setStorageType("disk");
//        fileStorage.setBusinessId(businessId);
//        fileStorage.setBusinessType(fileTypeEnum.getCode());
//        fileStorage.setSize(debtorFile.length());
//        fileService.save(fileStorage);
        return debtorFile;
    }

    @Override
    public Object findOperatorByBusinessNumber(String businessNumber) {
        CSalesContractBasicInfo salesContractBasicInfo = icSalesContractManagementService.findByBusinessNumber(businessNumber);
        if (salesContractBasicInfo != null) {
            List<CSalesContractPersonInfo> contractPersonInfos = icSalesContractPersonInfoService.lambdaQuery().eq(CSalesContractPersonInfo::getcSalesContractBasicInfoId, salesContractBasicInfo.getId()).eq(CSalesContractPersonInfo::getType, SalesContractPersonTypeEnum.SALESCONTRACTPERSONTYPE_SETTLEMENT.getCode()).list();
//            String names = contractPersonInfos.stream().map(r -> r.getName()).collect(Collectors.joining(","));
            return contractPersonInfos;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBill(SettlementBasicInfo settlementBasicInfo) {
//        Long oldId = settlementBasicInfo.getId();
        //修改原始记录
        if (settlementBasicInfo.getSubmit()) {
            ValidatorUtil.validator(ValidatorEntity.ValidatorType.UPDATE, settlementBasicInfo);
            settlementBasicInfo = updateBillBasicInformation(settlementBasicInfo);
            //c_updateBill 调用B端处理流程
            ResponseEntity<String> response = restTemplate.postForEntity(updateBillBasicInformation,
                    settlementBasicInfo, String.class);
            if (response.getStatusCode().value() != HttpStatus.OK.value()) {
                throw new BusinessException(CodeUtil.FAIL, "结算单新增异常！");
            }
        } else {
            settlementBasicInfo = updateBillBasicInformation(settlementBasicInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean getSignTppe(String electronicInfoId, String taskId, String basicId) {
        if (StringUtil.isEmpty(electronicInfoId) || StringUtil.isEmpty(taskId) || StringUtil.isEmpty(basicId)) {
            throw new ValidatorException(CodeUtil.FAIL, "参数不能为空!");
        }
        ;
        boolean result = false;
        SettlementElectronicInfo electronicInfo = settlementElectronicInfoService.getById(electronicInfoId);
        if (electronicInfo == null || !electronicInfo.getSignStatus().equals(1)) {
            SettlementBasicInfo settlementBasicInfo = settlementBasicInfoService.getById(basicId);
            Platform platform = platformService.getById(settlementBasicInfo.getTradingPlatformId());
            String contractId = settlementBasicInfo.getContractId();
            String customerId = platform.getFddCustomerId();
            if (electronicInfo.getSignStatus().equals(0)) {
                String signResult = ElectronicSignatureUtil.getSignInfo(customerId, contractId, electronicInfo.getTransactionId());
                if (signResult.equals("3000")) {
                    result = true;
                    String[] objStrs = new String[]{"signSettlement", electronicInfo.getSettlementBasicInfoId() + "", taskId};
                    doSignCallBackByQuery(contractId, objStrs);
                }
            } else {
                result = true;
            }
        } else {
            result = true;
        }
        return result;
    }

    private SettlementBasicInfo updateBillBasicInformation(SettlementBasicInfo settlementBasicInfo) {
        Dictionary entryDic = dictService.getByCode(SettlementDict.ChildEnum.ENTRY.getCode());
        Dictionary creatDic = dictService.getByCode(SettlementDict.ChildEnum.CREATE.getCode());
        if (entryDic == null || creatDic == null) {
            throw new ValidatorException(CodeUtil.FAIL, "状态字典项为空！");
        }
        AbstractUser abstractUser = LoginUserHolder.get();
        settlementBasicInfo.setUserModified(abstractUser.getId() + "");
        SettlementBasicInfo oldSettlement = settlementBasicInfoService.getById(settlementBasicInfo.getId());
        settlementBasicInfo.setSettlementNumber(oldSettlement.getSettlementNumber());
        //修改结算单基础信息
        settlementBasicInfoService.updateById(settlementBasicInfo);
        //修改结算单相关货物信息  先删除再新增
        settlementGoodsInfoService.remove(new QueryWrapper<SettlementGoodsInfo>().eq("c_settlement_basic_info_id", settlementBasicInfo.getId()));
        List<SettlementGoodsInfo> settlementGoodsInfos = settlementBasicInfo.getSettlementGoodsInfos();
        if (CollectionUtil.isNotEmpty(settlementGoodsInfos)) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                settlementGoodsInfo.setSettlementBasicInfoId(settlementBasicInfo.getId());
            }
            //校验验收单货物
            List<Long> acceptanceBasicInfoIds = settlementGoodsInfos.stream().map(SettlementGoodsInfo::getcAcceptanceBasicInfoId)
                    .distinct().collect(Collectors.toList());
            acceptanceBasicInfoIds.forEach(id -> {
                CAcceptanceBasicInfo basicInfo = icAcceptanceBasicInfoService.getById(id);
                if (basicInfo.getSettlement()) {
                    throw new BusinessException(CodeUtil.FAIL, "存在已结算或者正在结算的货物");
                } else {
                    if (settlementBasicInfo.getSubmit()) {
                        basicInfo.setSettlement(true);
                        icAcceptanceBasicInfoService.updateById(basicInfo);
                    }
                }
            });
            settlementGoodsInfoService.saveBatch(settlementGoodsInfos);
        }
        //修改回款计划   先删除再新增
        settlementRepaymentPlanService.remove(new QueryWrapper<SettlementRepaymentPlan>().eq("c_settlement_basic_info_id", settlementBasicInfo.getId()));
        List<SettlementRepaymentPlan> settlementRepaymentPlans = settlementBasicInfo.getSettlementRepaymentPlans();
        if (CollectionUtil.isNotEmpty(settlementRepaymentPlans)) {
            for (SettlementRepaymentPlan settlementRepaymentPlan : settlementRepaymentPlans) {
                settlementRepaymentPlan.setSettlementBasicInfoId(settlementBasicInfo.getId());
            }
            settlementRepaymentPlanService.saveBatch(settlementRepaymentPlans);
        }

        //下游结算清单附件
        List<Long> fileIds = settlementBasicInfo.getFileIds();
        List<FileStorageDO> fileStorageDOS2 = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_FILE.getCode());
        for (FileStorageDO fileStorageDO : fileStorageDOS2) {
            fileService.updateBusinessId(fileStorageDO.getId(), null);
        }
        if (CollectionUtil.isNotEmpty(fileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : fileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }
        //结算单管理-补充说明文件
        List<Long> additionalFileIds = settlementBasicInfo.getAdditionalFileIds();
        List<FileStorageDO> fileStorageDOS1 = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_SUPPLEMENT_FILE.getCode());
        for (FileStorageDO fileStorageDO : fileStorageDOS1) {
            fileService.updateBusinessId(fileStorageDO.getId(), null);
        }
        if (CollectionUtil.isNotEmpty(additionalFileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : additionalFileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }

        //再新增结算单网价附件
        List<Long> netPriceFileIds = settlementBasicInfo.getNetPriceFileIds();
        List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_NET_PRICE_FILE.getCode());
        for (FileStorageDO fileStorageDO : fileStorageDOS) {
            fileService.updateBusinessId(fileStorageDO.getId(), null);
        }
        if (CollectionUtil.isNotEmpty(netPriceFileIds)) {
            //SETTLEMENT_FILE("settlementFile", "结算单管理-下游结算单文件"),
            for (Long id : netPriceFileIds) {
                fileService.updateBusinessId(id, settlementBasicInfo.getId());
            }
        }

        //删除旧的上游结算单

        if (settlementBasicInfo.getSubmit()) {
            for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
                if (settlementGoodsInfo.getSalesPrice() != null && settlementGoodsInfo.getSalesPrice().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new BusinessException(CodeUtil.FAIL, "请填写销售单价并进行质保金计算");
                }
            }
            //将文件set集合的key分类
//            ArrayList<String> additional = new ArrayList<>();
//            if (request instanceof MultipartHttpServletRequest) {
//                MultiValueMap<String, MultipartFile> multiValueMap = ((MultipartHttpServletRequest) request)
//                        .getMultiFileMap();
//                Set<String> keys = multiValueMap.keySet();
//                for (String key : keys) {
//                    //验收单附件key
//                    if (key.startsWith("additional")) {
//                        additional.add(key);
//                    }
//                }
//            }
            //结算单经办人验证
            //销售合同
            CSalesContractManagement salesContractManagement = icSalesContractManagementService.getOne(
                    new QueryWrapper<CSalesContractManagement>()
                            .eq("business_number", settlementBasicInfo.getBusinessNumber())
                            .last("LIMIT 1"));
            CSalesContractBasicInfo salesContractBasicInfo = icSalesContractBasicInfoService.getOne(
                    new QueryWrapper<CSalesContractBasicInfo>().eq("c_sales_contract_management_id", salesContractManagement.getId()).orderByDesc("gmt_create").last("LIMIT 1"));
            List<CSalesContractPersonInfo> contractPersonInfos = icSalesContractPersonInfoService.lambdaQuery().eq(CSalesContractPersonInfo::getcSalesContractBasicInfoId, salesContractBasicInfo.getId()).eq(CSalesContractPersonInfo::getType, "结算经办人").list();
            boolean contains = false;
            for (CSalesContractPersonInfo contractPersonInfo : contractPersonInfos) {
                contains = settlementBasicInfo.getOperatorEnterprise().contains(contractPersonInfo.getName());
                if (contains) {
                    break;
                }
            }
//            if (!contains && additional.size() == 0) {
//                throw new ValidatorException(CodeUtil.FAIL, "结算单经办人和销售合同规定经办人不一致需要上传说明附件！");
//            }
            //解除原未签署结算单关联，生成新的结算单
//            List<FileStorageDO> fileStorageDOS3 = fileService.findByBusinessId(settlementBasicInfo.getId(), FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE.getCode());
//            for (FileStorageDO fileStorageDO:fileStorageDOS3) {
//                fileService.updateBusinessId(fileStorageDO.getId(),null);
//            }
            //模板中填充数据
//            File file = inputData(settlementBasicInfo);
//            FileStorageDO fileStorage = FileStorageUtil.createFileStorage3(settlementBasicInfo.getId()+"",FileTypeEnum.SETTLEMENT_UPSTREAM_UNSIGNED_FILE,file.getName(),".pdf");
//            fileStorage.setBusinessId(settlementBasicInfo.getId());
//            fileService.save(fileStorage);
        }
        //生成新的上游结算单
        return settlementBasicInfo;
    }

    @Override
    public void doSignCallBackByQuery(String contractId, String[] fdds) {
        Long settlementBasicInfoId = Long.valueOf(fdds[1]);
        String taskId = fdds[2];

        SettlementElectronicInfo settlementElectronicInfo = settlementElectronicInfoService.getOne(new QueryWrapper<SettlementElectronicInfo>().eq("c_settlement_basic_info_id", settlementBasicInfoId).orderByDesc("gmt_create").last("LIMIT 1"));
        //合同下载
        String contDownUrl = ElectronicSignatureUtil.downloadContract(contractId);
        List<FileStorageDO> fileStorageDOS3 = fileService.findByBusinessId(Long.valueOf(fdds[1]), FileTypeEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE.getCode());
        if (CollectionUtil.isNotEmpty(fileStorageDOS3)) {
            fileService.removeBatchByIds(fileStorageDOS3);
        }
        FileStorageDO contractSupplementFile = fileService.addFileStorageWithBelongAndName(fdds[1], FileTypeEnum.SETTLEMENT_UPSTREAM_SIGNED_FILE, contDownUrl);
        if (contractSupplementFile != null && contractSupplementFile.getId() != null) {
            fileService.updateBusinessId(contractSupplementFile.getId(), settlementBasicInfoId);
        }
        //合同归档
        ElectronicSignatureUtil.contractFiled(contractId);
        //电子文件签署线上出证下载
        String reportDownUrl = ElectronicSignatureUtil.complianceContractReport(contractId);
        List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(Long.valueOf(fdds[1]), FileTypeEnum.SETTLEMENT_CONTRACT_REPORT.getCode());
        if (CollectionUtil.isNotEmpty(fileStorageDOS)) {
            fileService.removeBatchByIds(fileStorageDOS);
        }
        FileStorageDO contractSupplementReportFile = fileService.addFileStorageWithBelongAndName(fdds[1], FileTypeEnum.SETTLEMENT_CONTRACT_REPORT, reportDownUrl);
        if (contractSupplementReportFile != null && contractSupplementReportFile.getId() != null) {
            fileService.updateBusinessId(contractSupplementReportFile.getId(), settlementBasicInfoId);
        }
        //获取最新签署信息，更新签署状态
        settlementElectronicInfo.setSignStatus(1);
        settlementElectronicInfoService.updateById(settlementElectronicInfo);
        //签署后流程
//        settlementElectronicInfoService.sign(settlementElectronicInfo, taskId);
    }

    @Override
    public Object doBusinessHistoryView(Long businessKey, String businessType) {
        String url = doBusinessHistoryView + "?businessKey=" + businessKey + "&businessType=" + businessType;
        JSONObject response = restTemplate.getForObject(url, JSONObject.class);
        if (response.get("code").equals("500")) {
            throw new BusinessException(CodeUtil.FAIL, response.get("msg").toString());
        }
        List<BusinessHistoricDetailVo> list = (List<BusinessHistoricDetailVo>) response.get("data");
        List<BusinessHistoricDetailVo> resultList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Object o : list) {
                String jsonString = JSONObject.toJSONString(o);
                //将json转成需要的对象
                BusinessHistoricDetailVo businessHistoricDetailVo = JSONObject.parseObject(jsonString, BusinessHistoricDetailVo.class);
                BusinessProcessingLogVo businessProcessingLogVo = businessHistoricDetailVo.getBusinessProcessingLogVo();
                if (businessProcessingLogVo.getAssigneeName() == null || businessProcessingLogVo.getAssigneeName().equals("供应商")) {
                    resultList.add(businessHistoricDetailVo);
                }
            }
        }
        return resultList;
    }

    private TableRenderData makeGoddsList(List<SettlementGoodsInfo> settlementGoodsInfos, Map<String, Object> dataMap) {
        int number = 0;
        BigDecimal sum = new BigDecimal("0.0000");
        BigDecimal sumPrice = new BigDecimal("0.00");

        Tables.TableBuilder tableBuilder = Tables.ofA4MediumWidth();

        BorderStyle borderStyle = new BorderStyle();
        borderStyle.setSize(5);
        borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);

        String supplierName = (String) dataMap.get("supplierName");

        RowRenderData header0 = Rows.of("供货单位：", null, supplierName, null, null, null, null, null, null)
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();

        tableBuilder.addRow(header0);

        String contractNumber = (String) dataMap.get("contractNumber");

        RowRenderData header1 = Rows.of("合同编号：", null, contractNumber, null, null, null, null, null, null)
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();

        tableBuilder.addRow(header1);

        String settlementDate = (String) dataMap.get("settlementDate");

        RowRenderData header2 = Rows.of("结算日期：", null, settlementDate, null, null, null, null, null, null)
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();

        tableBuilder.addRow(header2);

        RowRenderData header = Rows.of("序号", "名称", "厂家", "型号", "材质", "单位", "数量", "结算单价", "结算金额")
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();

        tableBuilder.addRow(header);
        int indexNumber = 1;

        for (SettlementGoodsInfo settlementGoodsInfo : settlementGoodsInfos) {
            CAcceptanceGoodsInfo acceptanceGoodsInfo = icAcceptanceGoodsInfoService.getById(settlementGoodsInfo.getAcceptanceGoodsInfoId());
            number = number + 1;
            sum = sum.add(acceptanceGoodsInfo.getGoodsQuantity());
            sumPrice = sumPrice.add(settlementGoodsInfo.getPurchaseTotalPrice().setScale(2, RoundingMode.HALF_UP));

            RowRenderData data = Rows.of(indexNumber + "", acceptanceGoodsInfo.getGoodsName(), acceptanceGoodsInfo.getGoodsFactory()
                            , acceptanceGoodsInfo.getGoodsType(), acceptanceGoodsInfo.getGoodsMaterial(), acceptanceGoodsInfo.getGoodsUnit()
                            , acceptanceGoodsInfo.getGoodsQuantity().toString(), settlementGoodsInfo.getPurchasePrice().setScale(2, RoundingMode.HALF_UP).toString()
                            , settlementGoodsInfo.getPurchaseTotalPrice().setScale(2, RoundingMode.HALF_UP).toString())
                    .center()
                    .textFontFamily("宋体")
                    .textFontSize(10)
                    .create();
            tableBuilder.addRow(data);
            indexNumber++;
        }

        RowRenderData foot = Rows.of("合计", null, null, null, null, null, sum.toString(), null, sumPrice.toString())
                .center()
                .textFontFamily("宋体")
                .textFontSize(10)
                .create();

        tableBuilder.addRow(foot);

        MergeCellRule rule = MergeCellRule.builder().map(MergeCellRule.Grid.of(0, 0), MergeCellRule.Grid.of(0, 1))
                .map(MergeCellRule.Grid.of(0, 2), MergeCellRule.Grid.of(0, 8))
                .map(MergeCellRule.Grid.of(1, 0), MergeCellRule.Grid.of(1, 1))
                .map(MergeCellRule.Grid.of(1, 2), MergeCellRule.Grid.of(1, 8))
                .map(MergeCellRule.Grid.of(2, 0), MergeCellRule.Grid.of(2, 1))
                .map(MergeCellRule.Grid.of(2, 2), MergeCellRule.Grid.of(2, 8))
                .build();

        tableBuilder.mergeRule(rule);

        int[] colWidthsPercent = {10, 15, 15, 10, 10, 10, 10, 10, 10};


        TableRenderData goodsTable = tableBuilder.center().percentWidth("100%", colWidthsPercent).border(borderStyle).create();
        return goodsTable;
    }
}
