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.dict.impl.FileModuleDict;
import com.sunxung.factoring.entity.electronicsignature.FddSignData;
import com.sunxung.factoring.entity.entprise.Enterprise;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.purchcontractmanagement.*;
import com.sunxung.factoring.entity.supplier.SupplierInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.mapper.purchcontractmanagement.PurchContractSignConclusionMapper;
import com.sunxung.factoring.service.entprise.IEnterpriseService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.purchcontractmanagement.*;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购合同 合同的签署结论 服务实现类
 * </p>
 *
 * @author liutao
 * @since 2023-03-14
 */
@Service("purch_contract_sign_confirmService")
public class PurchContractSignConclusionServiceImpl extends ServiceImpl<PurchContractSignConclusionMapper, PurchContractSignConclusion> implements IPurchContractSignConclusionService {

    @Autowired
    private BusinessAssigneeService assigneeService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private PurchContractElectronicInfoService purchContractElectronicInfoService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private ISupplierInfoService supplierInfoService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private PurchContractApprovalService purchContractApprovalService;

    @Autowired
    private IUploadPurchContractService uploadPurchContractService;

    @Autowired
    private FileStorageService fileService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private IPurchContractSupplementInfoService supplementInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PurchContractSignConclusion signPage(Long businessKey) {

        PurchContractSignConclusion contractSignConclusion = new PurchContractSignConclusion();
        PurchContractManagement purchContractManagement = purchContractService.getById(businessKey);
        PurchContractBasicInfo purch = purchContractBasicInfoService.getOne(new QueryWrapper<PurchContractBasicInfo>()
                .eq("c_purch_contract_management_id", businessKey));
        Platform platform = platformService.getById(purchContractManagement.getTradingPlatformId());
        SupplierInfo supplierInfo = supplierInfoService.get(purchContractManagement.getSupplierId());
        Enterprise supplier = enterpriseService.getById(supplierInfo.getcEnterpriseId());
        //认证状态  签署状态初始化
        if (!supplier.getAuthStatus()) {
            String result = ElectronicSignatureUtil.getAuthInfo(supplier.getSocialCreditCode(), "2");
            if ("1".equals(result)) {
                supplier.setAuthStatus(true);
                enterpriseService.updateById(supplier);
                purchContractElectronicInfoService.lambdaUpdate()
                        .eq(PurchContractElectronicInfo::getFddCustomerId, supplier.getFddCustomerId())
                        .set(PurchContractElectronicInfo::getCertifyStatus, 1)
                        .update();
            }
        }
        contractSignConclusion.setSupplier(supplierInfo);
        contractSignConclusion.setSupplierInfo(supplier);


        //获取合同对应的最新签署信息
        List<PurchContractElectronicInfo> electronicInfos = purchContractElectronicInfoService.lambdaQuery()
                .eq(PurchContractElectronicInfo::getcPurchContractBasicInfoId, purch.getId())
                .list();
        if (CollectionUtil.isEmpty(electronicInfos)) {
            electronicInfos = new ArrayList<>();
            PurchContractApproval latestPurchContractApproval = purchContractApprovalService
                    .getOne(new QueryWrapper<PurchContractApproval>().eq("purch_contract_basic_info_id", purch.getId())
                            .eq("visible", 1)
                            .orderByDesc("gmt_create").last("limit 1"));
            if (latestPurchContractApproval == null) {
                return null;
            }
            //批量手动签署
            List<FddSignData> fddSignDataList = new ArrayList<FddSignData>();

            //之前制作好的待处理文件
            AttachmentDto attachmentDto = AttachmentDto.builder()
                    .setEntityId(latestPurchContractApproval.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_FILE_view)
                    .build();

            //只有一个文件
            List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
            FileStorage fileStorage;
            if (CollectionUtil.isNotEmpty(files)) {
                fileStorage = files.get(0);
            } else {
                throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
            }
            String filePath = fileStorage.getAbsolutePath();
            File purchContractPdfFile = new File(filePath);
            doAutoSign(purch, platform, supplier, electronicInfos, purchContractPdfFile, fddSignDataList,
                    purch.getContractNumber() + "-" + purch.getContractName());

            //上传的合同
            if (latestPurchContractApproval.getUpload().equals(1)) {
                List<UploadPurchContract> uploadPurchContracts = uploadPurchContractService.lambdaQuery()
                        .eq(UploadPurchContract::getPurchContractApprovalId, latestPurchContractApproval.getId()).list();
                for (UploadPurchContract uploadPurchContract : uploadPurchContracts) {
                    AttachmentDto attachmentDtoUpload = AttachmentDto.builder()
                            .setEntityId(uploadPurchContract.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_UPLOAD_CONTRACT_FILE)
                            .build();
                    //只有一个文件
                    List<FileStorage> fileStorages = sysAttachmentRefService.getFiles(attachmentDtoUpload);
                    FileStorage uploadFileStorage;
                    if (CollectionUtil.isNotEmpty(fileStorages)) {
                        uploadFileStorage = fileStorages.get(0);
                    } else {
                        throw new ValidatorException(CodeUtil.FAIL, "未查询到文件！");
                    }
                    File uploadPdf = new File(uploadFileStorage.getAbsolutePath());
                    doAutoSign(purch, platform, supplier, electronicInfos, uploadPdf, fddSignDataList,
                            purch.getContractNumber() + "-" + uploadPurchContract.getContractName());
                }
            }
            String contractLink = ElectronicSignatureUtil.manualBatchSign(supplier.getFddCustomerId(), fddSignDataList, purch.getContractName());
            String shortUrl = ElectronicSignatureUtil.shortUrl(null, contractLink);
            for (PurchContractElectronicInfo electronicInfo : electronicInfos) {
                electronicInfo.setShortContractLink(shortUrl);
                electronicInfo.setContractLink(contractLink);
                purchContractElectronicInfoService.saveOrUpdate(electronicInfo);
            }
        }
        contractSignConclusion.setPurchContractElectronicInfos(electronicInfos);

        return contractSignConclusion;
    }

