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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.component.util.onlineConverter.OfficeConverterUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.PurchContractStatusDict;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.ProjectInformation;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.purchcontractmanagement.vo.PurchContractApprovalVo;
import com.sunxung.factoring.entity.salescontractmanagement.*;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.sys.UserDO;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.entity.tradingPlatform.TradingPlatformInvoiceInfo;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractApprovalMapper;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.IProjectInformationService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.salescontractmanagement.*;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
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 com.sunxung.factoring.service.tradingPlatform.TradingPlatformInvoiceInfoService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 采购合同审批service实现类
 * @Author : JiaYf
 * @Date: 2021-09-18 15:11
 */
@Service("purch_contract_approvalService")
public class PurchContractApprovalServiceImpl extends ServiceImpl<PurchContractApprovalMapper, PurchContractApproval>
        implements PurchContractApprovalService {

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private PurchContractReplenishInfoService purchContractReplenishInfoService;

    @Autowired
    private IPurchContractApprovalSettlePaymentService approvalSettlePaymentService;

    @Autowired
    private PurchContractQualityAcceptService purchContractQualityAcceptService;

    @Autowired
    private PurchContractDeliverClauseService purchContractDeliverClauseService;

    @Autowired
    private IPurchContractApprovalSettleCycleService approvalSettleCycleService;

    @Autowired
    private IPurchContractNeedUserRelService purchContractNeedUserRelService;

    @Autowired
    private IPurchContractApprovalVatInfoService approvalVatInfoService;

    @Autowired
    private PurchContractOtherClauseService purchContractOtherClauseService;

    @Autowired
    private PurchContractGoodsInfoService purchContractGoodsInfoService;

    @Autowired
    private ISalesContractSupplementGoodsInfoService salesContractSupplementGoodsInfoService;

    @Autowired
    private SalesContractGoodsInfoService salesContractGoodsInfoService;

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;

    @Autowired
    private SalesContractApprovalService salesContractApprovalService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private PurchContractElectronicInfoService purchContractElectronicInfoService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IUploadPurchContractService uploadPurchContractService;

    @Autowired
    private IUploadPurchContractSignerService uploadPurchContractSignerService;

    @Autowired
    private BusinessAssigneeService assigneeService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Resource(name = "projectInformationService")
    private IProjectInformationService projectInformationService;

    @Autowired
    private UserService userService;

    @Autowired
    private CUserService cUserService;

    @Resource(name = "SupplierInfoService")
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private TradingPlatformInvoiceInfoService tradingPlatformInvoiceInfoService;

    @Override
    public PurchContractApprovalVo getView(Long id) {

        PurchContractApproval purchContractApproval = baseMapper.selectById(id);
        if (purchContractApproval == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同审批信息");
        }
        PurchContractApprovalVo purchContractApprovalVo = new PurchContractApprovalVo();

        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(purchContractApproval.getId())
                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE_view)
                .build();
        //只有一个文件
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        FileStorage contractFile = null;
        if (CollectionUtil.isNotEmpty(files)) {
            contractFile = files.get(0);
        }

        purchContractApproval.setFileStorage(contractFile);

        List<UploadPurchContract> uploadPurchContracts = uploadPurchContractService.lambdaQuery().eq(UploadPurchContract::getPurchContractApprovalId, id).list();
        uploadPurchContracts.forEach(r -> {
            AttachmentDto attachmentDtoUpload = AttachmentDto.builder()
                    .setEntityId(r.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_UPLOAD_CONTRACT_FILE)
                    .build();
            //只有一个文件
            List<FileStorage> fileStorages = sysAttachmentRefService.getFiles(attachmentDtoUpload);
            FileStorage fileStorage;
            if (CollectionUtil.isNotEmpty(fileStorages)) {
                fileStorage = fileStorages.get(0);
            } else {
                throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
            }

            r.setFileStorage(fileStorage);
            List<UploadPurchContractSigner> uploadPurchContractSigners = uploadPurchContractSignerService.lambdaQuery().eq(UploadPurchContractSigner::getUploadPurchContractId, r.getId()).list();
            r.setUploadPurchContractSigners(uploadPurchContractSigners);
        });

        //获取贸易平台
        PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.getById(purchContractApproval.getPurchContractBasicInfoId());
        PurchContractManagement purchContractManagement = purchContractService
                .lambdaQuery().eq(PurchContractManagement::getId, purchContractBasicInfo.getPurchContractManagementId()).one();
        if (purchContractManagement != null) {
            Platform platform = platformService.getById(purchContractManagement.getTradingPlatformId());
            purchContractApprovalVo.setPlatform(platform);
            purchContractApproval.setPlatform(platform);
        }

        purchContractApproval.setUploadPurchContracts(uploadPurchContracts);
        purchContractApprovalVo.setPurchContractApproval(purchContractApproval);

        //需方收货人（该业务对应的供应商用户的项目经理）
        //获取需方收货人
        List<PurchContractNeedUserRel> userRels = purchContractNeedUserRelService.lambdaQuery()
                .eq(PurchContractNeedUserRel::getPurchContractApprovalId, purchContractApproval.getId()).list();
        List<User> users = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(userRels)) {
            userRels.forEach(c -> {
                User user = new User();
                user.setMobile(c.getMobile());
                user.setIdCard(c.getIdCard());
                user.setName(c.getName());
                users.add(user);
            });
        }
        purchContractApprovalVo.setUserList(users);


        //根据采购合同审核表ID,获取合同其他信息
        //获取合同补充信息
        PurchContractReplenishInfo replenishInfo = purchContractReplenishInfoService
                .lambdaQuery().eq(PurchContractReplenishInfo::getPurchContractApprovalId, purchContractApproval.getId()).one();
        replenishInfo.setContractName(purchContractBasicInfo.getContractName());
        replenishInfo.setContractNumber(purchContractBasicInfo.getContractNumber());
        purchContractApprovalVo.setPurchContractReplenishInfo(replenishInfo);
        //获取质量与验收
        PurchContractQualityAccept qualityAccept = purchContractQualityAcceptService
                .lambdaQuery().eq(PurchContractQualityAccept::getPurchContractApprovalId, purchContractApproval.getId()).one();
        purchContractApprovalVo.setPurchContractQualityAccept(qualityAccept);

        //结算与付款
        PurchContractApprovalSettlePayment approvalSettlePayment = approvalSettlePaymentService.lambdaQuery()
                .eq(PurchContractApprovalSettlePayment::getPurchContractApprovalId, purchContractApproval.getId()).one();
        purchContractApprovalVo.setApprovalSettlePayment(approvalSettlePayment);

        //获取交货规定
        PurchContractDeliverClause deliverClause = purchContractDeliverClauseService
                .lambdaQuery().eq(PurchContractDeliverClause::getPurchContractApprovalId, purchContractApproval.getId()).one();
        purchContractApprovalVo.setPurchContractDeliverClause(deliverClause);

        //获取结算
        PurchContractApprovalSettleCycle settleCycle = approvalSettleCycleService.lambdaQuery()
                .eq(PurchContractApprovalSettleCycle::getPurchContractApprovalId, purchContractApproval.getId()).one();
        purchContractApprovalVo.setApprovalSettleCycle(settleCycle);

        //增值税要求
        PurchContractApprovalVatInfo approvalVatInfo = approvalVatInfoService.lambdaQuery()
                .eq(PurchContractApprovalVatInfo::getPurchContractApprovalId, purchContractApproval.getId()).one();
        purchContractApprovalVo.setApprovalVatInfo(approvalVatInfo);

        //获取其他条款
        List<PurchContractOtherClause> otherClauseList = purchContractOtherClauseService
                .lambdaQuery().eq(PurchContractOtherClause::getPurchcontractApprovalId, purchContractApproval.getId()).list();
        purchContractApprovalVo.setPurchContractOtherClause(otherClauseList);

        //获取供应商
        SupplierInfo supplierInfo = supplierInfoService.get(purchContractManagement.getSupplierId());
        Enterprise supplier = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        purchContractApprovalVo.setSupplier(supplier);

        return purchContractApprovalVo;
    }

    @Override
    public PurchContractApproval getLatestPurchContractApproval(Long id, Integer visible) {
        return getOne(new QueryWrapper<PurchContractApproval>().eq("purch_contract_basic_info_id", id)
                .eq("visible", visible).orderByDesc("id").last("LIMIT 1"));
    }


    @Override
    public PurchContractApprovalVo getDetail(Long id) {
        PurchContractApprovalVo purchContractApprovalVo = new PurchContractApprovalVo();
        PurchContractManagement purchContractManagement = purchContractService.getById(id);
        PurchContractBasicInfo purch = purchContractBasicInfoService
                .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, id).one();
        purchContractApprovalVo.setPurchContractBasicInfo(purch);

        //供应商信息
        SupplierInfo supplier = supplierInfoService.get(purchContractManagement.getSupplierId());
        Enterprise supplierInfo = enterpriseService.getById(supplier.getcEnterpriseId());
        purchContractApprovalVo.setSupplier(supplierInfo);

        PurchContractApproval purchContractApproval = this.getLatestPurchContractApproval(purch.getId(), 0);
        if (purchContractApproval == null) {
            purchContractApproval = new PurchContractApproval();
            purchContractApproval.setUpload(0);
        }
        //贸易平台的信息
        Platform platform = platformService.getById(purch.getTradingPlatformId());
        purchContractApproval.setPlatform(platform);
        purchContractApproval.setSupplier(supplierInfo);
        purchContractApprovalVo.setPurchContractApproval(purchContractApproval);
        purchContractApprovalVo.setPlatform(platform);


        //补充信息
        PurchContractReplenishInfo replenishInfo = new PurchContractReplenishInfo();

        //需方收货人（该业务对应的供应商用户的项目经理）
        List<User> userList = new ArrayList<>();
        UserDO cuser = cUserService.getById(supplier.getSysUserId());
        User manager = userService.get(cuser.getProjectManager());
        userList.add(manager);
        purchContractApprovalVo.setUserList(userList);


        if (purchContractApproval.getId() != null) {
            AttachmentDto attachmentDto = AttachmentDto.builder()
                    .setEntityId(purchContractApproval.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE_view)
                    .build();
            //只有一个文件
            List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
            FileStorage signFile = null;
            if (CollectionUtil.isNotEmpty(files)) {
                signFile = files.get(0);
            }
            purchContractApproval.setFileStorage(signFile);
        } else {
            //首次 拉取 销售合同审核页面的结算周期方式及结算周期字段
            CSalesContract salesContract = salesContractService.lambdaQuery()
                    .eq(CSalesContract::getBusinessNumber, purchContractManagement.getBusinessNumber()).one();
            CSalesContractBasicInfo salesContractBasicInfo = salesContractBasicInfoService.lambdaQuery()
                    .eq(CSalesContractBasicInfo::getcSalesContractManagementId, salesContract.getId()).one();
            SalesContractApproval salesContractApproval = salesContractApprovalService
                    .lambdaQuery().eq(SalesContractApproval::getcSalesContractBasicInfoId, salesContractBasicInfo.getId())
                    .orderByDesc(SalesContractApproval::getGmtCreate).last("limit 1").one();
            PurchContractApprovalSettleCycle settleCycle = new PurchContractApprovalSettleCycle();
            settleCycle.setSettleCycleMethod(salesContractApproval.getSettleCycleMethod());
            settleCycle.setSettleCycle(salesContractApproval.getSettleCycle());
            settleCycle.setPaymentNode(salesContractApproval.getPaymentNode());
            settleCycle.setPaymentTerm(salesContractApproval.getPaymentTerm());
            purchContractApprovalVo.setApprovalSettleCycle(settleCycle);

            //首次 增值税从贸易平台拉取
            PurchContractApprovalVatInfo approvalVatInfo = new PurchContractApprovalVatInfo();
            purchContractApprovalVo.setApprovalVatInfo(approvalVatInfo);
            TradingPlatformInvoiceInfo platformInvoiceInfo = tradingPlatformInvoiceInfoService.findByPlatformId(platform.getId());
            approvalVatInfo.setOpenBank(platformInvoiceInfo.getBankAccount());
            approvalVatInfo.setReceiptAccount(platformInvoiceInfo.getAccount());
            purchContractApprovalVo.setApprovalVatInfo(approvalVatInfo);

        }


        //根据采购合同审核表ID,获取合同其他信息
        if (purchContractApproval != null && purchContractApproval.getId() != null) {
            //获取合同补充信息
            replenishInfo = purchContractReplenishInfoService
                    .lambdaQuery().eq(PurchContractReplenishInfo::getPurchContractApprovalId, purchContractApproval.getId()).one();
            //获取质量与验收
            PurchContractQualityAccept qualityAccept = purchContractQualityAcceptService
                    .lambdaQuery().eq(PurchContractQualityAccept::getPurchContractApprovalId, purchContractApproval.getId()).one();
            purchContractApprovalVo.setPurchContractQualityAccept(qualityAccept);

            //结算与付款
            PurchContractApprovalSettlePayment approvalSettlePayment = approvalSettlePaymentService.lambdaQuery()
                    .eq(PurchContractApprovalSettlePayment::getPurchContractApprovalId, purchContractApproval.getId()).one();
            purchContractApprovalVo.setApprovalSettlePayment(approvalSettlePayment);

            //获取交货规定
            PurchContractDeliverClause deliverClause = purchContractDeliverClauseService
                    .lambdaQuery().eq(PurchContractDeliverClause::getPurchContractApprovalId, purchContractApproval.getId()).one();
            purchContractApprovalVo.setPurchContractDeliverClause(deliverClause);

            //获取结算
            PurchContractApprovalSettleCycle settleCycle = approvalSettleCycleService.lambdaQuery()
                    .eq(PurchContractApprovalSettleCycle::getPurchContractApprovalId, purchContractApproval.getId()).one();
            purchContractApprovalVo.setApprovalSettleCycle(settleCycle);

            //获取需方收货人
            List<PurchContractNeedUserRel> userRels = purchContractNeedUserRelService.lambdaQuery()
                    .eq(PurchContractNeedUserRel::getPurchContractApprovalId, purchContractApproval.getId()).list();
            List<User> users = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(userRels)) {
                userRels.forEach(c -> {
                    User user = new User();
                    user.setMobile(c.getMobile());
                    user.setIdCard(c.getIdCard());
                    user.setName(c.getName());
                    users.add(user);
                    purchContractApprovalVo.setUserList(users);
                });
            }


            //增值税要求
            PurchContractApprovalVatInfo approvalVatInfo = approvalVatInfoService.lambdaQuery()
                    .eq(PurchContractApprovalVatInfo::getPurchContractApprovalId, purchContractApproval.getId()).one();
            purchContractApprovalVo.setApprovalVatInfo(approvalVatInfo);

            //获取其他条款
            List<PurchContractOtherClause> otherClauseList = purchContractOtherClauseService
                    .lambdaQuery().eq(PurchContractOtherClause::getPurchcontractApprovalId, purchContractApproval.getId()).list();
            purchContractApprovalVo.setPurchContractOtherClause(otherClauseList);


            //上传的合同
            if (purchContractApproval.getUpload() != null && purchContractApproval.getUpload().equals(1)) {
                List<UploadPurchContract> list = uploadPurchContractService
                        .lambdaQuery().eq(UploadPurchContract::getPurchContractApprovalId, purchContractApproval.getId()).list();
                if (CollectionUtil.isNotEmpty(list)) {
                    for (UploadPurchContract uploadPurchContract : list) {


                        AttachmentDto attachmentDtoUpload = AttachmentDto.builder()
                                .setEntityId(uploadPurchContract.getId())
                                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_UPLOAD_CONTRACT_FILE)
                                .build();
//                        List<Long> fileIds = new ArrayList<>();
//                        fileIds.add(uploadPurchContract.getFileId());
//                        sysAttachmentRefService.saveRef(fileIds, attachmentDtoUpload);

                        //只有一个文件
                        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDtoUpload);
                        FileStorage fileStorage = null;
                        if (CollectionUtil.isNotEmpty(files)) {
                            fileStorage = files.get(0);
                        }
//                        else {
//                            throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
//                        }
                        uploadPurchContract.setFileStorage(fileStorage);
                        List<UploadPurchContractSigner> uploadPurchContractSigners = uploadPurchContractSignerService.lambdaQuery().eq(UploadPurchContractSigner::getUploadPurchContractId, uploadPurchContract.getId()).list();
                        uploadPurchContract.setUploadPurchContractSigners(uploadPurchContractSigners);
                    }
                }
                purchContractApprovalVo.getPurchContractApproval().setUploadPurchContracts(list);
            }
        }
        replenishInfo.setContractName(purch.getContractName());
        replenishInfo.setContractNumber(purch.getContractNumber());

        purchContractApprovalVo.setPurchContractReplenishInfo(replenishInfo);
        purchContractApprovalVo.setPurchContractApproval(purchContractApproval);

        return purchContractApprovalVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(PurchContractApprovalVo purchContractApprovalVo) throws IOException {

        if (purchContractApprovalVo == null || purchContractApprovalVo.getBusinessKey() == null) {
            throw new ValidatorException(CodeUtil.FAIL, "审核信息或者业务id不能为空");
        }

        PurchContractManagement purchContractManagement = purchContractService.getById(purchContractApprovalVo.getBusinessKey());
        if (purchContractManagement == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同管理信息");
        }

        PurchContractBasicInfo purch = purchContractBasicInfoService.getOne(new QueryWrapper<PurchContractBasicInfo>()
                .eq("c_purch_contract_management_id", purchContractApprovalVo.getBusinessKey()));
        if (purch == null) {
            throw new BusinessException(CodeUtil.FAIL, "获取不到对应采购合同信息");
        }
        PurchContractApproval purchContractApproval = purchContractApprovalVo.getPurchContractApproval();

        if (purchContractApproval != null) {

            //删除之前的审批信息
            PurchContractApproval oldApproval = getLatestPurchContractApproval(purch.getId(), 0);

            if (oldApproval != null) {
                //删除之前上传的合同信息
                List<UploadPurchContract> oldUploadContracts = uploadPurchContractService.lambdaQuery().eq(UploadPurchContract::getPurchContractApprovalId, oldApproval.getId()).list();
                if (CollectionUtil.isNotEmpty(oldUploadContracts)) {
                    //删除之前的上传合同签署信息
                    for (UploadPurchContract oldUploadContract : oldUploadContracts) {
                        uploadPurchContractSignerService.lambdaUpdate().eq(UploadPurchContractSigner::getUploadPurchContractId, oldUploadContract.getId()).remove();
                    }
                    uploadPurchContractService.removeByIds(oldUploadContracts.stream().map(uploadPurchContract -> uploadPurchContract.getId()).collect(Collectors.toSet()));
                }
                baseMapper.deleteById(oldApproval.getId());

                purchContractReplenishInfoService.remove(new QueryWrapper<PurchContractReplenishInfo>().eq("purch_contract_approval_id", oldApproval.getId()));
                purchContractQualityAcceptService.remove(new QueryWrapper<PurchContractQualityAccept>().eq("purch_contract_approval_id", oldApproval.getId()));
                approvalSettlePaymentService.remove(new QueryWrapper<PurchContractApprovalSettlePayment>().eq("purch_contract_approval_id", oldApproval.getId()));
                purchContractDeliverClauseService.remove(new QueryWrapper<PurchContractDeliverClause>().eq("purch_contract_approval_id", oldApproval.getId()));
                approvalSettleCycleService.remove(new QueryWrapper<PurchContractApprovalSettleCycle>().eq("purch_contract_approval_id", oldApproval.getId()));
                purchContractNeedUserRelService.remove(new QueryWrapper<PurchContractNeedUserRel>().eq("purch_contract_approval_id", oldApproval.getId()));
                approvalVatInfoService.remove(new QueryWrapper<PurchContractApprovalVatInfo>().eq("purch_contract_approval_id", oldApproval.getId()));
                purchContractOtherClauseService.remove(new QueryWrapper<PurchContractOtherClause>().eq("purch_contract_approval_id", oldApproval.getId()));
            }

            //保存新的审批信息
            purchContractApproval.setAuditorId(ThreadLocalUtil.getUserId());
            purchContractApproval.setPurchContractBasicInfoId(purch.getId());
            purchContractApproval.setVisible(purchContractApprovalVo.getVisible());
            baseMapper.insert(purchContractApproval);
            //保存新的上传的合同信息
            List<UploadPurchContract> uploadPurchContracts = purchContractApproval.getUploadPurchContracts();
            if (CollectionUtil.isNotEmpty(uploadPurchContracts)) {
                Set<String> set = uploadPurchContracts.stream().map(r -> r.getContractName()).collect(Collectors.toSet());
                boolean anyMatch = uploadPurchContracts.stream().anyMatch(r -> r.getContractName().equals(purch.getContractName()));
                if (set.size() < uploadPurchContracts.size() || anyMatch) {
                    throw new ValidatorException(CodeUtil.FAIL, "上传的合同名称不能重复!");
                }
                for (UploadPurchContract uploadPurchContract : uploadPurchContracts) {
                    uploadPurchContract.setPurchContractApprovalId(purchContractApproval.getId());
                    uploadPurchContractService.save(uploadPurchContract);
                    Long fileId = uploadPurchContract.getFileId();
                    if (fileId != null) {

                        FileStorage fileStorage = fileStorageService.get(fileId);
                        //校验上传模板中的关键字
                        String text;
                        try {
                            // 创建PDF文档对象
                            PDDocument document = PDDocument.load(new File(fileStorage.getAbsolutePath()));
                            // 获取PDF文档中的文本内容
                            text = new PDFTextStripper().getText(document);
                            // 关闭PDF文档
                            document.close();
                        } catch (IOException e) {
                            throw new ValidatorException(CodeUtil.FAIL, "pdf解析失败！");
                        }
                        if (!text.contains("gys")) {
                            throw new ValidatorException(CodeUtil.FAIL, "上传的《" + fileStorage.getOriginalName() + "》中签章位置上缺少关键字：gys");
                        }
                        if (!text.contains("xf")) {
                            throw new ValidatorException(CodeUtil.FAIL, "上传的《" + fileStorage.getOriginalName() + "》中签章位置上缺少关键字：xf");
                        }

                        AttachmentDto attachmentDto = AttachmentDto.builder().setEntityId(uploadPurchContract.getId())
                                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_UPLOAD_CONTRACT_FILE).build();
                        List<Long> fileIds = new ArrayList<>();
                        fileIds.add(fileId);
                        sysAttachmentRefService.saveRef(fileIds, attachmentDto);
                    }
                    if (CollectionUtil.isNotEmpty(uploadPurchContract.getUploadPurchContractSigners())) {
                        uploadPurchContract.getUploadPurchContractSigners().forEach(c -> {
                            c.setUploadPurchContractId(uploadPurchContract.getId());
                            uploadPurchContractSignerService.save(c);
                        });
                    }

                }
            }
        }


        //添加合同补充信息
        if (purchContractApprovalVo.getPurchContractReplenishInfo() != null) {
            PurchContractReplenishInfo replenishInfo = purchContractApprovalVo.getPurchContractReplenishInfo();
            replenishInfo.setPurchContractApprovalId(purchContractApproval.getId());
            purchContractReplenishInfoService.save(replenishInfo);
        }


        //添加质量与验收
        if (purchContractApprovalVo.getPurchContractQualityAccept() != null) {
            PurchContractQualityAccept qualityAccept = purchContractApprovalVo.getPurchContractQualityAccept();
            qualityAccept.setPurchContractApprovalId(purchContractApproval.getId());
            purchContractQualityAcceptService.save(qualityAccept);
        }

        //结算与付款
        if (purchContractApprovalVo.getApprovalSettlePayment() != null) {
            PurchContractApprovalSettlePayment approvalSettlePayment = purchContractApprovalVo.getApprovalSettlePayment();
            approvalSettlePayment.setPurchContractApprovalId(purchContractApproval.getId());
            approvalSettlePaymentService.save(approvalSettlePayment);
        }

        //添加交货规定
        if (purchContractApprovalVo.getPurchContractDeliverClause() != null) {
            PurchContractDeliverClause deliverClause = purchContractApprovalVo.getPurchContractDeliverClause();
            deliverClause.setPurchContractApprovalId(purchContractApproval.getId());
            purchContractDeliverClauseService.save(deliverClause);
        }

        //结算周期
        if (purchContractApprovalVo.getApprovalSettleCycle() != null) {
            PurchContractApprovalSettleCycle approvalSettleCycle = purchContractApprovalVo.getApprovalSettleCycle();
            approvalSettleCycle.setPurchContractApprovalId(purchContractApproval.getId());
            approvalSettleCycleService.save(approvalSettleCycle);
        }

        //需方收货人
        if (CollectionUtil.isNotEmpty(purchContractApprovalVo.getUserList())) {
            for (User user : purchContractApprovalVo.getUserList()) {
                PurchContractNeedUserRel needUserRel = new PurchContractNeedUserRel();
                needUserRel.setName(user.getName());
                needUserRel.setIdCard(user.getIdCard());
                needUserRel.setMobile(user.getMobile());
                needUserRel.setPurchContractApprovalId(purchContractApproval.getId());
                needUserRel.setSysUserId(user.getId());
                purchContractNeedUserRelService.save(needUserRel);
            }
        }

        //增值税要求
        if (purchContractApprovalVo.getApprovalVatInfo() != null) {
            PurchContractApprovalVatInfo approvalVatInfo = purchContractApprovalVo.getApprovalVatInfo();
            approvalVatInfo.setPurchContractApprovalId(purchContractApproval.getId());
            approvalVatInfoService.save(approvalVatInfo);
        }

        //添加其他条款
        if (purchContractApprovalVo.getPurchContractOtherClause() != null && purchContractApprovalVo.getPurchContractOtherClause().size() > 0) {
            int i = 0;
            for (PurchContractOtherClause otherClause : purchContractApprovalVo.getPurchContractOtherClause()) {
                i++;
                otherClause.setPurchcontractApprovalId(purchContractApproval.getId());
                otherClause.setSerialNumber(i);
            }
            purchContractOtherClauseService.saveBatch(purchContractApprovalVo.getPurchContractOtherClause());
        }
        if (purchContractApprovalVo.getVisible().equals(1)) {
            if (purchContractApproval.getUpload() != null && purchContractApproval.getUpload() == 1) {
                List<UploadPurchContract> uploadPurchContracts = purchContractApprovalVo.getPurchContractApproval().getUploadPurchContracts();
                if (CollectionUtil.isEmpty(uploadPurchContracts)) {
                    throw new ValidatorException(CodeUtil.FAIL, "请上传合同文件！！！");
                }
            }
            //添加历史
            Map<String, Object> procVariables = new HashMap<>(1);

            Dictionary firstApprovalDict = dictService.getByCode(PurchContractStatusDict.ChildEnum.FIRST_APPROVAL.getCode());
            Dictionary overRuleDict = dictService.getByCode(PurchContractStatusDict.ChildEnum.OVERRULE.getCode());
            if (firstApprovalDict == null || overRuleDict == null) {
                throw new BusinessException(CodeUtil.FAIL, "采购合同状态字典项不能为空");
            }

            String result = ConstantConversionUtil.processApprovalResult.get(purchContractApproval.getApprovalConclusion());
            if (purchContractApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
                //释放销售合同
                salesContractService.lambdaUpdate().eq(CSalesContract::getBusinessNumber, purchContractManagement.getBusinessNumber())
                        .set(CSalesContract::getPurch, 0)
                        .update();

                //如果审核结论为驳回 释放销售合同的货物
                List<PurchContractGoodsInfo> purchContractGoodsInfoList = purchContractGoodsInfoService
                        .lambdaQuery().eq(PurchContractGoodsInfo::getPurchContractBasicInfoId, purch.getId()).list();
                if (CollectionUtil.isNotEmpty(purchContractGoodsInfoList)) {
                    purchContractGoodsInfoList.forEach(purchContractGoodsInfo -> {
                        if (purchContractGoodsInfo.getSupplement()) {
                            //变更货物
                            SalesContractSupplementGoodsInfo salesContractSupplementGoods =
                                    salesContractSupplementGoodsInfoService.getById(purchContractGoodsInfo.getSalesContractGoodsInfoId());
                            salesContractSupplementGoodsInfoService.lambdaUpdate().eq(SalesContractSupplementGoodsInfo::getId, salesContractSupplementGoods.getId())
                                    .set(SalesContractSupplementGoodsInfo::getOccupy, 0).update();
                        } else {
                            CSalesContractGoodsInfo salesContractGoods = salesContractGoodsInfoService.getById(purchContractGoodsInfo.getSalesContractGoodsInfoId());
                            salesContractGoodsInfoService.lambdaUpdate().eq(CSalesContractGoodsInfo::getId, salesContractGoods.getId())
                                    .set(CSalesContractGoodsInfo::getOccupy, 0).update();
                        }
                    });
                }
            }

            //供应商签署
            User admin = userService.getByLoginName("admin");

            procVariables.put(ConstantUtil.PURCH_CONTRACT_CONFIRM + ConstantUtil.ASSIGNEE, admin.getId());
            procVariables.put("result", result);

            Map<String, Object> msgVariables = new HashMap<>(2);
            ProjectInformation projectInformation = projectInformationService
                    .lambdaQuery().eq(ProjectInformation::getBusinessNumber, purchContractManagement.getBusinessNumber()).one();
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, projectInformation.getProjectName());
            msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                    "业务编号为" + purchContractManagement.getBusinessNumber() + "”的项目已inOut“"
                            + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.PURCH_CONTRACT) + "—formBusiness”阶段，");
            Boolean success = flowableService.completeMyTask(purchContractApprovalVo.getTaskId(), purchContractManagement, procVariables, null,
                    purchContractApproval.getId(), msgVariables, ConstantUtil.PURCH_CONTRACT);
            if (success == null || !success) {
                throw new ValidatorException(CodeUtil.FAIL, "采购合同审批出错啦！");
            }
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FileStorage makeContractPdf(PurchContractApprovalVo purchContractApprovalVo, boolean makeContractPdf) {
        if (purchContractApprovalVo.getPurchContractApproval().getApprovalConclusion() != null
                && purchContractApprovalVo.getPurchContractApproval().getApprovalConclusion().equals("pass")
                && purchContractApprovalVo.getPurchContractApproval().getSignMode() != null) {
            PurchContractReplenishInfo purchContractReplenishInfo = purchContractApprovalVo.getPurchContractReplenishInfo();
            if (purchContractReplenishInfo == null || purchContractReplenishInfo.getProjectAmountCategory() == null || StringUtil.isEmpty(purchContractReplenishInfo.getGoodsPriceSettleMethod())) {
                throw new ValidatorException(CodeUtil.FAIL, "合同补充信息不全，请补全！");
            }
            PurchContractQualityAccept purchContractQualityAccept = purchContractApprovalVo.getPurchContractQualityAccept();
            if (purchContractQualityAccept == null || StringUtil.isEmpty(purchContractQualityAccept.getQualityCriteria()) || StringUtil.isEmpty(purchContractQualityAccept.getAcceptCriteria())) {
                throw new ValidatorException(CodeUtil.FAIL, "质量与验收信息不全，请补全！");
            }
            PurchContractDeliverClause purchContractDeliverClause = purchContractApprovalVo.getPurchContractDeliverClause();
            if (purchContractDeliverClause == null
                    || StringUtil.isEmpty(purchContractDeliverClause.getDeliverDate()) || StringUtil.isEmpty(purchContractDeliverClause.getDeliverSite())
                    || StringUtil.isEmpty(purchContractDeliverClause.getDeliverMethod()) || StringUtil.isEmpty(purchContractDeliverClause.getTransportPremium())) {
                throw new ValidatorException(CodeUtil.FAIL, "交货规定信息不全，请补全！");
            }

        }
        try {
            audit(purchContractApprovalVo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PurchContractManagement purchContractManagement = purchContractService.getById(purchContractApprovalVo.getBusinessKey());
        PurchContractBasicInfo purch = purchContractApprovalVo.getPurchContractBasicInfo();
        PurchContractApproval contractApproval = purchContractApprovalVo.getPurchContractApproval();
        if (contractApproval != null && contractApproval.getApprovalConclusion() == null) {
            return null;
        }
        if ((contractApproval != null &&
                contractApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS))
                || contractApproval == null) {
            //贸易平台的信息
            Platform platform = platformService.getById(purch.getTradingPlatformId());
            if (purchContractApprovalVo.getPurchContractReplenishInfo().getProjectAmountCategory() != null && platform.getAuthStatus().equals(1) && platform.isAutoSignStatus() && purchContractApprovalVo.getPurchContractApproval().getSignMode().equals(1)) {
                //制作合同
                File outFile = purchContractElectronicInfoService.makePurchContractDocx(purchContractManagement, purch);
                //将docx转为pdf
                String suffix = FileUtil.getSuffix(outFile.getName());
                String newPath = outFile.getAbsolutePath().replace(suffix, ".pdf");
                File purchContractPdfFile = OfficeConverterUtil.office2Pdf(outFile.getAbsolutePath(), newPath);
                FileStorage fileStorage = new FileStorage(purchContractPdfFile, FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE_view);
                fileStorageService.saveAttachmentRefByFileStorage(fileStorage, FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE_view, contractApproval.getId());
                return fileStorage;
            }
            return null;
        } else if (contractApproval != null &&
                contractApproval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
            return null;
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "审核结论出错！");
        }

    }

}
