package com.hr.repository.service.impl;

import com.hr.dto.EsignParmDto;
import com.hr.dto.EsignReturnDto;
import com.hr.repository.service.EsignService;


import com.hr.util.ClientHelper;
import com.hr.util.HtmlToPDFUtil;
import com.hr.util.SignHelper;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.canvas.PdfCanvasConstants;
import com.itextpdf.kernel.pdf.canvas.parser.PdfCanvasProcessor;
import com.itextpdf.kernel.pdf.canvas.parser.listener.IPdfTextLocation;
import com.itextpdf.kernel.pdf.canvas.parser.listener.RegexBasedLocationExtractionStrategy;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Image;


import com.timevale.esign.paas.tech.bean.bean.PosBean;
import com.timevale.esign.paas.tech.bean.request.PlatformSignParam;
import com.timevale.esign.paas.tech.bean.request.SignFilePdfParam;
import com.timevale.esign.paas.tech.bean.result.FileDigestSignResult;
import com.timevale.esign.paas.tech.client.ServiceClient;
import com.timevale.esign.paas.tech.enums.SignType;
import com.yy.basedevelop.common.data.BaseReturnDto;
import com.yy.basedevelop.common.util.OSSUtil;
import esign.utils.exception.SuperException;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;
import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.security.InvalidParameterException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yaoy
 * @createTime 2025/10/17 11:59
 **/
@Component
@Slf4j
public class EsignServiceImpl implements EsignService {
    @Autowired
    private FontManager fontManager;
    private int topValue = 10;
    private int leftValue = 20;
    private int rightValue = 10;
    private int bottomValue = 10;
    private int userSpaceWidth = 1024;
//    @Autowired
//    private RestTemplate restTemplate;
    @Autowired
    private OSSUtil oSSUtil;
    private Pattern pattern = Pattern.compile("^\\d+-\\d+$");
    private Pattern pattern2 = Pattern.compile("^(\\d+)-(\\d+)$");
    private static final Logger LOGGER = LoggerFactory.getLogger(EsignServiceImpl.class);
    private static SignHelper signHelper;

    private byte[] fontBytes=null;
    private volatile Font cachedFont;



