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

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.CodeUtil;
import com.sunxung.factoring.component.util.CollectionUtil;
import com.sunxung.factoring.component.util.ConstantConversionUtil;
import com.sunxung.factoring.component.util.ConstantUtil;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.salescontractmanagement.CSalesContractGoodsInfo;
import com.sunxung.factoring.entity.salescontractmanagement.SalesContractSupplementGoodsInfo;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractSupplementApprovalMapper;
import com.sunxung.factoring.service.businessmanagement.BusinessBasicInfoService;
import com.sunxung.factoring.service.customerinformation.CustomerService;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.salescontractmanagement.ISalesContractSupplementGoodsInfoService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractGoodsInfoService;
import com.sunxung.factoring.service.supplier.ISupplierInfoService;
import com.sunxung.factoring.service.sys.DictionaryService;
import com.sunxung.factoring.service.sys.FileStorageService;
import com.sunxung.factoring.service.sys.ISysAttachmentRefService;
import com.sunxung.factoring.service.sys.UserService;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import org.apache.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 java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购合同-变更审核表 服务实现类
 * </p>
 *
 * @author daxian
 * @since 2022-03-14
 */
@Service("purch_contract_change_approvalService")
public class PurchContractSupplementApprovalServiceImpl extends ServiceImpl<PurchContractSupplementApprovalMapper, PurchContractSupplementApproval> implements IPurchContractSupplementApprovalService {


    @Autowired
    PurchContractService purchContractService;

    @Autowired
    CustomerService customerService;

    @Autowired
    BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    FlowableService flowableService;

    @Autowired
    DictionaryService dictService;

    @Autowired
    IPurchContractSupplementInfoService supplementInfoService;

    @Autowired
    private IPurchContractSupplementGoodsInfoService purchContractSupplementGoodsInfoService;

    @Autowired
    private ISalesContractSupplementGoodsInfoService salesContractSupplementGoodsInfoService;

    @Autowired
    private SalesContractGoodsInfoService salesContractGoodsInfoService;

    @Autowired
    IPurchContractSupplementApprovalService supplementApprovalService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IUploadPurchContractSupplementSignerService uploadPurchContractSupplementSignerService;

    @Autowired
    private IUploadPurchSupplementContractService uploadPurchSupplementContractService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IPurchContractSupplementApprovalCommentInfoService purchContractSupplementApprovalCommentInfoService;

    @Autowired
    private UserService userService;

    @Override
    public PurchContractSupplementApproval getView(Long id) {
        PurchContractSupplementApproval purchContractSupplementApproval = supplementApprovalService.getById(id);

        //其他约定
        List<PurchContractSupplementApprovalCommentInfo> commentInfoList = purchContractSupplementApprovalCommentInfoService
                .lambdaQuery().eq(PurchContractSupplementApprovalCommentInfo::getPurchContractSupplementApprovalId, id).list();
        if (CollectionUtil.isNotEmpty(commentInfoList)) {
            List<String> comments = commentInfoList.stream().map(c -> c.getOtherComment()).collect(Collectors.toList());
            purchContractSupplementApproval.setComments(comments);
        }


        //系统制作的文件
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(id)
                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_MAKE_FILE)
                .build();
        //只有一个文件
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        FileStorage signFile = null;
        if (CollectionUtil.isNotEmpty(files)) {
            signFile = files.get(0);
        }
        purchContractSupplementApproval.setFileStorage(signFile);

