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

import com.itextpdf.text.pdf.PdfReader;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ElectronicSignatureUtil;
import com.sunxung.factoring.component.util.PdfUtil;
import com.sunxung.factoring.component.util.StringUtil;
import com.sunxung.factoring.component.util.onlineConverter.OfficeConverterUtil;
import com.sunxung.factoring.entity.customerinformation.ElectronicSignaturePersonal;
import com.sunxung.factoring.entity.electronicsignature.FddSignData;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmation;
import com.sunxung.factoring.entity.signconfirmation.SignConfirmationElectronicInfo;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.service.customerinformation.IElectronicSignaturePersonalService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationAddFlowService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationElectronicInfoService;
import com.sunxung.factoring.service.signconfirmation.ISignConfirmationService;
import com.sunxung.factoring.service.sys.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 * @author liutao
 * @since 2023-05-16
 */
@Service("sign_confirmation_addService")
public class SignConfirmationAddFlowServiceImpl implements ISignConfirmationAddFlowService {

    @Autowired
    private ISignConfirmationService signConfirmationService;

    @Autowired
    private ISignConfirmationElectronicInfoService signConfirmationElectronicInfoService;

    @Autowired
    private IElectronicSignaturePersonalService electronicSignaturePersonalService;

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public SignConfirmation getView(Long id) {
        SignConfirmation signConfirmation = signConfirmationService.getById(id);
        List<SignConfirmationElectronicInfo> signConfirmationElectronicInfos = signConfirmationElectronicInfoService.lambdaQuery().eq(SignConfirmationElectronicInfo::getSignConfirmationId, signConfirmation.getId()).list();

        Long electronicSignaturePersonalId = signConfirmationElectronicInfos.get(0).getElectronicSignaturePersonalId();
        ElectronicSignaturePersonal electronicSignaturePersonal = electronicSignaturePersonalService.getById(electronicSignaturePersonalId);
        if(electronicSignaturePersonal.getAuthStatus().equals(1)){
            List<FddSignData> fddSignDataList = new ArrayList();
            if(StringUtil.isEmpty(signConfirmation.getContractLink())){
                for (SignConfirmationElectronicInfo signConfirmationElectronicInfo : signConfirmationElectronicInfos) {
                    //将文件转换为PDF在上传法大大
                    FileStorage fileStorage = fileStorageService.get(signConfirmationElectronicInfo.getFileId());
                    File file = new File(fileStorage.getAbsolutePath());
                    String fileType = fileStorage.getFileType();
                    String newPath = file.getAbsolutePath().replace(fileType, ".pdf");
                    File pdfFile;
                    //只支持图片和excel转换
                    if(fileType.equals(".pdf")){
                        pdfFile = file;
                    }else if(fileType.equals(".xlsx") || fileType.equals(".xls")){
                        pdfFile = OfficeConverterUtil.office2Pdf(file.getAbsolutePath(), newPath);
                    }else if(fileType.equals(".jpg") || fileType.equals(".png") || fileType.equals(".jpeg") || fileType.equals(".bmp")){
                        PdfUtil.convert(file.getAbsolutePath(),newPath);
                        pdfFile = new File(newPath);
                    }else {
                        throw new ValidatorException(CodeUtil.FAIL,"文件类型错误！");
                    }
                    PdfReader pdfReader = null;
                    try {
                        pdfReader = new PdfReader(new FileInputStream(pdfFile));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    int pages = pdfReader.getNumberOfPages();
                    //上传合同
                    String contractId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
                    String docTitle = fileStorage.getOriginalName();
                    String transactionId = UUID.randomUUID().toString().trim().replaceAll("-", "").toUpperCase();
                    ElectronicSignatureUtil.uploadContract(contractId, docTitle, pdfFile);
                    //批量手动签署
                    FddSignData fddSignData = new FddSignData();
                    fddSignData.setContractId(contractId);
                    fddSignData.setContractType("settlement");
                    String page = String.valueOf(pages - 1);
                    fddSignData.setSearchLocation(page);
                    fddSignData.setTransactionId(transactionId);
                    fddSignDataList.add(fddSignData);

                    signConfirmationElectronicInfo.setContractId(contractId);
                    signConfirmationElectronicInfo.setTransactionId(transactionId);
                    signConfirmationElectronicInfoService.updateById(signConfirmationElectronicInfo);
                }
                String contractLink = ElectronicSignatureUtil.batchSignUrlSearchLocation(electronicSignaturePersonal.getFddCustomerId(), fddSignDataList, "签署确认批量签署");
                //合同链接
                String shortUrl = ElectronicSignatureUtil.shortUrl(null, contractLink);
                signConfirmation.setContractLink(contractLink);
                signConfirmation.setShortContractLink(shortUrl);
                signConfirmation.setShortContractLinkCreate(new Date());
                signConfirmationService.updateById(signConfirmation);
            }
        }
        signConfirmation.setSignConfirmationElectronicInfos(signConfirmationElectronicInfos);
        signConfirmation.setElectronicSignaturePersonal(electronicSignaturePersonal);
        return signConfirmation;
    }
}