    private void doAutoSign(PurchContractBasicInfo purch, Platform platform, Enterprise supplier, List<PurchContractElectronicInfo> electronicInfos, File purchContractPdfFile, List<FddSignData> fddSignDataList, String contractName) {
        //上传合同
        String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        purch.setContractId(contractId);
        purchContractBasicInfoService.updateById(purch);
        //采购合同自动签署
        String transactionIdAuto = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        ElectronicSignatureUtil.uploadContract(contractId, contractName, purchContractPdfFile);
        String signKeyword = "xf";
        ElectronicSignatureUtil.autoSign(transactionIdAuto, contractId, platform.getFddCustomerId(), contractName, signKeyword);

        FddSignData fddSignData = new FddSignData();
        fddSignData.setContractId(contractId);
        fddSignData.setContractType("Purch");
        fddSignData.setSignKeyword("gys");
        String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        while (transactionId.contains("FDD")) {
            transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
        }
//        transactionIdCache.saveObjBuildTransactionId(transactionId,"SIGNPURCHFDD" + purchContractManagement.getId() + "FDD" + purch.getId() + "FDD" + taskId + "FDD" + ThreadLocalUtil.getUserId());
        fddSignData.setTransactionId(transactionId);
        fddSignDataList.add(fddSignData);

        PurchContractElectronicInfo electronicInfo = new PurchContractElectronicInfo();
        electronicInfo.setSignStatus(false);
        electronicInfo.setCertifyStatus(false);
        electronicInfo.setContractId(contractId);
        electronicInfo.setTransactionId(transactionId);
        electronicInfo.setShortContractLinkCreate(new Date());
        electronicInfo.setCertifyLink(supplier.getShortAuthUrl());
        electronicInfo.setFddCustomerId(supplier.getFddCustomerId());
        //认证状态
        electronicInfo.setCertifyStatus(supplier.getAuthStatus());
        electronicInfo.setContractName(contractName);
        electronicInfo.setcPurchContractBasicInfoId(purch.getId());
        electronicInfos.add(electronicInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sign(PurchContractSignConclusion purchContractSignConclusion) {

        ThreadLocalUtil.setUser(userService.getByLoginName("admin"));
        Long businessKey = purchContractSignConclusion.getBusinessKey();

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

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

        //获取合同对应的最新签署信息
        List<PurchContractElectronicInfo> electronicInfos = purchContractElectronicInfoService.lambdaQuery()
                .eq(PurchContractElectronicInfo::getcPurchContractBasicInfoId, purch.getId())
                .list();
        boolean allMatch = electronicInfos.stream().allMatch(r -> r.getSignStatus());
        if (!allMatch) {
            throw new ValidatorException(CodeUtil.FAIL, "所有合同必须全部签署完成才能提交！");
        }

        //保存签署确认信息
        purchContractSignConclusion.setPurchContractBasicInfoId(purch.getId());
        saveOrUpdate(purchContractSignConclusion);

        //走正常流程
        String processKey = ConstantUtil.PURCH_CONTRACT;
        String assigneeKey = ConstantUtil.PURCH_CONTRACT_FINAL_APPROVAL + ConstantUtil.CANDIDATE;

        //taskId
        BusinessProcessingLog lastLog = businessProcessingLogService.getByBusinessTypeBusinessKey(processKey, purchContractManagement.getId());
        String taskId = lastLog.getHistoricTaskId();

        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.OPERATION_SPECIALIST + "角色内无任何用户！");
        }
        List<String> legalIds = legalSpecialists.stream().map(c -> c.toString()).collect(Collectors.toList());

        String result;
        if (purchContractSignConclusion.getConclusion().equals(ConstantConversionUtil.APPROVAL_RESULT_PASS)) {
            result = "线上";
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "结论错误！");
        }