    public  void initEsign(){
        try {
            //1、注册客户端，全局使用，只需注册一次
            ClientHelper.registClient();

            //2、获取已初始化的客户端，以便后续正常调用SDK提供的各种服务，全局使用，只需获取一次
            ServiceClient serviceClient = ClientHelper.getServiceClient(ClientHelper.getProjectId());

            //3、实例化辅助类
            signHelper = new SignHelper(serviceClient);
            log.info("E签宝初始化成功:{}",signHelper);


        } catch (Exception e) {
//            e.getE().printStackTrace();
            log.info("E签宝初始化失败了");
            log.error("系统加载,初始化E签宝失败",e);
        }

    }
    /**
     * 电子签章
     * @param parm
     * @return
     */
    @Override
    public BaseReturnDto<EsignReturnDto> platformSignByPdfStream(EsignParmDto parm) {
        checkParm(parm);
        EsignReturnDto esignReturnDto = new EsignReturnDto();
        try {
            /**
             * 平台自身PDF文件流签署
             */
            //-------------------------------------------开始盖章,不调用e签宝---------------------------------------------
            // 签章位置信息
            //处理freemarker内容,并生成pdf,返回pdf字节流
            byte[] srcPdfBytes=doConversion(dealFreeMarkerContent(parm.getFreeMarkerContent(), parm.getParmData()));
            InputStream inputStream = new ByteArrayInputStream(srcPdfBytes);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
//            InputStream inputStream = new ByteArrayInputStream(dto.getSrcPdfBytes());
//            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
            Document document = new Document(pd);

            /***----------------------------------------------------------------------------------------*******/
            /***----------------------------------------------------------------------------------------*******/
            /***----------------------------------------------------------------------------------------*******/
            //如果没有章则不盖章
            if(parm.getSealData()!=null) {
                //在原图片上面增加日期
                parm.setSealData(addTimestampToBase64Image(parm.getSealData(), parm.getAddFontHeight(), parm.getCharSpacing(), parm.getAddFontSize(),parm.getCreateTime()));

                //将签章转换为 图片，以便获取宽高
                byte[] imageBytes = Base64.getDecoder().decode(parm.getSealData());
                ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
                BufferedImage originalImage = ImageIO.read(bis);
                bis.close();
                //得到图片的宽高
                int _width = originalImage.getWidth();
                int _height = originalImage.getHeight();


                if (originalImage == null) {
                    throw new IllegalArgumentException("无效的图片数据");
                }


                int pageCount = pd.getNumberOfPages();
                Boolean limitpagenum = false;
                int[] limmitpagenums = null;
                if (parm.getPosPage() != null && !"".equals(parm.getPosPage())) {
                    limitpagenum = isValidFormat(parm.getPosPage());
                    limmitpagenums = extractNumbers(parm.getPosPage());
                }
                //遍历每一页
                for (int i = 1; i <= pageCount; i++) {

                    if (limitpagenum == true && limmitpagenums != null && limmitpagenums.length == 2) {
                        if (i < limmitpagenums[0] || i > limmitpagenums[1]) {
                            continue;
                        }
                    }

                    PdfPage page = pd.getPage(i);
                    //查找页中的匹配文字，并定位到位置。
                    RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(parm.getKeyWord());
                    PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
                    processor.processPageContent(page);
                    Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();

                    //自定义结果处理
                    if (!resultantLocations.isEmpty()) {
                        for (IPdfTextLocation item : resultantLocations) {
                            Rectangle boundRectangle = item.getRectangle();
//                        System.out.println(item.getText());
                            ImageData imageData = ImageDataFactory.create(Base64.getDecoder().decode(parm.getSealData()));
//                        System.out.println("关键字“" + dto.getKeyWord() + "” 的坐标为 x: " + boundRectangle.getX() + "  ,y: " + boundRectangle.getY());
                            Image image = new Image(imageData).scaleAbsolute(parm.getWidth(), parm.getWidth() * _height / _width).setFixedPosition(i,
                                    boundRectangle.getRight() + parm.getPosX(),
                                    boundRectangle.getBottom() - parm.getPosY());
                            document.add(image);
                            break;
                        }
                    }
                }
            }
            document.close();
            pd.close();
            //输出文件
            out.close();
            byte[] filebytes=out.toByteArray();

//            File file222 = new File("D:\\_____Work\\output.pdf");
//
//            try (FileOutputStream fos = new FileOutputStream(file222)) {
//                fos.write(filebytes);
//                fos.flush();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }


            // 签署文件信息
            SignFilePdfParam file = new SignFilePdfParam();
            //PDF文件信息
//            String srcPdfPath = PATH_PREFEX + "test.pdf";
            //获取PDF文件的字节流
//            byte[] srcPdfBytes = parm.getSrcPdfBytes();

            file.setStreamFile(filebytes);// 待填充PDF文件本地二进制数据
            String filename="我的平台自身签署文件.pdf";
            if(parm.getFileName()!=null){
                filename=parm.getFileName();
            }
            file.setFileName(filename);
            //file.setDstPdfFile(PATH_PREFEX + "Signed_Platform.pdf");// 签署后PDF文件本地路径，含文件名（为空时返回签署后的文件流）
            //传入平台自身签署参数内
            PlatformSignParam platformSignParam = new PlatformSignParam();
            FileDigestSignResult signRst=null;
            //如果当前有用户签名信息，则还需要签用户
            if(parm.getSealDataUserName()!=null ){

                //获取了第一次盖章的pdf二进制
                file.setStreamFile(filebytes);
                platformSignParam.setFileBean(file);//签署文件信息
                int addtimestampfontsize=10;
                int addfontheight=13;
                if(parm.getSealDataUserName().length()<4){
                    addtimestampfontsize=11;
                    addfontheight=13;
                }
                if(parm.getSealDataUserName().length()>8){
                    parm.setPosXUser(parm.getPosXUser()+10+1*parm.getSealDataUserName().length());
                }


                //根据用户名字生成红色透明背景图片
                platformSignParam.setSealData(addTimestampToBase64Image(generateTransparentImageWithText(parm.getSealDataUserName()),addfontheight,0,addtimestampfontsize,parm.getCreateTime()));
                platformSignParam.setSignType(SignType.Key);
                List<PosBean> posBeansUser = new ArrayList<>();
                platformSignParam.setPosBeans(posBeansUser);
                PosBean signPos1 = new PosBean();
                String posPage1="1";
                if(parm.getPosPage()!=null){
                    posPage1=parm.getPosPage();
                }
                signPos1.setPosPage(posPage1);// 签署页码（除关键字签章外，页码均不可为空）若为多页签章，支持指定多个页码，例如格式：“1-3,5,8“
                int posX1=50;
                if(parm.getPosXUser()!=null){
                    posX1=parm.getPosXUser();
                }
                signPos1.setPosX(posX1);// 签署位置X坐标，若为关键字定位，相对于关键字的X坐标偏移量，默认0
                int posY1=0;
                if(parm.getPosYUser()!=null){
                    posY1=parm.getPosYUser();
                }
                signPos1.setPosY(posY1);// 签署位置Y坐标，若为关键字定位，相对于关键字的Y坐标偏移量，默认0
                String KeyWord1="";
                if(parm.getKeyWordUser()!=null){
                    KeyWord1=parm.getKeyWordUser();
                }
                signPos1.setKeyWord(KeyWord1);// 关键字，仅限关键字签章时有效，若为关键字定位时，不可空
                int with1=130;
                // 创建一个宽度为100像素，高度为50像素的透明背景图片
//                int width = 130;
                if(parm.getSealDataUserName().length()*11>with1){
                    with1 = parm.getSealDataUserName().length()*11;
                }
//                if(parm.getSealDataUserName().length()*11>parm.getWidthUser()){
//                    parm.setWidthUser(parm.getSealDataUserName().length()*11);
//                }
//                if(parm.getWidthUser()!=null){
//                    with1=parm.getWidthUser();
//                }
                signPos1.setWidth(with1+20);// 印章展现宽度，将以此宽度对印章图片做同比缩放。
//                signPos1.setAddSignTime(true);// 是否显示本地签署时间，需要width设置92以上才可以看到时间
                posBeansUser.add(signPos1);
                platformSignParam.setPosBeans(posBeansUser);//签章位置信息
                try {
                    signRst = signHelper.platformSign(platformSignParam);
                    if (signRst.getErrCode() != 0) {
                        String typeMsg = "Esign平台自身";
                        throw new SuperException(
                                MessageFormat.format("{0}用户签章,签署失败: errCode = {1},msg = {2}",
                                        typeMsg, signRst.getErrCode(), signRst.getMsg()));
                    }
                }catch (Exception ex1) {
                    log.error("通过E签宝签章失败:", ex1);
                    //如果e签宝次数用完了，则需要调用平台自签章，111111
                    try {
                        log.info("通过系统重新签章");
                        //将e签宝的参数进行调整以便适应本地生成用户签名
                        if (parm.getWidthUser() != null) {
                            parm.setWidthUser(parm.getWidthUser() - 20);
                        }
                        if (parm.getPosYUser() != null) {
                            parm.setPosYUser(parm.getPosYUser() - 49);
                        }
                        if (parm.getPosXUser() != null) {
                            parm.setPosXUser(parm.getPosXUser() - 50);
                        }
                        return hrSignByPdfStream(parm);

                    } catch (Exception e1) {
                        log.error("签章Pdf2,非E签宝,失败:", e1);
                    }
                }




//            if(1==1){
////// 定义一个文件名字进行接收获取文件
//                FileOutputStream fileOut = new FileOutputStream(new File("D:\\_____Work\\aaa.pdf" ));
//                byte[] buf = new byte[1024 * 8];
//                InputStream ipt = new ByteArrayInputStream(signRst.getStream());
//                while (true) {
//                    int read = 0;
//                    if (ipt != null) {
//                        read = ipt.read(buf);
//                    }
//                    if (read == -1) {
//                        break;
//                    }
//                    fileOut.write(buf, 0, read);
//                }
//                return new EsignReturnDto();
//            }



                if (signRst.getStream() != null) {

                    String url=null;
                    if(parm.getOssFileName()!=null ) {
                        InputStream ipt = new ByteArrayInputStream(signRst.getStream());
                        if (parm.getOssFileName().startsWith("/")) {
                            url = oSSUtil.upLoadInputStream(ipt, "esgin" + parm.getOssFileName());
                        } else {
                            url = oSSUtil.upLoadInputStream(ipt, "esgin/" + parm.getOssFileName());
                        }
                        log.info("E签宝签章后PDF,OSS文件地址. URL: {}" , url);
                        esignReturnDto.setOssurl(url);
                    }
                }
            }else {
                throw new RuntimeException("esign未传入用户名字");
            }



        }
        catch (Exception eex){

            log.error("Esign平台自身签署程序异常",eex);
            return BaseReturnDto.error(eex.getMessage());
        }


        return BaseReturnDto.success(esignReturnDto);
    }