        List<UploadPurchSupplementContract> uploadPurchSupplementContracts = uploadPurchSupplementContractService.lambdaQuery().eq(UploadPurchSupplementContract::getPurchContractSupplementApprovalId, purchContractSupplementApproval.getId()).list();
        uploadPurchSupplementContracts.forEach(r -> {
            List<UploadPurchContractSupplementSigner> list = uploadPurchContractSupplementSignerService.lambdaQuery().eq(UploadPurchContractSupplementSigner::getUploadPurchContractId, r.getId()).list();
            r.setUploadPurchContractSupplementSignerList(list);
            AttachmentDto attachmentDtoUpload = AttachmentDto.builder()
                    .setEntityId(r.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_SUPPLEMENT_CONTRACT_UPLOAD_CONTRACT_FILE)
                    .build();
            //只有一个文件
            List<FileStorage> fileStorages = sysAttachmentRefService.getFiles(attachmentDtoUpload);
            FileStorage file;
            if (CollectionUtil.isNotEmpty(fileStorages)) {
                file = fileStorages.get(0);
            } else {
                throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
            }
            r.setFileStorage(file);
        });
        purchContractSupplementApproval.setUploadPurchSupplementContracts(uploadPurchSupplementContracts);
        //贸易平台和供应商
        PurchContractSupplementInfo supplementInfo = supplementInfoService.lambdaQuery()
                .eq(PurchContractSupplementInfo::getId, purchContractSupplementApproval.getPurchContractSupplementInfoId()).one();
        PurchContractManagement contractManagement = purchContractService.getById(supplementInfo.getPurchContractManagementId());
        Platform platform = platformService.getById(contractManagement.getTradingPlatformId());
        purchContractSupplementApproval.setPlatform(platform);
        SupplierInfo supplierInfo = supplierInfoService.get(contractManagement.getSupplierId());
        Enterprise supplier = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        purchContractSupplementApproval.setSupplier(supplier);
        return purchContractSupplementApproval;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAudit(PurchContractSupplementApproval approval, Long businessKey, String taskId) {

        User admin = userService.getByLoginName("admin");

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

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

        PurchContractBasicInfo basicInfo = purchContractBasicInfoService.lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, businessKey).one();
        PurchContractSupplementInfo supplementInfo = supplementInfoService.getLastPruchContractSupplementInfoByContractManagementId(purchContractManagement.getId());
        if (supplementInfo == null) {
            throw new BusinessException(CodeUtil.FAIL, "未查到该变更信息");
        }
        //保存变更审批       approval
        approval.setPurchContractSupplementInfoId(supplementInfo.getId());
        supplementApprovalService.save(approval);

        //保存其他约定
        if (CollectionUtil.isNotEmpty(approval.getComments())) {
            approval.getComments().forEach(c->{
                PurchContractSupplementApprovalCommentInfo contractSupplementApprovalCommentInfo = new PurchContractSupplementApprovalCommentInfo();
                contractSupplementApprovalCommentInfo.setPurchContractSupplementApprovalId(approval.getId());
                contractSupplementApprovalCommentInfo.setOtherComment(c);
                purchContractSupplementApprovalCommentInfoService.save(contractSupplementApprovalCommentInfo);
            });
        }

        if (approval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            //制作采购合同补充合同

            FileStorage supplementContract = supplementInfoService.makeContract(approval);
            fileStorageService.saveAttachmentRefByFileStorage(supplementContract, FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_MAKE_FILE, approval.getId());
        }

        Map<String, Object> procVariables = new HashMap<>();
        String result;

