package com.yd.api.practitioner.service.impl;

import com.yd.api.practitioner.service.PractitionerHiringContractService;
import com.yd.dal.entity.customer.*;
import com.yd.dal.mapper.customer.*;
import com.yd.dal.mapper.practitioner.PractitionerHiringMapper;
import com.libs.pdf.*;
import com.yd.rmi.ali.oss.service.OssService;
import com.yd.rmi.cache.SystemConfigService;
import com.yd.util.CommonUtil;
import com.yd.util.HttpUtil;
import com.yd.util.PDFConfiguration;
import com.yd.util.config.ZHBErrorConfig;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.*;

@Service("PractitionerHiringContractService")
public class PractitionerHiringContractServiceImpl implements PractitionerHiringContractService {
    @Autowired
    private OssService ossService;
    @Resource
    private PractitionerHiringMapper practitionerHiringMapper;
    @Autowired
    private AclPractitionerHiringMembershipMapper membershipMapper;
    @Autowired
    private AclPractitionerMapper aclPractitionerMapper;
    @Autowired
    private AclPractitionerHiringBasicInfoMapper basicInfoMapper;
    @Autowired
    private AclPractitionerHiringWorkingExperienceMapper workingExperienceMapper;
    @Autowired
    private AclPractitionerHiringApproveRecordsMapper recordsMapper;
    @Autowired
    private AclPractitionerHiringPersonalStatementsMapper statementsMapper;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private AclInsurerBranchMapper branchMapper;
    @Autowired
    private AclInsurerBranchDeptMapper deptMapper;


    /**
     * 申请经纪人的ID，生成电子合同，在经纪人表中自动生成记录
     *
     * @param practitioner
     * @return
     */
    @Override
    public String generatePractitionerContract(AclPractitioner practitioner) throws Exception {
        String contractNo = practitioner.getContractNo();
        Long hiringBasicInfoId = practitioner.getHiringBasicInfoId();
        //0、查询分公司电子印章
        String signImage = this.getSignImageLocalPath(practitioner);

        //1、从DB中按照hiringBasicInfoId，获取经纪人的文字信息
        Map<String, String> initDatas = new HashMap<String, String>();
        initDatas = initHiringBasicInfoData(hiringBasicInfoId, contractNo);

        //2、从DB中按照hiringBasicInfoId，从oss上获取经纪人上传的图片信息，需存本地临时文件
        Map<String, String> initImages = new HashMap<String, String>();
        initImages = initHiringImageInfoData(hiringBasicInfoId, signImage);


        //3、PDF模板生成合同文件，存本地临时文件后，上传oss
        String contractFile = generatePractitionerPDF(practitioner, signImage, initDatas, initImages);

        //上传至oss    ossService
        String contractFileOSS = this.putContractFileToOSS(contractFile, hiringBasicInfoId);

        //4、经纪人表生成经纪人记录ag_acl_practitioner，ag_acl_practitioner.contract_oss_path
        //   经纪人经纪人类型级别定义表ag_acl_practitioner_setting
        return contractFileOSS;
    }

    private String putContractFileToOSS(String contractFile, Long basicInfoId) throws Exception {
        StringBuffer directory = new StringBuffer();
        directory.append("brokerHiring/").append(basicInfoId).append("/");

        File tempFile =new File(contractFile.trim());

        //数据源不存在
        if(!tempFile.exists()) {
            throw new Exception("目标文件地址不存在!");
        }
        //非文件类型
        if(!tempFile.isFile()) {
            throw new Exception("目标文件不是文件类型!");
        }
        InputStream is = null;
        String ossPath = null;
        try {
            is = new BufferedInputStream(new FileInputStream(tempFile));//读取数据源

            String fileName = tempFile.getName();
            String key = directory.append(fileName).toString();
            ossPath = ossService.putFileToOss(null, key, is);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ossPath;
    }

    public static String copyFile(String src, String dest) throws IOException, ClassNotFoundException {
        File srcFile = new File(src);//源文件数据源
        File desFile = new File(dest);//写入到目标数据源
        //数据源不存在
        if(!srcFile.exists() || !desFile.exists()) {
            throw new ClassNotFoundException("源文件或者拷贝目标文件地址不存在！");
        }
        //非文件类型
        if(!srcFile.isFile() || !desFile.isFile()) {
            return "源文件或者目标文件不是文件类型!";
        }
        InputStream is = null;
        OutputStream os = null;
        byte[] buf = new byte[1024];//缓存区
        int len = 0;//读取长度
        try {
            is = new BufferedInputStream(new FileInputStream(srcFile));//读取数据源
            os = new BufferedOutputStream(new FileOutputStream(desFile));//写入到数据源
            while((len = is.read(buf)) != -1) { //读取长度不为-1，继续读取
                os.write(buf); //读取内容之后马上写入目标数据源
            }
            os.flush();//输出
            return "文件拷贝成功！查看拷贝文件路径：" + desFile.getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is != null)
                is.close();
            if(os != null)
                os.close();
        }
        return "文件拷贝失败";
    }