    public BaseReturnDto<EsignReturnDto> hrSignByPdfStream(EsignParmDto dto) {
        checkParm(dto);
        EsignReturnDto esignReturnDto = new EsignReturnDto();
        try {
            //读取二进制成为pdf文件
//            InputStream inputStream = new ByteArrayInputStream(dto.getSrcPdfBytes());
            //处理freemarker内容,并生成pdf,返回pdf字节流
            InputStream inputStream = new ByteArrayInputStream(doConversion(dealFreeMarkerContent(dto.getFreeMarkerContent(), dto.getParmData())));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
//            InputStream inputStream = new ByteArrayInputStream(dto.getSrcPdfBytes());
//            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
            Document document = new Document(pd);

            int _width=100;
            int _height=100;


            //在原图片上面增加日期
            if(dto.getSealData()!=null) {
                dto.setSealData(addTimestampToBase64Image(dto.getSealData(), dto.getAddFontHeight(), dto.getCharSpacing(), dto.getAddFontSize(),dto.getCreateTime()));


                //将签章转换为 图片，以便获取宽高
                byte[] imageBytes = Base64.getDecoder().decode(dto.getSealData());
                ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
                BufferedImage originalImage = ImageIO.read(bis);
                bis.close();
                //得到图片的宽高
                _width = originalImage.getWidth();
                _height = originalImage.getHeight();


                if (originalImage == null) {
                    throw new IllegalArgumentException("无效的图片数据");
                }

            }


            int pageCount = pd.getNumberOfPages();
            Boolean limitpagenum=false;
            int[] limmitpagenums=null;
            if(dto.getPosPage()!=null && !"".equals(dto.getPosPage())) {
                limitpagenum=isValidFormat(dto.getPosPage());
                limmitpagenums=extractNumbers(dto.getPosPage());
            }
            //遍历每一页
            for (int i = 1; i <= pageCount; i++) {

                if(limitpagenum==true && limmitpagenums!=null && limmitpagenums.length==2){
                    if(i<limmitpagenums[0] || i>limmitpagenums[1]){
                        continue;
                    }
                }

                PdfPage page = pd.getPage(i);

                if(dto.getKeyWord() !=null && !"".equals(dto.getKeyWord()) && dto.getSealData()!=null) {
                    //查找页中的匹配文字，并定位到位置。
                    RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(dto.getKeyWord());
                    PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
                    processor.processPageContent(page);
                    Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();

                    //自定义结果处理
                    if (!resultantLocations.isEmpty()) {
                        for (IPdfTextLocation item : resultantLocations) {
                            Rectangle boundRectangle = item.getRectangle();
//                        System.out.println(item.getText());
                            ImageData imageData = ImageDataFactory.create(Base64.getDecoder().decode(dto.getSealData()));
//                        System.out.println("关键字“" + dto.getKeyWord() + "” 的坐标为 x: " + boundRectangle.getX() + "  ,y: " + boundRectangle.getY());
                            Image image = new Image(imageData).scaleAbsolute(dto.getWidth(), dto.getWidth() * _height / _width).setFixedPosition(i, boundRectangle.getRight() + dto.getPosX(), boundRectangle.getBottom() - dto.getPosY());
                            document.add(image);
                            break;
                        }
                    }
                }
                //如果需要签章用户名字
                if(dto.getSealDataUserName()!=null && dto.getKeyWordUser()!= null){
                    //查找页中的匹配文字，并定位到位置。
                    RegexBasedLocationExtractionStrategy strategy2 = new RegexBasedLocationExtractionStrategy(dto.getKeyWordUser());
                    PdfCanvasProcessor processor2 = new PdfCanvasProcessor(strategy2);
                    processor2.processPageContent(page);
                    Collection<IPdfTextLocation> resultantLocations2 = strategy2.getResultantLocations();

                    //自定义结果处理
                    if (!resultantLocations2.isEmpty()) {
                        for (IPdfTextLocation item : resultantLocations2) {
                            Rectangle boundRectangle2 = item.getRectangle();
//                        System.out.println(item.getText());
                            int addtimestampfontsize=10;
                            int addfontheight=11;
                            if(dto.getSealDataUserName().length()<=4){
                                addtimestampfontsize=11;
                                addfontheight=13;
                            }
                            String textimgbase64=addTimestampToBase64Image(generateTransparentImageWithText(dto.getSealDataUserName()),addfontheight,0,addtimestampfontsize,dto.getCreateTime());
                            ImageData imageData = ImageDataFactory.create(Base64.getDecoder().decode(textimgbase64));

                            //将签章转换为 图片，以便获取宽高
                            byte[] imageBytes2 = Base64.getDecoder().decode(textimgbase64);
                            ByteArrayInputStream bis2 = new ByteArrayInputStream(imageBytes2);
                            BufferedImage originalImage2 = ImageIO.read(bis2);
                            bis2.close();
                            //得到图片的宽高
                            int _width2=originalImage2.getWidth();
                            int _height2=originalImage2.getHeight();

                            dto.setWidthUser(93);
                            if(dto.getSealDataUserName().length()*11>dto.getWidthUser()){
                                dto.setWidthUser(dto.getSealDataUserName().length()*11);
                            }
//                        System.out.println("关键字“" + dto.getKeyWord() + "” 的坐标为 x: " + boundRectangle.getX() + "  ,y: " + boundRectangle.getY());
                            Image image = new Image(imageData).scaleAbsolute(dto.getWidthUser(), dto.getWidthUser()*_height2/_width2).setFixedPosition(i, boundRectangle2.getRight() + dto.getPosXUser(), boundRectangle2.getBottom()-dto.getPosYUser());
                            document.add(image);
                            break;
                        }
                    }
                }
            }
            document.close();
            pd.close();
            //输出文件
            out.close();
            byte[] filebytes=out.toByteArray();
            InputStream ipt = new ByteArrayInputStream(filebytes);

//            if(1==1){
//// 定义一个文件名字进行接收获取文件
//                FileOutputStream fileOut = new FileOutputStream(new File("D:\\_____Work\\aaa_hr.pdf" ));
//                byte[] buf = new byte[1024 * 8];
//                while (true) {
//                    int read = 0;
//                    if (ipt != null) {
//                        read = ipt.read(buf);
//                    }
//                    if (read == -1) {
//                        break;
//                    }
//                    fileOut.write(buf, 0, read);
//                }
//                return new EsignReturnDto();
//            }


            String url=null;
            if(dto.getOssFileName()!=null ) {
                if (dto.getOssFileName().startsWith("/")) {
                    url = oSSUtil.upLoadInputStream(ipt, "esgin_hr" + dto.getOssFileName());
                } else {
                    url = oSSUtil.upLoadInputStream(ipt, "esgin_hr/" + dto.getOssFileName());
                }
                log.info("惠融生成签章文件PDF地址URL:{} " , url);
                esignReturnDto.setOssurl(url);
            }

//            oSSUtil.upLoadStream();


        }catch (Exception e){

            log.error("生成签章pdf文件处理异常",e);
            return BaseReturnDto.error(e.getMessage());
        }

        return BaseReturnDto.success(esignReturnDto);

    }

    /***
     * 匹配数字"2-15" 的格式
     * @param input
     * @return
     */
    public  int[] extractNumbers(String input) {
        if (input == null || input.isEmpty()) {
            return new int[0]; // 返回空数组表示无效输入
        }

        // 正则表达式：匹配类似 "2-15" 的格式
        Matcher matcher = pattern2.matcher(input);

        if (matcher.matches()) {
            int start = Integer.parseInt(matcher.group(1));
            int end = Integer.parseInt(matcher.group(2));
            return new int[]{start, end};
        } else {
            return new int[0]; // 不匹配格式，返回空数组
        }
    }
    public Boolean isValidFormat(String input) {
        if (input == null || input.isEmpty()) {
            return false;
        }
        // 正则表达式：匹配类似 "2-11" 的格式，只允许正整数
        Matcher matcher = pattern.matcher(input);
        return matcher.matches();
    }