        purchContractService.updateById(purchContractManagement);

//            CSalesContract salesContract = salesContractService.lambdaQuery().eq(CSalesContract::getBusinessNumber, purchContractManagement.getBusinessNumber())
//                    .orderByDesc(CSalesContract::getBusinessNumber).last("limit 1").one();

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


    }


    @Override
    public PurchContractSignConclusion getView(Long id) {
        PurchContractSignConclusion purchContractSignConclusion = getById(id);
        if (purchContractSignConclusion != null) {
            List<PurchContractElectronicInfo> purchContractElectronicInfoList = purchContractElectronicInfoService
                    .lambdaQuery().eq(PurchContractElectronicInfo::getcPurchContractBasicInfoId, purchContractSignConclusion.getPurchContractBasicInfoId()).list();
            purchContractSignConclusion.setPurchContractElectronicInfos(purchContractElectronicInfoList);

            //供应商
            if (CollectionUtil.isNotEmpty(purchContractElectronicInfoList)) {
                PurchContractElectronicInfo purchContractElectronicInfo = purchContractElectronicInfoList.get(0);
                PurchContractBasicInfo contractBasicInfo = purchContractBasicInfoService
                        .lambdaQuery().eq(PurchContractBasicInfo::getId, purchContractElectronicInfo.getcPurchContractBasicInfoId()).one();
                if (contractBasicInfo != null) {
                    PurchContractManagement purchContractManagement = purchContractService.getById(contractBasicInfo.getPurchContractManagementId());
                    SupplierInfo supplier = supplierInfoService.get(purchContractManagement.getSupplierId());
                    Enterprise supplierInfo = enterpriseService.getById(supplier.getcEnterpriseId());
                    purchContractSignConclusion.setSupplierInfo(supplierInfo);

                    //获取已签署文件
                    AttachmentDto attachmentDto = AttachmentDto.builder()
                            .setEntityId(contractBasicInfo.getId())
                            .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE)
                            .build();
                    List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
                    purchContractSignConclusion.setFiles(files);
                }
            }
        }

        return purchContractSignConclusion;
    }

    @Override
    public List<FileStorage> getAllSignFile(Long id, HttpServletResponse response) {

        List<FileStorage> allFiles = new ArrayList<>();
        PurchContractBasicInfo contractBasicInfo = purchContractBasicInfoService
                .lambdaQuery().eq(PurchContractBasicInfo::getPurchContractManagementId, id).one();
        //获取已签署文件
        //主流程已签署文件
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(contractBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SIGN_FILE)
                .build();
        allFiles.addAll(sysAttachmentRefService.getFiles(attachmentDto));
        //变更流程已签署文件
        PurchContractSupplementInfo supplementInfo = supplementInfoService.lambdaQuery()
                .eq(PurchContractSupplementInfo::getPurchContractManagementId, id).one();
        if (supplementInfo != null){
            AttachmentDto attachmentDtosupplement = AttachmentDto.builder()
                    .setEntityId(supplementInfo.getId())
                    .setChildEnum(FileModuleDict.ChildEnum.PURCHASE_CONTRACT_SUPPLEMENT_SIGN_FILE)
                    .build();
            //已签署文件
            allFiles.addAll(sysAttachmentRefService.getFiles(attachmentDtosupplement));
        }

        return allFiles;
    }

}