        if (approval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_BACK)) {
            result = ConstantConversionUtil.APPROVAL_RESULT_BACK_DISPLAY;

            //驳回时 释放货物
            List<PurchContractSupplementGoodsInfo> supplementGoodsInfos = purchContractSupplementGoodsInfoService
                    .lambdaQuery().eq(PurchContractSupplementGoodsInfo::getPurchContractSupplementInfoId, supplementInfo.getId()).list();
            if (CollectionUtil.isNotEmpty(supplementGoodsInfos)) {
                supplementGoodsInfos.forEach(supplementGoodsInfo -> {
                    if (supplementGoodsInfo.getSupplement()){
                        //变更货物
                        SalesContractSupplementGoodsInfo salesContractSupplementGoods =
                                salesContractSupplementGoodsInfoService.getById(supplementGoodsInfo.getSalesContractGoodsInfoId());
                        salesContractSupplementGoodsInfoService.lambdaUpdate().eq(SalesContractSupplementGoodsInfo::getId,salesContractSupplementGoods.getId())
                                .set(SalesContractSupplementGoodsInfo::getOccupy,0).update();
                    }else {
                        CSalesContractGoodsInfo salesContractGoods = salesContractGoodsInfoService.getById(supplementGoodsInfo.getSalesContractGoodsInfoId());
                        salesContractGoodsInfoService.lambdaUpdate().eq(CSalesContractGoodsInfo::getId,salesContractGoods.getId())
                                .set(CSalesContractGoodsInfo::getOccupy,0).update();
                    }
                });
            }

        } else if (approval.getApprovalConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
                String assigneeKey = ConstantUtil.PURCH_CONTRACT_CHANGE_SIGN_CONFIRM + ConstantUtil.ASSIGNEE;
                result = "线上";
                //供应商签署
                procVariables.put(assigneeKey, admin.getId());
                List<UploadPurchSupplementContract> uploadPurchSupplementContracts = approval.getUploadPurchSupplementContracts();
                if (CollectionUtil.isNotEmpty(uploadPurchSupplementContracts)) {
                    PurchContractBasicInfo purch = purchContractBasicInfoService
                            .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, purchContractManagement.getId()).one();
                    Set<String> set = uploadPurchSupplementContracts.stream().map(r -> r.getContractName()).collect(Collectors.toSet());
                    boolean anyMatch = uploadPurchSupplementContracts.stream().anyMatch(r -> r.getContractName().equals(purch.getContractName()));
                    uploadPurchSupplementContracts.forEach(r -> {
                        List<UploadPurchSupplementContract> oldUploads = uploadPurchSupplementContractService.lambdaQuery().eq(UploadPurchSupplementContract::getContractName, r.getContractName()).list();
                        if (CollectionUtil.isNotEmpty(oldUploads)) {
                            oldUploads.forEach(old -> {
                                PurchContractSupplementApproval oldApproval = supplementApprovalService.getById(old.getPurchContractSupplementApprovalId());
                                PurchContractSupplementInfo oldSupplement = supplementInfoService.getById(oldApproval.getPurchContractSupplementInfoId());
                                if (oldSupplement.getPurchContractManagementId().equals(purchContractManagement.getId())) {
                                    throw new ValidatorException(CodeUtil.FAIL, "上传的合同名称不能和老数据重复!");
                                }
                            });
                        }
                    });
                    if (set.size() < uploadPurchSupplementContracts.size() || anyMatch) {
                        throw new ValidatorException(CodeUtil.FAIL, "上传的合同名称不能重复!");
                    }

                    uploadPurchSupplementContracts.forEach(uploadPurchSupplementContract -> {
                        uploadPurchSupplementContract.setPurchContractSupplementApprovalId(approval.getId());
                        uploadPurchSupplementContractService.save(uploadPurchSupplementContract);

                        FileStorage fileStorage = null;
                        AttachmentDto attachmentDtoUpload = AttachmentDto.builder()
                                .setEntityId(uploadPurchSupplementContract.getId())
                                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_SUPPLEMENT_CONTRACT_UPLOAD_CONTRACT_FILE)
                                .build();
                        List<Long> fileIds = new ArrayList<>();
                        fileIds.add(uploadPurchSupplementContract.getFileId());
                        sysAttachmentRefService.saveRef(fileIds, attachmentDtoUpload);
                        //只有一个文件
                        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDtoUpload);
                        if (CollectionUtil.isNotEmpty(files)) {
                            fileStorage = files.get(0);
                        } else {
                            throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
                        }

                        //校验上传模板中的关键字
                        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");
                        }

                        fileStorageService.saveAttachmentRefByFileStorage(fileStorage, FileModuleDict.ChildEnum.PURCHASE_SUPPLEMENT_CONTRACT_UPLOAD_CONTRACT_FILE, uploadPurchSupplementContract.getId());
                        //保存上传合同的签署人信息
                        Platform platform = platformService.getById(purchContractManagement.getTradingPlatformId());
                        UploadPurchContractSupplementSigner uploadPurchContractSignerPlatform = new UploadPurchContractSupplementSigner();
                        uploadPurchContractSignerPlatform.setSignerName(platform.getPlatformName());
                        uploadPurchContractSignerPlatform.setSignerSocialCreditCode(platform.getSocialCreditCode());
                        uploadPurchContractSignerPlatform.setUploadPurchContractId(uploadPurchSupplementContract.getId());
                        uploadPurchContractSupplementSignerService.save(uploadPurchContractSignerPlatform);
                        //供应商信息
                        SupplierInfo supplierInfo = supplierInfoService.get(purchContractManagement.getSupplierId());
                        Enterprise supplier = enterpriseService.getById(supplierInfo.getcEnterpriseId());
                        UploadPurchContractSupplementSigner uploadPurchContractSignerSupplier = new UploadPurchContractSupplementSigner();
                        uploadPurchContractSignerSupplier.setSignerName(supplier.getCorporateName());
                        uploadPurchContractSignerSupplier.setSignerSocialCreditCode(supplier.getSocialCreditCode());
                        uploadPurchContractSignerSupplier.setUploadPurchContractId(uploadPurchSupplementContract.getId());
                        uploadPurchContractSupplementSignerService.save(uploadPurchContractSignerSupplier);
                    });
                }

        } else {
            throw new ValidatorException(CodeUtil.FAIL, "审核结论出错！");
        }

        //流程处理
        String processKey = ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS;

        procVariables.put("result", result);

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

    }

    @Override
    public PurchContractSupplementApproval approval(Long businessKey) {

        PurchContractSupplementInfo supplementInfo = supplementInfoService.lambdaQuery()
                .eq(PurchContractSupplementInfo::getPurchContractManagementId, businessKey)
                .orderByDesc(PurchContractSupplementInfo::getGmtCreate).last("limit 1").one();
        PurchContractSupplementApproval supplementApproval = lambdaQuery()
                .eq(PurchContractSupplementApproval::getPurchContractSupplementInfoId, supplementInfo.getId())
                .eq(PurchContractSupplementApproval::getVisible, 0).one();
        //其他约定
        if (supplementApproval != null) {
            List<PurchContractSupplementApprovalCommentInfo> comments = purchContractSupplementApprovalCommentInfoService.lambdaQuery()
                    .eq(PurchContractSupplementApprovalCommentInfo::getPurchContractSupplementApprovalId, supplementApproval.getId()).list();
            if (CollectionUtil.isNotEmpty(comments)) {
                List<String> commentStrs = comments.stream().map(c -> c.getOtherComment()).collect(Collectors.toList());
                supplementApproval.setComments(commentStrs);
            }

            //采购合同补充文件(系统生成)
            AttachmentDto attachmentDtoMake = AttachmentDto.builder()
                    .setEntityId(supplementApproval.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_MAKE_FILE)
                    .build();
            List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDtoMake);
            //只会生成一份文件
            supplementApproval.setFileStorage(files.get(0));

            //上传合同文件
            List<UploadPurchSupplementContract> uploadPurchSupplementContractList = uploadPurchSupplementContractService
                    .lambdaQuery().eq(UploadPurchSupplementContract::getPurchContractSupplementApprovalId, supplementApproval.getId()).list();
            if (CollectionUtil.isNotEmpty(uploadPurchSupplementContractList)) {
                uploadPurchSupplementContractList.forEach(c -> {
                    //签署人
                    List<UploadPurchContractSupplementSigner> supplementSigners = uploadPurchContractSupplementSignerService
                            .lambdaQuery().eq(UploadPurchContractSupplementSigner::getUploadPurchContractId, c.getId()).list();
                    c.setUploadPurchContractSupplementSignerList(supplementSigners);
                    //文件
                    AttachmentDto attachmentDto = AttachmentDto.builder()
                            .setEntityId(c.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_SUPPLEMENT_CONTRACT_UPLOAD_CONTRACT_FILE)
                            .build();
                    //只有一个文件
                    List<FileStorage> filesUpload = sysAttachmentRefService.getFiles(attachmentDto);
                    c.setFileStorage(filesUpload.get(0));
                });
            }

        } else {
            supplementApproval = new PurchContractSupplementApproval();
        }
        PurchContractManagement contractManagement = purchContractService.getById(supplementInfo.getPurchContractManagementId());
        Platform platform = platformService.getById(contractManagement.getTradingPlatformId());
        supplementApproval.setPlatform(platform);
        PurchContractBasicInfo contractBasicInfo = purchContractBasicInfoService
                .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, contractManagement.getId()).one();
        SupplierInfo supplierInfo = supplierInfoService.get(contractManagement.getSupplierId());
        Enterprise supplier = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        supplementApproval.setSupplier(supplier);
        supplementApproval.setPurchContractSupplementInfoId(supplementInfo.getId());

        return supplementApproval;

    }

}