    public  String addTimestampToBase64Image(String base64Image, int addfontheight, int charSpacing, int fontSize, Date siggnTime) {
        try {
            // 1. 解码 Base64 为图片
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            BufferedImage originalImage = ImageIO.read(bis);
            bis.close();

            if (originalImage == null) {
                throw new IllegalArgumentException("无效的图片数据");
            }

            // 2. 创建新图片，在下方留出空间添加文字
            int width = originalImage.getWidth();
            int height = originalImage.getHeight() + addfontheight; // 预留文字区域

            BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = newImage.createGraphics();

            // 抗锯齿设置
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 绘制原图
            g2d.drawImage(originalImage, 0, 0, null);

            // 时间戳
            String timestamp = new SimpleDateFormat("yyyy-MM-dd").format(siggnTime);
            String year=timestamp.substring(0,4);
            String month=timestamp.substring(5,7);
            String day=timestamp.substring(8,10);
            timestamp=year+"年"+month+"月"+day+"日";

            Font font = null;
            font=fontManager.getFont(fontSize);
//            try {
//
//                // 获取 InputStream
//                ClassPathResource resource = new ClassPathResource("fonts/simsun.ttf");
//                File fontFile = resource.getFile();
//                log.info(fontFile.getAbsolutePath());
//                if(fontFile.exists()){
//                    log.info("====设置字体ByFileImage=====");
//                    font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
//                }else {
//                    log.info("====设置字体ByFileImage=====");
//                    InputStream inputStream = getFontInput();
//                    font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
//                }
//            } catch (FontFormatException e) {
//                log.error("字体加载失败",e);
//            } catch (IOException e) {
//                log.error("文件不存在",e);
//            }
            // 修复NullPointerException：如果字体加载失败，使用默认字体
            if (font == null) {
                log.error("无法加载自定义字体，使用系统默认字体");
                font = new Font("SansSerif", Font.PLAIN, 11);
            } else {

                // 设置字体大小，比如 24
                font = font.deriveFont(13f);

            }

//        Font font = new Font("Default", Font.CENTER_BASELINE, 15); // 使用宋体，粗体，大小为24
            g2d.setFont(font);

            // 设置颜色，透明度为70%
            Color color = new Color(255, 0, 0, 179); // 红色，透明度为70%
            g2d.setColor(color);
            g2d.setColor(Color.red);

            // 设置起始位置
            int textY = height - 5; // 距离底部10像素
            int currentX = 10; // 初始 X 坐标（可改为居中）

            // 居中计算（总宽度）
            FontMetrics fm = g2d.getFontMetrics();
            int totalWidth = 0;
            for (int i = 0; i < timestamp.length(); i++) {
                totalWidth += fm.charWidth(timestamp.charAt(i));
            }
            totalWidth += charSpacing * (timestamp.length() - 1); // 加上字符间距
            currentX = (width - totalWidth) / 2;

            // 逐个字符绘制，添加字符间距
            for (int i = 0; i < timestamp.length(); i++) {
                char c = timestamp.charAt(i);
                int charWidth = fm.charWidth(c);
                g2d.drawString(String.valueOf(c), currentX, textY);
                currentX += charWidth + charSpacing; // 增加字符宽度 + 间距
            }

            g2d.dispose();

            // 3. 将新图片转为 Base64 返回
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(newImage, "PNG", bos);
            byte[] newImageBytes = bos.toByteArray();
            return Base64.getEncoder().encodeToString(newImageBytes);

        } catch (Exception e) {
            log.error("添加时间戳处理异常",e);
            return null;
        }
    }





    /**
     * 在指定位置添加文字
     *
     * @param pdfDoc   PdfDocument对象
     * @param page     页码（从1开始）
     * @param posX     X坐标
     * @param posY     Y坐标
     * @param text     要添加的文字
     * @param fontSize 字体大小
     */
    public static void addText(PdfDocument pdfDoc, int page, int posX, int posY, String text, int fontSize,String keyWord) throws IOException {
//        PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(page));
        //查找页中的匹配文字，并定位到位置。
        RegexBasedLocationExtractionStrategy strategy = new RegexBasedLocationExtractionStrategy(keyWord);
        PdfCanvasProcessor processor = new PdfCanvasProcessor(strategy);
        PdfPage pdfpage = pdfDoc.getPage(page);
        processor.processPageContent(pdfpage);
        Collection<IPdfTextLocation> resultantLocations = strategy.getResultantLocations();

        float findPosX=-1;
        float findPosY=-1;
        //自定义结果处理
        if (!resultantLocations.isEmpty()) {
            for (IPdfTextLocation item : resultantLocations) {
                Rectangle boundRectangle = item.getRectangle();
                findPosX=boundRectangle.getRight();
                findPosY=boundRectangle.getBottom() ;
                System.out.println(findPosX+"---"+findPosY);
            }
        }
        // 加载字体
//        com.itextpdf.kernel.font.PdfFont font = com.itextpdf.kernel.font.PdfFontFactory.createFont();
//        PdfFont font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H");

        if(findPosX>-1 && findPosY>-1) {
//            // 设置字体和字体大小
//            canvas.beginText()
//                    .setFontAndSize(font, fontSize)
//                    .moveText(findPosX + posX, findPosY + posY)
//                    .showText(text)
//                    .endText();
//            PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(page));

            // 在指定位置插入文字
//            Text textElement = new Text(text)
//                    .setFontColor(com.itextpdf.kernel.colors.ColorConstants.BLACK)
//                    .setFontSize(12);
//            Paragraph paragraph = new Paragraph(textElement);
//            canvas.beginText().setColor(com.itextpdf.kernel.colors.ColorConstants.BLACK,true)
//                    .setFontAndSize(font, fontSize)
//                    .moveText(findPosX + posX, findPosY + posY)
//                    .showText(text)
//                    .endText();
            try (InputStream fontStream = EsignServiceImpl.class.getClassLoader().getResourceAsStream("otherIf-config/siyuan.ttf")) {
                if (fontStream == null) {
                    throw new IOException("Font file not found: otherIf-config/siyuan.ttf");
                }

                // 加载字体文件
                PdfFont font = PdfFontFactory.createFont(inputStreamToByteArray(fontStream), PdfEncodings.IDENTITY_H);
                // 通过PDF页来构建画布
                PdfCanvas pdfCanvas = new PdfCanvas(pdfDoc.getPage(page));

                pdfCanvas.beginText()   // 开启文本
                        .moveText(findPosX+posX, findPosY+posY)           // 设置文本在画布的指定位置
                        .setFontAndSize(font, fontSize)    // 设置文本的样式和大小
                        // 设置文本的呈现方式，这里我设置的是既有描边也有填充
                        .setTextRenderingMode(PdfCanvasConstants.TextRenderingMode.FILL_CLIP)
                        .setStrokeColor(ColorConstants.BLACK)   // 描边绿色
//                        .setFillColor(ColorConstants.BLACK)       // 填充红色
                        .showText(text)
                        .endText();     // 关闭文本
                // 释放画布。使用完画布后，请使用此方法。
                pdfCanvas.release();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }


        }
    }