    /**
     * 申请ID的数据列表
     *
     * @param hiringBasicInfoId
     * @return
     */
    @Override
    public Map<String, String> initHiringBasicInfoData(Long hiringBasicInfoId, String contractNo) {

        AclPractitionerHiringBasicInfo basicInfo = basicInfoMapper.selectByPrimaryKey(hiringBasicInfoId);
        AclPractitionerHiringMembership memberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);
        AclPractitioner mentor = aclPractitionerMapper.selectByPrimaryKey(memberShip.getMentorPractitionerId());
        AclPractitioner introducer = aclPractitionerMapper.selectByPrimaryKey(memberShip.getIntroducerPractitionerId());
        AclPractitioner second = aclPractitionerMapper.selectByMobileNo(basicInfo.getMobileNo());
        List<AclPractitionerHiringWorkingExperience> workingExperienceList = workingExperienceMapper.selectByHiringBasicInfoId(hiringBasicInfoId);


        String mentorName = mentor == null ? "" : mentor.getName();
        String mentorIdNo = mentor == null ? "" : mentor.getIdNo();
        String mentorMobile = mentor == null ? "" : mentor.getMobileNo();

        String introducerName = introducer == null ? "" : introducer.getName();
        String introducerIdNo = introducer == null ? "" : introducer.getIdNo();
        String introducerMobile = introducer == null ? "" : introducer.getMobileNo();

        //模板文件生成零时文件
        //甲方
        String firstParty = PDFConfiguration.getProperty("pdf.firstParty");
        //甲方负责人
        String firstPartyResponser = PDFConfiguration.getProperty("pdf.firstPartyResponser");
        //甲方地址
        String firstPartyAddress = PDFConfiguration.getProperty("pdf.firstPartyAddress");

        //PDF模板中定义的文字key，和值的集合
        Map<String, String> data = new HashMap<String, String>();
        //1页
        data.put("contactNo", contractNo);
        data.put("practitionerNo", second.getPractitionerCode());
        data.put("subsystem", memberShip.getSubsystem());
        data.put("practitioner", basicInfo.getName());
        data.put("idNo", basicInfo.getIdNo());

        StringBuffer secondResidentAddress = new StringBuffer();
        secondResidentAddress.append(basicInfo.getProvinceName()).append(basicInfo.getCityName());
        data.put("residentAddress", basicInfo.getResidentAddress());
        data.put("mobileNo", basicInfo.getMobileNo());
        //7页
        data.put("firstParty", firstParty);
        data.put("firstPartyResponser", firstPartyResponser);
        data.put("firstPartyAddress", firstPartyAddress);
        // 设置一些地址
        this.setSomeAddress(data, hiringBasicInfoId);

        Calendar now = Calendar.getInstance();
        data.put("contactYear", now.get(Calendar.YEAR) + "");
        data.put("contactMonth", (now.get(Calendar.MONTH) + 1) + "");
        data.put("contactDay", now.get(Calendar.DAY_OF_MONTH) + "");
        //8页
        data.put("secondParty801", basicInfo.getName());

        Calendar secondBirthday = Calendar.getInstance();
        Date practitionerBirthdate = CommonUtil.stringParseDate(basicInfo.getPractitionerBirthdate(), "yyyy-MM-dd");
        secondBirthday.setTime(practitionerBirthdate);

        data.put("secondBirthYear801", secondBirthday.get(Calendar.YEAR) + "");
        data.put("secondBirthMonth801", (secondBirthday.get(Calendar.MONTH) + 1) + "");
        data.put("secondBirthDay801", secondBirthday.get(Calendar.DAY_OF_MONTH) + "");
        data.put("secondPartyIDNo801", basicInfo.getIdNo());
        data.put("secondPartyPermanentResidenceAddress", secondResidentAddress.toString());
        data.put("secondPartyAddress801", basicInfo.getResidentAddress());
        data.put("secondMobileNo801", basicInfo.getMobileNo());
        data.put("secondPractitionerRegNo", second.getPractitionerRegNo());
        data.put("secondEmail", basicInfo.getEmail());

        this.setWorkingExperience(data, workingExperienceList);

        data.put("secondBankAccount", basicInfo.getName());
        data.put("secondBankAccountOpening", basicInfo.getBankAccountOpening());
        data.put("secondBankAccountID", basicInfo.getBankAccountId());
        data.put("secondMentor802", mentorName);
        data.put("secondIntroducer", introducerName);
        data.put("secondMentorIDNo801", mentorIdNo);
        data.put("secondIntroducerIDNo", introducerIdNo);

        Calendar applyDate = Calendar.getInstance();
        applyDate.setTime(basicInfo.getCreatedAt());
        data.put("secondEffectiveYear", applyDate.get(Calendar.YEAR) + "");
        data.put("secondEffectiveMonth", (applyDate.get(Calendar.MONTH) + 1) + "");
        data.put("secondEffectiveDay", applyDate.get(Calendar.DAY_OF_MONTH) + "");
        data.put("secondParty802", basicInfo.getName());
        data.put("secondMentor801", mentorName);
        data.put("secondSubsystem", memberShip.getSubsystem());
        data.put("secondSubsystemNo", "");
        // 签核人员
        this.setApprovepeople(data, hiringBasicInfoId);

        //9页

        String secondSignatureDate = CommonUtil.dateParseString(basicInfo.getCreatedAt(), "yyyy-MM-dd");
        //10页
        data.put("secondSignatureDate1001", secondSignatureDate);
        //12页
        data.put("secondParty1201", basicInfo.getName());
        data.put("secondSignatureDate1201", secondSignatureDate);
        //14页
        data.put("secondParty1401", basicInfo.getName());
        data.put("secondSignatureDate1401", secondSignatureDate);
        //16页
        data.put("secondParty1601", basicInfo.getName());
        data.put("secondPartyIDNo1601", basicInfo.getIdNo());
        data.put("secondSignatureDate1601", secondSignatureDate);