    public static byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            return byteArrayOutputStream.toByteArray();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }


    public String convertVue(String vueHtml) {
        // 1. 转换插值表达式 {{ expression }} -> ${expression}
        vueHtml = vueHtml.replaceAll("\\{\\{\\s*(.*?)\\s*}}", "\\${$1}");

        // 2. 转换 v-if 指令
        Pattern vIfPattern = Pattern.compile("<(\\w+)\\s+v-if=\"([^\"]+)\"([^>]*)>");
        Matcher vIfMatcher = vIfPattern.matcher(vueHtml);
        StringBuffer result = new StringBuffer();
        while (vIfMatcher.find()) {
            String tag = vIfMatcher.group(1); // 标签名
            String condition = vIfMatcher.group(2); // 条件表达式
            String attributes = vIfMatcher.group(3); // 其他属性
            // 替换为 FreeMarker 的 <#if> 标签
            vIfMatcher.appendReplacement(result, "<#if " + condition + "><" + tag + attributes + ">");
        }
        vIfMatcher.appendTail(result);
        vueHtml = result.toString();

        // 3. 转换 v-for 指令
        Pattern vForPattern = Pattern.compile("<(\\w+)\\s+v-for=\"(\\w+)\\s+in\\s+([^\"]+)\"([^>]*)>");
        Matcher vForMatcher = vForPattern.matcher(vueHtml);
        result = new StringBuffer();
        while (vForMatcher.find()) {
            String tag = vForMatcher.group(1); // 标签名
            String item = vForMatcher.group(2); // 循环变量
            String collection = vForMatcher.group(3); // 集合
            String attributes = vForMatcher.group(4); // 其他属性
            // 替换为 FreeMarker 的 <#list> 标签
            vForMatcher.appendReplacement(result, "<#list " + collection + " as " + item + "><" + tag + attributes + ">");
        }
        vForMatcher.appendTail(result);
        vueHtml = result.toString();

        // 4. 添加结束标签 </#if> 和 </#list>
        vueHtml = vueHtml.replaceAll("</(\\w+)>", "</$1></#if></#list>");

        return vueHtml;
    }

    public  String generateTransparentImageWithText(String userName) {
        // 创建一个宽度为100像素，高度为50像素的透明背景图片
        int width = 130;
        if(userName.length()*13>width){
            width = userName.length()*13;
        }
        int height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // 获取Graphics2D对象以绘制图像
        Graphics2D g2d = image.createGraphics();

        // 创建 ClassPathResource 对象
//        Resource resource = new ClassPathResource("fonts/simsun.ttf");

//
//        String classPath = HtmlToPDFUtil.class.getResource("/").getPath() + "fonts"+"/simsun.ttf";
//        System.out.println(classPath);
        // 设置字体
        Font font = null;
        font=fontManager.getFont(11);
//        try {
//            // 获取 InputStream
//            ClassPathResource resource = new ClassPathResource("fonts/simsun.ttf");
//            File  fontFile = resource.getFile();
//            if(fontFile.exists()) {
//                log.info("====设置字体ByFileImage2=====");
//                font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
//            }else {
//                log.info("====设置字体ByinputStreamImage2=====");
//                InputStream inputStream = getFontInput();
////            Resource resource = new ClassPathResource("fonts/simsun.ttf");
//                font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
//            }
//        } catch (FontFormatException e) {
//            log.error("字体加载失败");
//        } catch (IOException e) {
//            log.error("文件不存在");
//        }

        // 修复NullPointerException：如果字体加载失败，使用默认字体
        if (font == null) {
            log.error("无法加载自定义字体，使用系统默认字体");
            font = new Font("SansSerif", Font.PLAIN, 11);
        } else {
            if(userName.length()<=4){
                font = font.deriveFont(15f);
            }else {
                // 设置字体大小，比如 24
                font = font.deriveFont(13f);
            }
        }

//        Font font = new Font("Default", Font.CENTER_BASELINE, 15); // 使用宋体，粗体，大小为24
        g2d.setFont(font);

        // 设置颜色，透明度为70%
        Color color = new Color(255, 0, 0, 179); // 红色，透明度为70%
        g2d.setColor(color);

        // 计算文本的位置
        String text = userName;
        int x = (width - g2d.getFontMetrics().stringWidth(text)) / 2; // 水平居中
        int y = (height + g2d.getFontMetrics().getAscent()) / 2; // 垂直居中

        // 绘制文本
        g2d.drawString(text, x, y);

        // 释放资源
        g2d.dispose();

        // 将BufferedImage转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", baos);
        } catch (IOException e) {
            log.error("Esign将图片文件转化为字节数组字符串，并对其进行Base64编码处理异常，异常信息：{}", e.getMessage(), e);
            return null;
        }

        // 将字节数组转换为Base64字符串
        byte[] imageBytes = baos.toByteArray();
        String base64Image = Base64.getEncoder().encodeToString(imageBytes);

        return base64Image;
    }

    public byte[] doConversion(String htmlDocument) throws InvalidParameterException, IOException {
        PD4ML pd4ml = new PD4ML();
        pd4ml.enableDebugInfo();
        pd4ml.setHtmlWidth(userSpaceWidth);
        pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
        pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
        pd4ml.addStyle("BODY {margin: 0; font-family:MSJH;}", true);//background:#111;
        pd4ml.addStyle(".table {display: flex;flex-direction: column;width: 100%;height: auto;gap: 0;border: 1px solid #333;}",true);
        pd4ml.addStyle(".table .table-label {width: 100%;font-weight: 600;display: grid;grid-template-columns: 30px 40px 40px 1fr 1fr 30px;}",true);
        pd4ml.addStyle(".table .table-row {width: 100%;display: grid;grid-template-columns: 30px 40px 40px 1fr 1fr 30px;}",true);
        pd4ml.addStyle(".table .table-row div {display: flex;justify-content: center;align-items: center;box-sizing: border-box;border: 1px solid #333;height: auto;line-height: 1.5;word-break: break-all;}",true);
        pd4ml.addStyle("/* 表格整体样式 */\n" +
                "        table {\n" +
                "            width: 100%; /* 表格宽度占满父容器 */\n" +
                "            border-collapse: collapse; /* 合并边框 */\n" +
                "            text-align: center; /* 文字居中对齐 */\n" +
                "        }\n" +
                "\n" +
                "        /* 表头样式 */\n" +
                "        th {\n" +
                "             text-align:center; "+
                "            font-weight: bold; /* 加粗 */\n" +
                "            border: 1px solid #333; /* 边框 */\n" +
                "        }\n" +
                "\n" +
                "        /* 表格单元格样式 */\n" +
                "        td {\n" +
                "       text-align: center; vertical-align: middle;"+
                "            border: 1px solid #333; /* 边框 */\n" +
                "        }\n" +
//                "\n" +
//                "        /* 表格行样式 */\n" +
//                "        tr:nth-child(even) {\n" +
//                "            background-color: #f9f9f9; /* 偶数行背景颜色（浅灰色） */\n" +
//                "        }\n" +
//                "\n" +
                "        /* 表格标题样式 */\n" +
                "        caption {\n" +
                "            font-weight: bold; /* 加粗 */\n" +
                "        }",true);
        String classPath = HtmlToPDFUtil.class.getResource("/") + "fonts";
        pd4ml.useTTF(classPath, true);
        pd4ml.setDefaultTTFs("SimSun", "SimSun", "SimSun");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        pd4ml.render(new StringReader(htmlDocument), byteArrayOutputStream);
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 处理FreeMarker模板
     * @param html
     * @param map
     * @return
     */
    private String dealFreeMarkerContent(String html, Map<String, Object> map) {
        // 边界检查
        if (html == null || html.isEmpty() || map == null || map.isEmpty()) {
            return html; // 如果模板或参数为空，直接返回原始模板
        }
        if(map==null){
            map=new HashMap<>();
        }

        try {
            // 创建 FreeMarker 配置对象
            Configuration cfg = new Configuration();
            cfg.setClassicCompatible(true);
            cfg.setLogTemplateExceptions(false);
            cfg.setWrapUncheckedExceptions(true);
            BeansWrapper wp= new BeansWrapper();
            cfg.setObjectWrapper(wp);

            // 将 HTML 内容包装为 FreeMarker 模板
            Template template = new Template("templateName", new StringReader(html), cfg);

            // 创建 StringWriter 用于捕获输出
            StringWriter writer = new StringWriter();

            // 使用 FreeMarker 处理模板并生成结果
            template.process(map, writer);

            // 返回渲染后的字符串
            return writer.toString();
        } catch (Exception e) {
            // 捕获异常并返回原始 HTML 或错误信息
            log.error("EsignService Error processing template", e);
            return html; // 或者返回错误信息，例如 "Error processing template"
        }
    }

    private void checkParm(EsignParmDto parm){
        if(parm==null){
            throw new IllegalArgumentException("参数不能为空");
        }
//        if(parm.getKeyWord()==null){
//            throw new IllegalArgumentException("KeyWord不能为空");
//        }
        if(parm.getKeyWordUser()==null){
            throw new IllegalArgumentException("KeyWordUser不能为空");
        }
        if(parm.getFreeMarkerContent()==null){
            throw new IllegalArgumentException("freeMarkerContent不能为空");
        }
//        if(parm.getCreateTime()==null){
//            throw new IllegalArgumentException("订单日期不能为空");
//        }

    }

    public ByteArrayInputStream getFontInput() throws IOException {
        if(fontBytes==null) {
            Resource resource = new ClassPathResource("fonts/simsun.ttf");
//            BufferedInputStream bufferedInputStream = new BufferedInputStream(resource.getInputStream());
//            byte[] buffer = new byte[bufferedInputStream.available()];
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            FileCopyUtils.copy(resource.getInputStream(), outputStream);
            fontBytes = outputStream.toByteArray();
        }
        return  new ByteArrayInputStream( fontBytes);
    }


    public static void main(String[] args) {

        EsignServiceImpl imp2=new EsignServiceImpl();
        int addtimestampfontsize=10;
        int addfontheight=13;
        String name="余珊珊";
        if(name.length()<=4){
            addtimestampfontsize=11;
            addfontheight=20;
        }

//        String textimgbase64=imp2.addTimestampToBase64Image(imp2.generateTransparentImageWithText("但是给让的发过热的速度国际法的方式上如果的时光撒给他各色人等一个看和给"),13,0,12,new Date());
        String textimgbase64=imp2.addTimestampToBase64Image(imp2.generateTransparentImageWithText("余珊珊"),addfontheight,0,addtimestampfontsize,new Date());

        ImageData imageData = ImageDataFactory.create(Base64.getDecoder().decode(textimgbase64));
        String srcPdfPath3="D:\\_____Work\\" + "pp.png";
        //将签章转换为 图片，以便获取宽高
        byte[] imageBytes2 = Base64.getDecoder().decode(textimgbase64);
//        ByteArrayInputStream bis2 = new ByteArrayInputStream(imageBytes2);
//        File file2 = new File("D:\\_____Work\\" + "pp.png");
        try {

            FileOutputStream fos = new FileOutputStream(srcPdfPath3);
            fos.write(imageBytes2);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(1==1){
            return ;
        }

        String srcPdfPath = "D:\\_____Work\\" + "test.pdf";
//        String srcPdfPath2 = "D:\\Auth\\tech2\\PaaS_SDKDemoForJava_3.0.20\\PaaS_SDKDemoForJava_3.0.20\\pdf\\" + "xieyi_test_del.pdf";
//        srcPdfPath2="D:\\test3.pdf";
//        RestTemplate myrestTemplate =new RestTemplate();
//
//        // 设置请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Content-Type", "application/x-www-form-urlencoded");
//
//        // 准备要发送的数据
//        String bodystr = "https://link.hrshuke.cn/view/agreement-new/agreement-personalV2.html?appId=33&userId=123123&time=2025-1-1&phone=13111111111&isAlliance=3";
//        bodystr="https://link.hrshuke.cn/view/agreement/agreement-personal-qdts-2-new.html?appId=453&time=2025-1-1&userId=448436589149760&phone=13511111111&name=%E5%BC%A0%E4%B8%89";
//        // 构建URL
//        String baseUrl = "http://your-target-url.com/endpoint";  // 替换为实际的URL
//        // 准备要发送的数据
//        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
//        body.add("url", bodystr);
//
//
//        // 创建HttpEntity对象，它包含了请求头和请求体
//        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
//
//        // 目标URL
//        String url = "http://192.168.1.170:20001/geturl";  // 替换为实际的URL
////        url = "http://localhost:20001/geturl";
//
//        // 发送POST请求并接收响应
//        ResponseEntity<String> response = myrestTemplate.exchange(url, HttpMethod.POST, request, String.class);
//
//        // 输出响应状态码
//        System.out.println("Response Status Code: " + response.getStatusCode());
//
//        // 获取并打印响应体
//        String responseBody = response.getBody();
////        System.out.println(responseBody);
//// 解码Base64字符串
//        byte[] decodedBytes = Base64.getDecoder().decode(responseBody);
//        try {
//            //读取二进制成为pdf文件
//            InputStream inputStream = new ByteArrayInputStream(decodedBytes);
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
//            //            InputStream inputStream = new ByteArrayInputStream(dto.getSrcPdfBytes());
//            //            PdfDocument pd = new PdfDocument(new PdfReader(inputStream), new PdfWriter(out));
//            Document document = new Document(pd);
//
//            int pageCount = pd.getNumberOfPages();
//            PdfPage pdpage=pd.getPage(1);
//
//            addText(pd, 1, 11, 0, "李三武", 10, "本人姓名");
//            pd.close();
//            out.close();
//            FileOutputStream fos = new FileOutputStream(srcPdfPath2);
//            fos.write(out.toByteArray());
//        }catch (Exception e){
//            e.printStackTrace();
//        }


//        // 指定输出文件路径
//        String outputFilePath = "output3.pdf";
//
//        try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
//            // 将解码后的字节数组写入文件
//            fos.write(decodedBytes);
//            System.out.println("PDF文件已成功保存到: " + outputFilePath);
//        } catch (IOException e) {
//            e.printStackTrace();
//            System.err.println("保存PDF文件时发生错误: " + e.getMessage());
//        }

//        // 设置WebDriver路径
//        System.setProperty("webdriver.chrome.driver", "path/to/your/chromedriver");  // 替换为你的WebDriver路径
//
//        // 启动WebDriver
//        ChromeOptions options = new ChromeOptions();
//
//
//        options.addArguments("--headless");  // 无头模式，不打开浏览器窗口
////        WebDriver driver = new ChromeDriver(options);
////        WebDriver driver =new ChromeDriver();
//
//        // 获取并渲染网页
//        String url = "https://example.com";  // 替换为你需要抓取的网页URL
////        driver.get(url);
//        try {
//            Thread.sleep(5000);  // 等待页面加载完成（根据实际情况调整等待时间）
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//
//        // 获取渲染后的HTML内容
//        WebElement body = driver.findElement(By.tagName("body"));
//        String htmlContent = body.getAttribute("outerHTML");
//
//        // 关闭WebDriver
//        driver.quit();
//
//        // 将HTML内容转换为PDF
//        try {
//            File pdfFile = new File("output.pdf");
//            FileOutputStream fos = new FileOutputStream(pdfFile);
//            HtmlConverter.convertToPdf(htmlContent, fos);
//            fos.close();
//            System.out.println("PDF文件已成功保存: " + pdfFile.getAbsolutePath());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        /***
         int page = 1;  // 要修改的页码（从1开始）
         int posX = 36;  // X坐标
         int posY = 750;  // Y坐标
         String text = "Hello, iText 7!";  // 要添加的文字
         int fontSize = 12;  // 字体大小

         try {
         // 创建PdfReader和PdfWriter
         PdfReader reader = new PdfReader(srcPdfPath);
         PdfWriter writer = new PdfWriter(srcPdfPath2);
         PdfDocument pdfDoc = new PdfDocument(reader, writer);

         // 获取指定页面
         PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(page));

         // 添加文字
         addText(canvas, pdfDoc, page, posX, posY, text, fontSize);

         // 关闭文档
         pdfDoc.close();
         } catch (Exception e) {
         e.printStackTrace();
         }

         ***/
        String sss="<html lang=\"en\">\n" +
                "  <head>\n" +
                "    <meta charset=\"utf-8\" />\n" +
                "    <meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\" />\n" +
                "    <meta name=\"format-detection\" content=\"telephone=no\" />\n" +
                "    <meta content=\"yes\" name=\"apple-mobile-web-app-capable\" />\n" +
                "    <meta content=\"yes\" name=\"apple-touch-fullscreen\" />\n" +
                "    <meta content=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />\n" +
                "    <link rel=\"stylesheet\" href=\"css/common.css\" />\n" +
                "    <script type=\"text/javascript\" src=\"https://loansm.oss-cn-hangzhou.aliyuncs.com/js/jquery-2.2.3.min.js\"></script>\n" +
                "    <script type=\"text/javascript\" src=\"https://common-libs-web.oss-cn-hangzhou.aliyuncs.com/mobile-detect.min.js\"></script>\n" +
                "    <script type=\"text/javascript\" src=\"https://loansm.oss-cn-hangzhou.aliyuncs.com/js/vue2.js\"></script>\n" +
                "    <script type=\"text/javascript\" src=\"../../src/js/tools.js\"></script>\n" +
                "    <script type=\"text/javascript\" src=\"../../src/js/config.js\"></script>\n" +
                "    <title>个人信息共享授权书</title>\n" +
                "    <style>\n" +
                "      [v-cloak] {\n" +
                "        display: none;\n" +
                "      }\n" +
                "    </style>\n" +
                "  </head>\n" +
                "\n" +
                "  <body>\n" +
                "    <div class=\"container\" id=\"app\">\n" +
                "      <p class=\"MsoNormal\" align=\"center\" style=\"text-align: center; font-family: DengXian; font-size: 12px\">\n" +
                "        <b><span style=\"font-family: 华文宋体; line-height: 35.2px; font-size: 20px\">个人信息共享授权书</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 35.2px; font-size: 22px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">重要提示：</span></b\n" +
                "        ><b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span></b>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b\n" +
                "          ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"\n" +
                "            ><span>为维护您（以下简称</span\n" +
                "            >“本人”或“您”）的合法权益，请在线签署《个人信息共享授权书》（以下简称“本授权书”）前，仔细阅读、充分理解本授权书各条款内容，特别是免除或减轻</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">{{companyName}}</span\n" +
                "        ><b\n" +
                "          ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"><span>（以下简称</span>“被授权人”）责任</span></b\n" +
                "        ><b\n" +
                "          ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"\n" +
                "            >，或限制您权利的条款，其中免除或减轻责任条款将以黑体加粗形式提示您。您点击本授权书所在页面按钮并进入下一页面或勾选本授权书即视为您已阅读本授权书，并同意接受本授权书条款的约束，本授权书即完成在线签署并生效。</span\n" +
                "          ></b\n" +
                "        ><b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span></b>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"><span>本人姓名：</span>${realName}</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"><span>本人身份证号码：</span>${idCardNo}</span></b\n" +
                "        ><b\n" +
                "          ><i><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span></i></b\n" +
                "        ><b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"\n" +
                "          >（为了保护您的个人信息，本授权书在向您展示时将部分隐藏您的身份信息，您的身份信息详情以您在本平台账户对应的实名信息为准）</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">一、定义</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">1、个人信息，指您的如下信息：</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"><span>（</span>1）</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">个人识别信息</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">，指您的</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">手机号码、微信号</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"\n" +
                "          ><span>，以及平台通过向您申请电话状态权限</span>/IDFA权限、位置权限（如涉及）而收集的您的</span\n" +
                "        ><b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            ><span>唯一设备识别码（</span>IMEI、IMSI）、IP地址、地理位置。</span\n" +
                "          ></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"><span>（</span>2）</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">个人资质信息</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">，指您的</span\n" +
                "        ><b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            ><span\n" +
                "              >姓名、年龄、户籍、现居住地址、婚姻状况、配偶信息（如涉及）、常用邮箱地址、房产情况（房产类型、房产价值等）、车辆情况（车辆品牌、车辆价值等）、工资发放形式、教育程度、信用情况（芝麻信用分、逾期信息等）、社保情况、公积金情况、信用卡情况、商业保单情况、月工资收入、职业类型、经营企业情况、单位</span\n" +
                "            >/公司名称、单位/公司电话、单位/公司地址、单位/公司性质、紧急联系人信息、贷款用途（具体以您在页面实际填写的信息为准）</span\n" +
                "          ></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">。其中</span\n" +
                "        ><b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">紧急联系人信息指您与紧急联系人的关系、紧急联系人的姓名及电话</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">，配偶信息指</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">您配偶的姓名、身份证号、工作电话及联系电话</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">。</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"><span>（</span>3）</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">个人账户信息</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">，指您的</span\n" +
                "        ><b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">银行卡号、开户行、开户行地址、预留手机号。</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"\n" +
                "          >2、贷款/助贷机构，指为您提供贷款服务或贷款咨询服务的机构，在本授权书下机构指</span\n" +
                "        >\n" +
                "        <span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">{{ companyText || '根据您个人信息匹配出的机构列表上的机构' }}</span>\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"> 及其前述机构的分支机构、关联方。</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: 400\">\n" +
                "          3、广告及分析服务类提供商，指受被授权人委托对您的产品需求/偏好进行评估，\n" +
                "          并向您推荐您需要的贷款产品及服务的第三方机构，具体详见本协议附件所列的第三方公司。\n" +
                "        </span>\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"\n" +
                "          >4、信用机构及数据服务商，指基于被授权人委托，向被授权人提供您的身份识别信息、风险识别信息、资质评估信息、表征信用情况的综合评分或信用评级的第三方机构，具体详见本协议附件所列的第三方公司。</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">二、授权内容</span></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >1、 在平台为您提供服务过程中，为了便于被授权人向您推荐适合您的贷款产品，您授权被授权人收集并存储您提交的个人信息。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >2、为了便于贷款/助贷机构根据您的资信情况对您进行授信评估，确定您是否满足监管机构要求及最终是否向您放款，以实现您的借款交易目的，您授权被授权人将您的个人识别信息、个人资质信息、个人账户信息（如涉及）共享给贷款/助贷机构，同时授权贷款/助贷机构基于前述目的收集、存储、使用、分析您的个人信息。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >3、为了对您的产品需求/偏好进行评估，并向您推荐平台产品及服务，您授权被授权人将您的个人识别信息共享给广告及分析服务类提供商，同时授权广告及分析服务类提供商分析评估您的产品需求/偏好，并将分析评估结果反馈给被授权人或者直接根据分析评估结果向您拨打电话为您推荐产品。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >4、为了对您的信用状况进行评估，以为您提供您选择的金融产品或服务，您授权被授权人将您的姓名、手机号码、身份证号共享给信用机构及数据服务商进行分析处理，并将处理后的信息分析结果反馈给被授权人，同时授权信用机构及数据服务商基于您的前述个人信息获取您的身份识别信息、风险识别信息、资质评估信息、表征信用情况的综合评估或信用评级，并将前述结果提供给被授权人。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >5、您已经充分认识到您的财产性信息对您而言是私密且重要的信息（本授权书项下的财产性信息包括您的住房性质、公积金情况、社保情况、车辆情况、月工资收入、商业保单情况、企业主情况、信用情况及个人账户信息），您已经充分理解并知悉提供和使用财产性信息的风险，这些风险包括但不限于：纳入这些信息对您的信用评级（评分）、信用报告等结果可能产生不利影响，该等信息被被授权人依法提供给第三方后被他人不当利用的风险，因您的信用状况较好而造成您被第三方推销产品或服务等打扰的风险等。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <!-- 新增同业联盟协议 -->\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">三、个人信息的共享</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span></b\n" +
                "      ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span\n" +
                "      ><b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">\n" +
                "          为了获取合作机构的具体产品或服务，您授权同意我们将收集的个人信息共享给如下合作机构：\n" +
                "        </span></b\n" +
                "      ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">四、授权期限</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"\n" +
                "          >本授权书自您签署时生效。授权期限自本授权书生效之日起至您与我们的业务终止之日止，</span\n" +
                "        ><b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >但在授权有效期内我们已实施的行为及依其自身性质需在授权终止后实施或需持续实施的行为，不受授权终止的影响。本授权书具有独立法律效力，不因您签署的任何业务合同或协议成立与否、效力状态变化（包括但不限于部分或全部条款无效或被撤销而无效或失效）的影响。</span\n" +
                "          ></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">五、争议解决</span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"\n" +
                "          >若本人与被授权人发生任何纠纷或争议，应友好协商解决。</span\n" +
                "        ><b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >协商解决不成的，本人同意将纠纷或争议提交至本授权书签订地（即重庆市两江新区）有管辖权的人民法院</span\n" +
                "          ></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">。</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"\n" +
                "            >六、本人已知悉本授权书所有内容（特别是加粗字体内容）的意义及由此产生的法律效力，自愿作出上述授权，本授权书是本人真实的意思表示，本人同意承担由此带来的一切法律后果。</span\n" +
                "          ></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" align=\"right\" style=\"text-align: right; font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" align=\"right\" style=\"text-align: right; font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"><span>您的登录账号：</span></span\n" +
                "        ><b><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\" v-cloak> {{phone}} </span></b\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" align=\"right\" style=\"text-align: right; font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"><span>您的</span>UID：</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\" v-cloak>{{uid}}</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\">&nbsp;</span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <b\n" +
                "          ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"><span>七、</span> <span>附件：</span></span></b\n" +
                "        ><span style=\"line-height: 22.4px; font-size: 14px; font-weight: 700\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\">广告及分析服务类提供商的名称及联系方式：</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\"\n" +
                "          ><span>（</span>1）杭州天谷信息科技有限公司（浙江省杭州市西湖区西斗门路3号天堂软件园D幢19层）；</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <p class=\"MsoNormal\" style=\"font-family: DengXian; font-size: 12px; text-indent: 21px\">\n" +
                "        <span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px; font-weight: normal\">联系方式：400-0878-198</span\n" +
                "        ><span style=\"font-family: 华文宋体; line-height: 22.4px; font-size: 14px\"></span>\n" +
                "      </p>\n" +
                "      <div style=\"height: 60px\"></div>\n" +
                "    </div>\n" +
                "  </body>\n" +
                "  \n" +
                "</html>";



        //这个是盖章图片的base64编码
        String sealData = " ";
        EsignServiceImpl imp=new EsignServiceImpl();
        //预留了45的文字高度
//        sealData=imp.addTimestampToBase64Image(sealData,45,6,43);
        try{
//        try (FileInputStream fis = new FileInputStream(srcPdfPath);
//             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
//            byte[] buffer = new byte[1024]; // 定义一个缓冲区
//            int length;
//            while ((length = fis.read(buffer)) != -1) { // 读取文件并写入到baos中
//                baos.write(buffer, 0, length);
//            }
//            byte[] data = baos.toByteArray(); // 获取byte数组

            // 签署文件信息
            EsignParmDto file = new EsignParmDto();
            file.setCreateTime(new Date());
            Map parmData=new HashMap();
            parmData.put("realName","赵某某");
            parmData.put("companyName","公司A");
            parmData.put("idCardNo","22222222222222222222222");
            file.setFreeMarkerContent(sss);
            file.setParmData(parmData);
            file.setSealData(sealData);
            file.setWidth(116);

            //向右移动20
            file.setPosX(20);
            //向下移动50
            file.setPosY(50);
//            file.setKeyWord("甲方盖章");

            //限制在哪几页盖章
            file.setPosPage("1-1");

            //下面是测试代码，盖在名字上面
//            file.setKeyWord("个人资质信息");
            //向左移动70
            file.setPosX(-70);
            //向下移动65
            file.setPosY(65);

            file.setPosYUser(5);
            file.setPosXUser(60);
            file.setWidthUser(60);
            file.setKeyWordUser("赵某某");
            file.setSealDataUserName("赵大成");

            file.setSealDataUserName("赵大成");
            file.setWidthUser(80-20);
            file.setPosYUser(3+5);
            file.setPosXUser(70-50);
            file.setKeyWordUser("赵某某");

            file.setOssFileName("esign/test.pdf");
//            EsignServiceImpl imp=new EsignServiceImpl();
//            imp.hrSignByPdfStream(file);
            String srcPdfPath2 = "D:\\Auth\\tech2\\PaaS_SDKDemoForJava_3.0.20\\PaaS_SDKDemoForJava_3.0.20\\pdf\\" + "test_del2.pdf";

            EsignServiceImpl impl=new EsignServiceImpl();
            try {
                BaseReturnDto<EsignReturnDto> rt=impl.hrSignByPdfStream(file);
//                EsignReturnDto rt=impl.platformSignByPdfStream(file);
                EsignReturnDto rrr=rt.getData();
                System.out.println(rt.getData().getOssurl());
            } catch (Exception e) {
//            throw new RuntimeException(e);
                e.printStackTrace();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