        return data;
    }

    private void setSomeAddress(Map<String, String> data, Long hiringBasicInfoId) {
        AclPractitionerHiringBasicInfo basicInfo = basicInfoMapper.selectByPrimaryKey(hiringBasicInfoId);
        AclPractitionerHiringMembership memberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);
        AclPractitioner systemOwner = aclPractitionerMapper.selectByPrimaryKey(memberShip.getSubsystemOwnerId());
        AclPractitioner mentor = aclPractitionerMapper.selectByPrimaryKey(memberShip.getMentorPractitionerId());

        String mentorName = mentor == null ? "" : mentor.getName();
        String mentorIdNo = mentor == null ? "" : mentor.getIdNo();
        String mentorMobile = mentor == null ? "" : mentor.getMobileNo();

        data.put("secondParty", basicInfo.getName());
        data.put("secondPartyIDNo", basicInfo.getIdNo());
        StringBuffer secondResidentAddress = new StringBuffer();
        secondResidentAddress.append(basicInfo.getProvinceName()).append(basicInfo.getCityName());
        data.put("secondPartyAddress", basicInfo.getResidentAddress());
        data.put("secondMobileNo", basicInfo.getMobileNo());


        data.put("secondSubsystemOwner", memberShip.getSubsystemOwner());
        data.put("secondSubsystemSignature", memberShip.getSubsystemOwner());
        // 查团队长信息
        String systemOwnerIdNo = null;
        String systemOwnerMobile = null;
        StringBuffer systemOwnerAddress = new StringBuffer();
        if (systemOwner == null) {
            if (Long.valueOf("30").equals(memberShip.getMdDropOptionId())) {
                systemOwnerIdNo = basicInfo.getIdNo();
                systemOwnerMobile = basicInfo.getMobileNo();
                systemOwnerAddress.append(basicInfo.getResidentAddress());
                data.put("secondSubsystemOwner", basicInfo.getName());
                data.put("secondSubsystemSignature", basicInfo.getName());
            }
        } else {
            systemOwnerIdNo = systemOwner.getIdNo();
            systemOwnerMobile = systemOwner.getMobileNo();
            systemOwnerAddress.append(systemOwner.getProvinceName()).append(systemOwner.getCityName());
        }
        data.put("secondSubsystemIDNo", systemOwnerIdNo);
        data.put("secondSubsystemAddress", systemOwnerAddress.toString());
        data.put("secondSubsystemMobileNo", systemOwnerMobile);

        data.put("secondMentor", mentorName);
        data.put("secondMentorIDNo", mentorIdNo);
        // 辅导人地址
        StringBuffer mentorAddress = new StringBuffer();
        if (mentor != null) {
            mentorAddress.append(mentor.getProvinceName()).append(mentor.getCityName());
        }
        data.put("secondMentorAddress", mentorAddress.toString());
        data.put("secondMentorMobileNo", mentorMobile);
    }

    private void setApprovepeople(Map<String, String> data, Long hiringBasicInfoId) {
        // 查询审批记录
        List<AclPractitionerHiringApproveRecords> recordsList = recordsMapper.queryListByBasicInfoId(hiringBasicInfoId);

        AclPractitioner practitioner;
        for (AclPractitionerHiringApproveRecords record:recordsList) {

            practitioner = aclPractitionerMapper.selectByPrimaryKey(record.getApprovingPractitionerId());

            if ("体系负责人".equals(record.getApproveStepName())) {
                data.put("secondSubsystemMaster", practitioner.getName());
                continue;
            }
            if ("公司运营主管".equals(record.getApproveStepName())) {
                data.put("secondBranchManager", practitioner.getName());
                continue;
            }
            if ("寿险总经理".equals(record.getApproveStepName())) {
                data.put("secondBranchMaster", practitioner.getName());
                continue;
            }
            if ("公司总经理".equals(record.getApproveStepName())) {
                data.put("secondCenterCEO", practitioner.getName());
                continue;
            }
        }
        data.put("secondSubsystemManager", "");

        // 获取人事专员姓名
        String secondCenterHr = systemConfigService.getSingleConfigValue("Practitioner_Hiring_SecondCenterHr");
        data.put("secondCenterHr", secondCenterHr);

    }

    private void setWorkingExperience(Map<String, String> data, List<AclPractitionerHiringWorkingExperience> workingExperienceList) {

        String experienceKey = "secondWorkingExperience";
        String positionKey = "secondWorkingPosition";
        String periodKey = "secondWorkingPeriod";

        AclPractitionerHiringWorkingExperience item = null;
        for (int i = 0; i <= 4; i++) {
            // 每次循环清空数据
            String experienceValue = "";
            String positionValue = "";
            String periodValue = "";

            if (i < workingExperienceList.size()) {
                item = workingExperienceList.get(i);

                experienceValue = item.getWorkingCompany();
                positionValue = item.getPosition();
                periodValue = item.getWorkingStart() + "~" + item.getWorkingEnd();
            }

            data.put(experienceKey + (i + 1), experienceValue);
            data.put(positionKey + (i + 1), positionValue);
            data.put(periodKey + (i + 1), periodValue);
        }
    }

    /**
     * 申请ID的图片列表，本地地址。从oss上拉到本地
     *
     * @param hiringBasicInfoId
     * @return
     */
    @Override
    public Map<String, String> initHiringImageInfoData(Long hiringBasicInfoId, String signImage) {

        AclPractitionerHiringBasicInfo basicInfo = basicInfoMapper.selectByPrimaryKey(hiringBasicInfoId);

        //PDF模板中定义的文字key，和值的集合
        Map<String, String> images = new HashMap<String, String>();
        //选中
        String check = PDFConfiguration.getProperty("pdf.check");
        //未选中
        String uncheck = PDFConfiguration.getProperty("pdf.uncheck");
        //本地图片目录
        String localDirectory = PDFConfiguration.getProperty("pdf.temp.path");

        // Map赋值
        // 个人照片
        String personerPicture = this.getImgTolocal(localDirectory,"personerPicture.png", basicInfo.getPersonerPictureOssPath());
        images.put("secondPersonerPicture", personerPicture);
        //印章从配置文件读
//        String signImage = PDFConfiguration.getProperty("pdf.signImage");
        images.put("yindunESignature1001", signImage);
        images.put("yindunESignature1201", signImage);
        images.put("yindunESignature1401", signImage);

        // 电子签名
        String signature = this.getImgTolocal(localDirectory,"signature.png", basicInfo.getPersonalSignOssPath());
        images.put("secondSignature1001", signature);
        images.put("secondSignature1201", signature);
        images.put("secondSignature1401", signature);
        images.put("secondSignature1601", signature);
        // 证件照
        String IDFront = this.getImgTolocal(localDirectory,"IDFront.png", basicInfo.getIdFrontPageOssPath());
        String IDBack = this.getImgTolocal(localDirectory,"IDBack.png", basicInfo.getIdBackPageOssPath());
        images.put("secondIDFrontPageImage", IDFront);
        images.put("secondIDBackPageImage", IDBack);
//        images.put("secondBankCardImage", "D:\\pcs12\\bank.jpg");

        //选中或不选中从配置文件读
        String checkFile = PDFConfiguration.getProperty("pdf.check");
        String unCheckFile = PDFConfiguration.getProperty("pdf.uncheck");
        // 设置证件类型
        this.setIDType(images, basicInfo.getIdType(), checkFile, unCheckFile);
        // 设置个人声明
        this.setPersonalStatement(images, hiringBasicInfoId, checkFile, unCheckFile);
        // 设置报聘职级
        this.setPosition(images, hiringBasicInfoId, checkFile, unCheckFile);


        return images;
    }

    private void setPosition(Map<String, String> images, Long hiringBasicInfoId, String checkFile, String unCheckFile) {
        AclPractitionerHiringMembership memberShip = membershipMapper.selectByHiringBasicInfoId(hiringBasicInfoId);

        images.put("secondPosition1", unCheckFile);
        images.put("secondPosition2", unCheckFile);
        images.put("secondPosition3", unCheckFile);
        images.put("secondPosition4", unCheckFile);
        images.put("secondPosition5", unCheckFile);
        images.put("secondPosition6", unCheckFile);

        Long mdDropOptionId = memberShip == null ? null : memberShip.getMdDropOptionId();
        if (Long.valueOf("30").equals(mdDropOptionId)) {
            images.put("secondPosition1", checkFile);
            return;
        }
        if (Long.valueOf("32").equals(mdDropOptionId)) {
            images.put("secondPosition2", checkFile);
            return;
        }
        if (Long.valueOf("33").equals(mdDropOptionId)) {
            images.put("secondPosition3", checkFile);
            return;
        }
        if (Long.valueOf("34").equals(mdDropOptionId)) {
            images.put("secondPosition4", checkFile);
            return;
        }
        if (Long.valueOf("35").equals(mdDropOptionId)) {
            images.put("secondPosition5", checkFile);
            return;
        }
        if (Long.valueOf("36").equals(mdDropOptionId)) {
            images.put("secondPosition6", checkFile);
            return;
        }

    }

    private void setPersonalStatement(Map<String, String> images, Long hiringBasicInfoId, String checkFile, String unCheckFile) {
        List<AclPractitionerHiringPersonalStatements> statementsList = statementsMapper.selectByHiringBasicInfoId(hiringBasicInfoId);

        images.put("secondPersonalStatement1", unCheckFile);
        images.put("secondPersonalStatement2", unCheckFile);
        images.put("secondPersonalStatement3", unCheckFile);
        images.put("secondPersonalStatement4", unCheckFile);
        images.put("secondPersonalStatement5", unCheckFile);
        images.put("secondPersonalStatement6", unCheckFile);

        String dropOptionCode = "";
        Long status;
        for (AclPractitionerHiringPersonalStatements statements : statementsList) {

            dropOptionCode = statements.getDropOptionCode();
            status = statements.getStatus();

            if (dropOptionCode.equals("NO_CRIME_RECORD") && Long.valueOf("1").equals(status)) {
                images.put("secondPersonalStatement1", checkFile);
                continue;
            }
            if (dropOptionCode.equals("NO_LOST_CREDIT") && Long.valueOf("1").equals(status)) {
                images.put("secondPersonalStatement2", checkFile);
                continue;
            }
            if (dropOptionCode.equals("NO_PUBLIC_CREDIT_RECORD") && Long.valueOf("1").equals(status)) {
                images.put("secondPersonalStatement3", checkFile);
                continue;
            }
            if (dropOptionCode.equals("NO_REGISTER_SAME_TRADE") && Long.valueOf("1").equals(status)) {
                images.put("secondPersonalStatement6", checkFile);
                continue;
            }

        }

    }

    private void setIDType(Map<String, String> images, String idType, String checkFile, String unCheckFile) {

        images.put("secondIDType1", unCheckFile);
        images.put("secondIDType2", unCheckFile);
        images.put("secondIDType3", unCheckFile);
        images.put("secondIDType4", unCheckFile);

        if (idType.indexOf("身份证") >= 0) {
            images.put("secondIDType1", checkFile);
            return;
        }

        if (idType.indexOf("台胞证") >= 0) {
            images.put("secondIDType2", checkFile);
            return;
        }

        if (idType.indexOf("护照") >= 0) {
            images.put("secondIDType3", checkFile);
            return;
        }
        images.put("secondIDType4", checkFile);
    }

    private String getImgTolocal(String localDirectory, String filename, String imgUrl) {
        Map<String, Object> input = HttpUtil.getInput(imgUrl);
        if (!(boolean) input.get("success")) {
            return null;
        }
        //获取头像流
        InputStream inputStream = (InputStream) input.get("is");

        String filePath = localDirectory + filename;
        byte[] data = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            while ((len = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, len);

            }

            return filePath;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {

            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        return null;
    }

    /**
     * 用采集过来的经纪人数据、图片，生成该经纪人的电子合同
     *
     * @param initDatas
     * @param initImages
     * @return
     */
    @Override
    public String generatePractitionerPDF(AclPractitioner practitioner, String signImage,
                                          Map<String, String> initDatas, Map<String, String> initImages) throws Exception {
        String templatePDF = "D:\\pcs12\\templatePractitionerContract.pdf";
        templatePDF = PDFConfiguration.getProperty("pdf.template");
        //模板文件生成零时文件
        String tmpPathPDF = PDFConfiguration.getProperty("pdf.temp.path");


        //PDF模板输出结果文件
        String practitionerNO = practitioner.getPractitionerCode();
        String templateResultPDF = tmpPathPDF + practitionerNO + "-template.pdf";
        //按模板填充数据生成结果PDF
        PDFTemplate.generatePDF(templatePDF, templateResultPDF, initDatas, initImages);

        //加盖电子印章结果文件
        String signResultPDF = "D:\\pcs12\\signedYD.pdf";
        signResultPDF = tmpPathPDF + practitionerNO + "-signedYD.pdf";

        String password = "UC645YlB";
        password = PDFConfiguration.getProperty("pdf.keyPassword");

        String keyStorePath = "D:\\pcs12\\4929078_m.zuihuibi.cn.pfx";
        keyStorePath = PDFConfiguration.getProperty("pdf.keyStorePath");

        //准备加盖电子印章的源文件
        String signSourcePDF = templateResultPDF;

        //电子印章文件
//        String signImage = "D:\\pcs12\\上海银盾保险经纪有限公司.png";
//        signImage = PDFConfiguration.getProperty("pdf.signImage");

        float x = 450;
        float y = 150;
        x = Float.parseFloat(PDFConfiguration.getProperty("pdf.position.x"));
        y = Float.parseFloat(PDFConfiguration.getProperty("pdf.position.y"));
        try {
            PDFSign.sign(signResultPDF, password, keyStorePath, signSourcePDF, signImage,13, x, y);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return signResultPDF;
    }

    private String getSignImageLocalPath(AclPractitioner practitioner) throws Exception {
        Long insurerBranchId = practitioner.getInsurerBranchId();
        Long deptId = practitioner.getDeptId();

        // 1.获取电子印章url
        InputStream inputStream = null;
        String electronicTaxSeal = null;

        AclInsurerBranchDept dept = deptMapper.selectByPrimaryKey(deptId);

        if (dept != null && StringUtils.isNotBlank(dept.getElectronicTaxSeal())) {
            electronicTaxSeal = dept.getElectronicTaxSeal();
        } else {
            AclInsurerBranch insurerBranch = branchMapper.selectByPrimaryKey(insurerBranchId);
            if (insurerBranch != null && StringUtils.isNotBlank(insurerBranch.getElectronicTaxSeal())) {
                electronicTaxSeal = insurerBranch.getElectronicTaxSeal();
            }
        }

        if (StringUtils.isBlank(electronicTaxSeal)) {
            throw new Exception("分公司和部门电子印章url不能同时为空");
        }

        // 2.从Oss下载电子印章图片到本地
        //本地图片目录
        String localDirectory = PDFConfiguration.getProperty("pdf.signImage");
        String signature = this.getImgTolocal(localDirectory,"signImage.png", electronicTaxSeal);

        return signature;
    }


    @Override
    public String getNextContractNo() {
        return practitionerHiringMapper.getNextContractNo();
    }
}
