package com.engine.htsc.seal.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.seal.entity.*;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import weaver.conn.RecordSet;
import weaver.docs.docs.util.CreateDocUtil;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.htsc.gwlc.WrokflowToOAUtil;
import weaver.interfaces.htsc.wpscenter.impl.ConvertDocToPdf;
import weaver.wps.officed.ConvertToPdf;
import weaver.wps.officed.OfficedWatermark;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipInputStream;

public class SendManualSignService extends Service {

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //我不是故意写这么多重复代码的，但是写重复代码真的好省事啊，不同流程不同入口进来绝对不会进错省了好多状态位参数和if判断（双手合十）

    /**
     * 总部用印申请触发电子签章-文件
     * @param user
     * @param requestid
     * @param docids
     * @return
     */
    public String sendFromApplicationFile(User user, String requestid, String docids, String yzType){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        bs.writeLog("sendFromApplicationFile start:"+requestid);

        try{
            ManualSignEntity manualSignEntity = initialization(user,requestid);
            String code = "";
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));//骑缝章
            if("LH".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeLH"));//统一信用代码-联合
            }else if("ZG".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZG"));//统一信用代码-资管
                sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfzZG"));//骑缝章
            }else if("CX".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeCX"));//统一信用代码-创新
            }else if("ZJ".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZJ"));//统一信用代码-紫金
            }else{
                code = Util.null2String(pb.getPropName("AutoSign.code"));//统一信用代码
            }

            String tableName = JAVATools.getMaintable(requestid);
            MessageDetailLog messageDetailLog = new MessageDetailLog(tableName);

            String mainid = "";
            String yz = "";
            String sql = "select id,yz from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                yz = Util.null2String(rs.getString("yz"));
            }
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }else if(StringUtils.isEmpty(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }

            List<DocSign> docSignList = new ArrayList<>();
            List<String> docidList = Arrays.asList(docids.split(","));
            for(String docid:docidList){
                DocSign docSign = new DocSign();
                String pdfid = getPdfid(docid);
                if(StringUtils.isEmpty(pdfid)){
                    resobject.put("status","500");
                    resobject.put("error","查询文件结果为null,请检查参数");
                    return resobject.toJSONString();
                }else {
                    String update_sql="update "+tableName+"_dt7 set zpdfhwj = '"+pdfid+"' where mainid = '"+mainid+"' and wjmc ='"+docid+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);
                }

                //文件类型
                String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));
                docSign.setDocType(doctype);
                //签署类型
                docSign.setSignMethod("ORDER");
                //签署开始时间-签署结束时间
                docSign.setValidityStartDate(sdf.format(new Date()));
                docSign.setValidityEndDate(getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));

                //签署方信息
                List<Signer> signerList = new ArrayList<>();
                String yzcode = getSignCode(yz,yzType);
                if ("".equals(yzcode)) {
                    resobject.put("status","500");
                    resobject.put("error","未找到对应的印章ID");
                    return resobject.toJSONString();
                }
                if("ZB".equals(yzType)||"ZG".equals(yzType)){
                    yzcode+=","+sealIdqfz;
                }
                Signer signer = new Signer();
                signer.setCode(code);
                signer.setCodeType("USC");
                signer.setRevokeFlag("false");
                signer.setSealId(yzcode);
                signer.setSignNum("1");
                signer.setOwnerType("INSIDE");
                signer.setSignatoryType("ENTERPRISE");
                signer.setKeyWord("华泰证券股份有限公司签章");
                signer.setSignMethod("TRUSTEESHIP");
                signer.setSignedExamine("DISABLE");
                signerList.add(signer);
                docSign.setSigners(signerList);

                //文件路径-文件名称
                Map<String, String> pdfMap = getLatestVersionPDF(requestid, pdfid);
                if (pdfMap.isEmpty()) {
                    resobject.put("status","500");
                    resobject.put("error","上传挂载正文PDF文件出错");
                    return resobject.toJSONString();
                }
                docSign.setFileAttachPatch(pdfMap.get("mountpath"));
                docSign.setFileNameDisplay(pdfMap.get("imagefilename"));

                sql = "select id,dsmdy,dzyyfs,yqxdyr,fwdyfs from "+tableName+"_dt7 where mainid = '"+mainid+"' and wjmc = '"+docid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    //文件编码
                    String id = Util.null2String(rs.getString("id"));
                    String signDocid = id+"_"+docid+"_"+getDatetime();
                    docSign.setDocId(signDocid);
                    String update_sql = "update "+tableName+"_dt7 set yyid = '"+signDocid+"' where id = '"+id+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);

//                    //骑缝章是否跳页加盖
//                    String dsmdy = Util.null2String(rs.getString("dsmdy"));
//                    if("0".equals(dsmdy)){//单面打印
//                        docSign.setAcrossSealSkipPage("DISABLE");
//                    }else if("1".equals(dsmdy)){//双面打印
//                        docSign.setAcrossSealSkipPage("ENABLE");
//                    }

                    //交付类型
                    String dzyyfs = Util.null2String(rs.getString("dzyyfs"));
                    if("0".equals(dzyyfs)){ //电子件
                        docSign.setEffectType("ELECTRONIC");
                    }else if("1".equals(dzyyfs)){//电子防伪件
                        docSign.setEffectType("PAPER");
                        //骑缝章是否跳页加盖
                        String dsmdy = Util.null2String(rs.getString("dsmdy"));
                        if("0".equals(dsmdy)){//单面打印
                            docSign.setAcrossSealSkipPage("DISABLE");
                        }else if("1".equals(dsmdy)){//双面打印
                            docSign.setAcrossSealSkipPage("ENABLE");
                        }
                        String yqxdyr = Util.null2String(rs.getString("yqxdyr"));
                        Map<String,String> map= getUserMap(yqxdyr,String.valueOf(user.getUID()));

                        if(map!=null&&map.size()>0){
                            //防伪打印信息
                            PrintSetting printSetting = new PrintSetting();
                            String fwdyfs = Util.null2String(rs.getString("fwdyfs"));
                            printSetting.setPersonName(map.get("username"));
                            printSetting.setPersonNum(map.get("usrlogins"));
                            printSetting.setPrintNum(fwdyfs);
                            docSign.setPrintSetting(printSetting);
                        }
                    }else if("2".equals(dzyyfs)){
                        docSign.setEffectType("NOWATERMARK");
                    }else{
                        resobject.put("status","500");
                        resobject.put("error","请选择电子用印方式");
                        return resobject.toJSONString();
                    }
                }
                docSignList.add(docSign);
            }
            manualSignEntity.setDocSigns(docSignList);
            bs.writeLog("manualSignEntity:"+JSON.toJSONString(manualSignEntity));
            messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(manualSignEntity),"1",messageDetailLog.Other);

            //触发手动签章
            String response = htUtil.ManualSignPost(JSONArray.toJSON(manualSignEntity).toString());
            bs.writeLog(response);
            if(StringUtils.isEmpty(response)){
                resobject.put("status","500");
                resobject.put("error","手动签章接口返回结果为空");
                return resobject.toJSONString();
            }
            JSONObject res = JSONObject.parseObject(response);
            String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
            String message = Util.null2String(res.get("message"));
            bs.writeLog("status:"+status);
            bs.writeLog("message:"+message);
            if(!"200".equals(status)){
                resobject.put("status","500");
                resobject.put("error","送e-seal用印失败");
                updateSignStatus(tableName+"_dt7",mainid,docids,"4");
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                return resobject.toJSONString();
            }
            updateSignStatus(tableName+"_dt7",mainid,docids,"2");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","送e-seal用印失败");
            return resobject.toJSONString();
        }

        bs.writeLog("sendFromApplicationFile end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    /**
     * 总部用印申请触发电子签章-证照
     * @param user
     * @param requestid
     * @param fzids
     * @return
     */
    public String sendFromApplicationLicense(User user, String requestid, String fzids, String yzType){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        bs.writeLog("sendFromApplicationLicense start:"+requestid);

        try{
            ManualSignEntity manualSignEntity = initialization(user,requestid);
            String code = "";
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));//骑缝章
            if("LH".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeLH"));//统一信用代码-联合
            }else if("ZG".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZG"));//统一信用代码-资管
                sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfzZG"));//骑缝章
            }else if("CX".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeCX"));//统一信用代码-创新
            }else if("ZJ".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZJ"));//统一信用代码-紫金
            }else{
                code = Util.null2String(pb.getPropName("AutoSign.code"));//统一信用代码
            }

            String tableName = JAVATools.getMaintable(requestid);
            MessageDetailLog messageDetailLog = new MessageDetailLog(tableName);

            String mainid = "";
            String yz = "";
            String zzyongtu = "";
            String sql = "select id,yz,zzyongtu from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                yz = Util.null2String(rs.getString("yz"));
                zzyongtu = Util.null2String(rs.getString("zzyongtu"));
            }
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }else if(StringUtils.isEmpty(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }
            String content = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+" "+zzyongtu;

            List<DocSign> docSignList = new ArrayList<>();
            for(String fzid:fzids.split(",")){
                DocSign docSign = new DocSign();
                sql = "select id,wjmc,dsmdy,dzyyfs,yqxdyr,fwdyfs from "+tableName+"_dt8 where mainid = '"+mainid+"' and fzid = '"+fzid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    String id = Util.null2String(rs.getString("id"));
                    String docid = Util.null2String(rs.getString("wjmc"));

                    int newDocid = getWarterMarkDocid(user,docid,content);
                    bs.writeLog("wartermark newdocid:"+newDocid);
                    if(newDocid==-1){
                        resobject.put("status","500");
                        resobject.put("error","添加证照用途水印失败");
                        return resobject.toJSONString();
                    }
                    String pdfid = getPdfid(String.valueOf(newDocid));
                    if(StringUtils.isEmpty(pdfid)){
                        resobject.put("status","500");
                        resobject.put("error","查询文件结果为null,请检查参数");
                        return resobject.toJSONString();
                    }

                    //文件类型
                    String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));
                    docSign.setDocType(doctype);
                    //签署类型
                    docSign.setSignMethod("ORDER");
                    //签署开始时间-签署结束时间
                    docSign.setValidityStartDate(sdf.format(new Date()));
                    docSign.setValidityEndDate(getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));

                    //签署方信息
                    List<Signer> signerList = new ArrayList<>();
                    String yzcode = getSignCode(yz,yzType);
                    if ("".equals(yzcode)) {
                        resobject.put("status","500");
                        resobject.put("error","未找到对应的印章ID");
                        return resobject.toJSONString();
                    }
                    if("ZB".equals(yzType)||"ZG".equals(yzType)){
                        yzcode+=","+sealIdqfz;
                    }
                    Signer signer = new Signer();
                    signer.setCode(code);
                    signer.setCodeType("USC");
                    signer.setRevokeFlag("false");
                    signer.setSealId(yzcode);
                    signer.setSignNum("1");
                    signer.setOwnerType("INSIDE");
                    signer.setSignatoryType("ENTERPRISE");
                    signer.setKeyWord("华泰证券股份有限公司签章");
                    signer.setSignMethod("TRUSTEESHIP");
                    signer.setSignedExamine("DISABLE");
                    signerList.add(signer);
                    docSign.setSigners(signerList);

                    //文件路径-文件名称
                    Map<String, String> pdfMap = getLatestVersionPDF(requestid, pdfid);
                    if (pdfMap.isEmpty()) {
                        resobject.put("status","500");
                        resobject.put("error","上传挂载正文PDF文件出错");
                        return resobject.toJSONString();
                    }
                    docSign.setFileAttachPatch(pdfMap.get("mountpath"));
                    docSign.setFileNameDisplay(pdfMap.get("imagefilename"));


                    //文件编码

                    String signDocid = id+"_"+docid+"_"+getDatetime();
                    docSign.setDocId(signDocid);
                    String update_sql = "update "+tableName+"_dt8 set yyid = '"+signDocid+"' where id = '"+id+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);

//                    //骑缝章是否跳页加盖
//                    String dsmdy = Util.null2String(rs.getString("dsmdy"));
//                    if("0".equals(dsmdy)){//单面打印
//                        docSign.setAcrossSealSkipPage("DISABLE");
//                    }else if("1".equals(dsmdy)){//双面打印
//                        docSign.setAcrossSealSkipPage("ENABLE");
//                    }

                    //交付类型
                    String dzyyfs = Util.null2String(rs.getString("dzyyfs"));
                    if("0".equals(dzyyfs)){ //电子件
                        docSign.setEffectType("SINGLEWATERMARK");
                    }else if("1".equals(dzyyfs)){//电子防伪件
                        docSign.setEffectType("PAPER");
                        //骑缝章是否跳页加盖
                        String dsmdy = Util.null2String(rs.getString("dsmdy"));
                        if("0".equals(dsmdy)){//单面打印
                            docSign.setAcrossSealSkipPage("DISABLE");
                        }else if("1".equals(dsmdy)){//双面打印
                            docSign.setAcrossSealSkipPage("ENABLE");
                        }
                        String yqxdyr = Util.null2String(rs.getString("yqxdyr"));
                        Map<String,String> map= getUserMap(yqxdyr,String.valueOf(user.getUID()));

                        if(map!=null&&map.size()>0){
                            //防伪打印信息
                            PrintSetting printSetting = new PrintSetting();
                            String fwdyfs = Util.null2String(rs.getString("fwdyfs"));
                            printSetting.setPersonName(map.get("username"));
                            printSetting.setPersonNum(map.get("usrlogins"));
                            printSetting.setPrintNum(fwdyfs);
                            docSign.setPrintSetting(printSetting);
                        }
                    }else{
                        resobject.put("status","500");
                        resobject.put("error","请选择电子用印方式");
                        return resobject.toJSONString();
                    }
                }
                docSignList.add(docSign);
            }
            manualSignEntity.setDocSigns(docSignList);
            bs.writeLog("manualSignEntity:"+JSON.toJSONString(manualSignEntity));
            messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(manualSignEntity),"1",messageDetailLog.Other);

            //触发手动签章
            String response = htUtil.ManualSignPost(JSONArray.toJSON(manualSignEntity).toString());
            bs.writeLog(response);
            if(StringUtils.isEmpty(response)){
                resobject.put("status","500");
                resobject.put("error","手动签章接口返回结果为空");
                return resobject.toJSONString();
            }
            JSONObject res = JSONObject.parseObject(response);
            String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
            String message = Util.null2String(res.get("message"));
            bs.writeLog("status:"+status);
            bs.writeLog("message:"+message);
            if(!"200".equals(status)){
                resobject.put("status","500");
                resobject.put("error","送e-seal用印失败");
                updateSignStatusForLicense(tableName+"_dt8",mainid,fzids,"4");
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                return resobject.toJSONString();
            }
            updateSignStatusForLicense(tableName+"_dt8",mainid,fzids,"2");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","处理异常");
            return resobject.toJSONString();
        }

        bs.writeLog("sendFromApplicationLicense end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    /**
     * 用印变更触发变更用印件
     * @param user
     * @param requestid
     * @param docids
     * @return
     */
    public String sendFromChangeFile(User user, String requestid, String docids){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        bs.writeLog("sendFromChangeFile start:"+requestid);

        try{
            ManualSignEntity manualSignEntity = initialization(user,requestid);
            String code = Util.null2String(pb.getPropName("AutoSign.code"));//统一信用代码
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));//统一信用代码

            String tableName = JAVATools.getMaintable(requestid);
            MessageDetailLog messageDetailLog = new MessageDetailLog(tableName);

            String mainid = "";
            String yz = "";
            String sql = "select id,yz from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                yz = Util.null2String(rs.getString("yz"));
            }
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }else if(StringUtils.isEmpty(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }

            List<DocSign> docSignList = new ArrayList<>();
            List<String> docidList = Arrays.asList(docids.split(","));
            for(String docid:docidList){
                DocSign docSign = new DocSign();
                String pdfid = getPdfid(docid);
                if(StringUtils.isEmpty(pdfid)){
                    resobject.put("status","500");
                    resobject.put("error","查询文件结果为null,请检查参数");
                    return resobject.toJSONString();
                }else {
                    String update_sql="update "+tableName+"_dt1 set zpdfhwj = '"+pdfid+"' where mainid = '"+mainid+"' and (wjmc ='"+docid+"' or ywj ='"+docid+"' or scwj = '"+docid+"')";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);
                }

                //文件类型
                String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));
                docSign.setDocType(doctype);
                //签署类型
                docSign.setSignMethod("ORDER");
                //签署开始时间-签署结束时间
                docSign.setValidityStartDate(sdf.format(new Date()));
                docSign.setValidityEndDate(getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));

                //签署方信息
                List<Signer> signerList = new ArrayList<>();
                String yzcode = getSignCode(yz,null);
                if ("".equals(yzcode)) {
                    resobject.put("status","500");
                    resobject.put("error","未找到对应的印章ID");
                    return resobject.toJSONString();
                }
                yzcode+=","+sealIdqfz;
                Signer signer = new Signer();
                signer.setCode(code);
                signer.setCodeType("USC");
                signer.setRevokeFlag("false");
                signer.setSealId(yzcode);
                signer.setSignNum("1");
                signer.setOwnerType("INSIDE");
                signer.setSignatoryType("ENTERPRISE");
                signer.setKeyWord("华泰证券股份有限公司签章");
                signer.setSignMethod("TRUSTEESHIP");
                signer.setSignedExamine("DISABLE");
                signerList.add(signer);
                docSign.setSigners(signerList);

                //文件路径-文件名称
                Map<String, String> pdfMap = getLatestVersionPDF(requestid, pdfid);
                if (pdfMap.isEmpty()) {
                    resobject.put("status","500");
                    resobject.put("error","上传挂载正文PDF文件出错");
                    return resobject.toJSONString();
                }
                docSign.setFileAttachPatch(pdfMap.get("mountpath"));
                docSign.setFileNameDisplay(pdfMap.get("imagefilename"));

                sql = "select id,dsmdy,dzyyfs,yqxdyr,fwdyfs from "+tableName+"_dt1 where mainid = '"+mainid+"' and (wjmc = '"+docid+"' or ywj ='"+docid+"' or scwj = '"+docid+"')";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    //文件编码
                    String id = Util.null2String(rs.getString("id"));
                    String signDocid = id+"_"+docid+"_"+getDatetime();
                    docSign.setDocId(signDocid);
                    String update_sql = "update "+tableName+"_dt1 set yyid = '"+signDocid+"' where id = '"+id+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);

//                    //骑缝章是否跳页加盖
//                    String dsmdy = Util.null2String(rs.getString("dsmdy"));
//                    if("0".equals(dsmdy)){//单面打印
//                        docSign.setAcrossSealSkipPage("DISABLE");
//                    }else if("1".equals(dsmdy)){//双面打印
//                        docSign.setAcrossSealSkipPage("ENABLE");
//                    }

                    //交付类型
                    String dzyyfs = Util.null2String(rs.getString("dzyyfs"));
                    if("0".equals(dzyyfs)){ //电子件
                        docSign.setEffectType("ELECTRONIC");
                    }else if("1".equals(dzyyfs)){//电子防伪件
                        docSign.setEffectType("PAPER");
                        //骑缝章是否跳页加盖
                        String dsmdy = Util.null2String(rs.getString("dsmdy"));
                        if("0".equals(dsmdy)){//单面打印
                            docSign.setAcrossSealSkipPage("DISABLE");
                        }else if("1".equals(dsmdy)){//双面打印
                            docSign.setAcrossSealSkipPage("ENABLE");
                        }
                        String yqxdyr = Util.null2String(rs.getString("yqxdyr"));
                        Map<String,String> map= getUserMap(yqxdyr,String.valueOf(user.getUID()));

                        if(map!=null&&map.size()>0){
                            //防伪打印信息
                            PrintSetting printSetting = new PrintSetting();
                            String fwdyfs = Util.null2String(rs.getString("fwdyfs"));
                            printSetting.setPersonName(map.get("username"));
                            printSetting.setPersonNum(map.get("usrlogins"));
                            printSetting.setPrintNum(fwdyfs);
                            docSign.setPrintSetting(printSetting);
                        }
                    }else{
                        resobject.put("status","500");
                        resobject.put("error","请选择电子用印方式");
                        return resobject.toJSONString();
                    }
                }
                docSignList.add(docSign);
            }
            manualSignEntity.setDocSigns(docSignList);
            bs.writeLog("manualSignEntity:"+JSON.toJSONString(manualSignEntity));
            messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(manualSignEntity),"1",messageDetailLog.Other);

            //触发手动签章
            String response = htUtil.ManualSignPost(JSONArray.toJSON(manualSignEntity).toString());
            bs.writeLog(response);
            if(StringUtils.isEmpty(response)){
                resobject.put("status","500");
                resobject.put("error","手动签章接口返回结果为空");
                return resobject.toJSONString();
            }
            JSONObject res = JSONObject.parseObject(response);
            String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
            String message = Util.null2String(res.get("message"));
            bs.writeLog("status:"+status);
            bs.writeLog("message:"+message);
            if(!"200".equals(status)){
                resobject.put("status","500");
                resobject.put("error","送e-seal用印失败");
                updateSignStatusForChange(tableName+"_dt1",mainid,docids,"4");
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                return resobject.toJSONString();
            }
            updateSignStatusForChange(tableName+"_dt1",mainid,docids,"2");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","处理异常");
            return resobject.toJSONString();
        }

        bs.writeLog("sendFromChangeFile end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    /**
     * 初始化信息
     * @param user
     * @param requestid
     * @return
     */
    public ManualSignEntity initialization(User user, String requestid){
        PropBean pb = new PropBean();
        RecordSet rs = new RecordSet();

        ManualSignEntity manualSignEntity = new ManualSignEntity();
        String appid = Util.null2String(pb.getPropName("AutoSign.appId"));//应用ID
        String secret = Util.null2String(pb.getPropName("AutoSign.secret"));//秘钥
        manualSignEntity.setAppId(appid);
        manualSignEntity.setSecret(secret);
        manualSignEntity.setSignUserId(user.getLoginid());
        manualSignEntity.setSignUserName(user.getLastname());
        manualSignEntity.setFlowOwner(getFlowOwner(requestid));

        String requestMark = requestid;
        String requestName=  new SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString();
        String sql="select requestName,requestMark from workflow_requestbase where requestid ="+requestid;
        rs.executeQuery(sql);
        if(rs.next()){
            requestMark = Util.null2String(rs.getString("requestMark"));
            requestName = Util.null2String(rs.getString("requestName"));
        }
        if(requestName.length()>100){
            requestName = requestName.substring(0,100);
        }
        manualSignEntity.setFlowNum(requestMark);
        manualSignEntity.setFlowName(requestName);

        return manualSignEntity;
    }

    /**
     * 获得印章签署方
     * @param requestid
     * @return
     */
    public FlowOwner getFlowOwner(String requestid){
        RecordSet rs = new RecordSet();
        DepartmentComInfo dc = new DepartmentComInfo();
        FlowOwner flowOwner = new FlowOwner();

        try{
            flowOwner.setFlowSendTime(sdf.format(new Date()));

            String tableName = JAVATools.getMaintable(requestid);
            String ngr = "";
            String sql = "select ngr from "+tableName+" where requestid = "+requestid;
            rs.executeQuery(sql);
            if(rs.next()){
                ngr= Util.null2String(rs.getString("ngr"));
            }

            User ngrUser = new User(Util.getIntValue(ngr));
            String orgId = Util.null2String(dc.getDepartmentCode(String.valueOf(ngrUser.getUserDepartment())));
            String orgName = Util.null2String(dc.getDepartmentName(String.valueOf(ngrUser.getUserDepartment())));
            String personNum = JAVATools.getHrmworkcode(ngrUser.getLoginid());
            String personName = ngrUser.getLastname();
            personName += "("+personNum+")";
            flowOwner.setOrgId(orgId);
            flowOwner.setOrgName(orgName);
            flowOwner.setPersonNum(personNum);
            flowOwner.setPersonName(personName);

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

        return flowOwner;
    }

    /**
     * 获取pdf文件id
     * @param docid
     * @return
     */
    private String getPdfid(String docid){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        ConvertToPdf convertToPdf=new ConvertToPdf();
        ConvertDocToPdf convertDocToPdf = new ConvertDocToPdf();

        int pdfid = 0;
        int imagefileid = 0;
        String imagefilename = "";
//        String sql = "select imagefileid,imagefilename from DocImageFile where docid = '"+docid+"'";
        String sql = "select imagefileid,imagefilename from (select * from DocImageFile t where docid = '"+docid+"' order by operatedate desc,operatetime desc ) where ROWNUM <= 1";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            imagefileid= Integer.parseInt(rs.getString("imagefileid"));
            imagefilename=  Util.null2String(rs.getString("imagefilename")).toLowerCase();
        }
        bs.writeLog("docid:"+docid);
        bs.writeLog("imagefileid:"+imagefileid);
        bs.writeLog("imagefilename:"+imagefilename);
        if(0!=imagefileid&&StringUtils.isNotEmpty(imagefilename)){
            String fileTyle=imagefilename.substring(imagefilename.lastIndexOf(".")+1,imagefilename.length());
            bs.writeLog("fileTyle:"+fileTyle);
            if("pdf".equals(fileTyle)){
                pdfid = imagefileid;
            }else {
                pdfid =convertToPdf.getDownloadPDFUrl(imagefileid,imagefilename,false);
//                pdfid = convertDocToPdf.ConvertToPDF(imagefileid,imagefilename,true);
                if(pdfid<=0){
                    pdfid =convertToPdf.getDownloadPDFUrl(imagefileid,imagefilename,false);
//                    pdfid = convertDocToPdf.ConvertToPDF(imagefileid,imagefilename,true);
                }
            }
            bs.writeLog("pdfid:"+pdfid);
            return String.valueOf(pdfid);
        }else {
            return null;
        }
    }

    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param pdfid 文档ID
     * @return 结果集合
     */
    public Map<String,String> getLatestVersionPDF(String requestid,String pdfid){
        Map<String,String> map = new HashMap<>();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        PropBean pb = new PropBean();
        try{
            String sql = "select imagefileid,imagefilename from imagefile where imagefileid = '"+pdfid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                String imagefileid = Util.null2String(rs.getString("imagefileid"));
                String imagefilenamehz = Util.null2String(rs.getString("imagefilename"));
                String postfix="";
                String postfilename="";
                if(imagefilenamehz.split("\\.").length>=2){
                    if(imagefilenamehz.indexOf(".")>0){
                        postfilename=imagefilenamehz.substring(0,imagefilenamehz.lastIndexOf("."));
                    }

                }
                postfix=".pdf";
                String imagefilename = imagefileid+postfix;
                String imagefilepostname="";
                if(!"".equals(postfilename)){
                    imagefilepostname=postfilename+postfix;
                }else{
                    imagefilepostname=imagefileid+postfix;
                }

                bs.writeLog("imagefilename:"+imagefilename);
                bs.writeLog("imagefilepostname:"+imagefilepostname);

                InputStream inputstream = ImageFileManager.getInputStreamById(Util.getIntValue(imagefileid));
                int index;
                byte[] bytes = new byte[1024];
                // 文件夹名称
                String folderName = requestid+"_"+imagefileid+"_"+System.currentTimeMillis();
                String mountdir = Util.null2String(pb.getPropName("AutoSign.mountdir"));
                if("".equals(mountdir)){
                    bs.writeLog("获取的用印上传共享目录为空！");
                    return map;
                }

                String path = mountdir+"/" + folderName;
                // linux下先创建文件夹
                File dir = new File(path);
                //设置写权限，windows下不用此语句
                dir.setWritable(true, false);
                dir.mkdirs();
                //赋权限，正常是当前用户的权限，但是这里和之前的老OA不是同一个用户
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                path += "/"+imagefilename;//创建文件
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream uploadFile = new FileOutputStream(file);
                while ((index = inputstream.read(bytes)) != -1) {
                    uploadFile.write(bytes, 0, index);
                    uploadFile.flush();
                }
                inputstream.close();
                uploadFile.close();
                Runtime.getRuntime().exec("chmod -R 777 " + path);
                String Signmountpath = Util.null2String(pb.getPropName("Signmountpath"));
                String mountpath=Signmountpath+folderName+"/"+imagefilename;
                map.put("mountpath",mountpath);
                map.put("imagefilename",imagefilepostname);
                bs.writeLog("realpath:"+path);
                bs.writeLog("mountpath:"+mountpath);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 更新用印状态
     * @param tableName
     * @param mainid
     * @param docids
     * @param yyzt
     */
    private void updateSignStatus(String tableName, String mainid, String docids, String yyzt){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        List<String> docidList = Arrays.asList(docids.split(","));
        for(String docid:docidList){
            String update_sql = "update "+tableName+" set yyzt = '"+yyzt+"' where mainid = '"+mainid+"' and wjmc = '"+docid+"'";
            bs.writeLog(update_sql);
            rs.executeUpdate(update_sql);
        }
    }

    /**
     * 证照更新用印状态
     * @param tableName
     * @param mainid
     * @param fzids
     * @param yyzt
     */
    private void updateSignStatusForLicense(String tableName, String mainid, String fzids, String yyzt){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        List<String> fzidList = Arrays.asList(fzids.split(","));
        for(String fzid:fzidList){
            String update_sql = "update "+tableName+" set yyzt = '"+yyzt+"' where mainid = '"+mainid+"' and fzid = '"+fzid+"'";
            bs.writeLog(update_sql);
            rs.executeUpdate(update_sql);
        }
    }

    /**
     * 用印变更更新状态
     * @param tableName
     * @param mainid
     * @param docids
     * @param yyzt
     */
    private void updateSignStatusForChange(String tableName, String mainid, String docids, String yyzt){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        List<String> docidList = Arrays.asList(docids.split(","));
        for(String docid:docidList){
            String update_sql = "update "+tableName+" set yyzt = '"+yyzt+"' where mainid = '"+mainid+"' and (wjmc = '"+docid+"' or ywj ='"+docid+"' or scwj = '"+docid+"')";
            bs.writeLog(update_sql);
            rs.executeUpdate(update_sql);
        }
    }

    /**
     * 印章ID转印章编号
     * @param signid 印章ID
     * @return 印章编号
     */
    private String getSignCode(String signid, String yzType){
        RecordSet rs = new RecordSet();
        String yzbhvalue="";
        if("LH".equals(yzType)){
            rs.execute("select yzbh from uf_lhyz where id in ("+signid+") and sfdzyz = '0'");
        }else if("ZG".equals(yzType)){
            rs.execute("select yzbh from uf_yinzhang where id in ("+signid+") and (glyz is null or glyz <> 0)");
        }else if("CX".equals(yzType)){
            rs.execute("select yzbh from uf_yinzhang where id in ("+signid+") and (glyz is null or glyz <> 1)");
        }else if("ZJ".equals(yzType)){
            rs.execute("select yzbh from uf_zjyyyz where id in ("+signid+")");
        }else {
            rs.execute("select yzbh from uf_yinzhang where id in ("+signid+")");
        }
        if (rs.getArray().size()<=0) {
            return "";
        }
        while(rs.next()){
            if(!"".equals(Util.null2String(rs.getString("yzbh")))){
                yzbhvalue+=Util.null2String(rs.getString("yzbh"))+",";
            }
        }
        if(yzbhvalue.length()>0){
            yzbhvalue=yzbhvalue.substring(0,yzbhvalue.length()-1);
        }
        return yzbhvalue;
    }

    /**
     * 取具体日期的后多少年日期
     * @param dateStr 参照日期
     * @param pattern 日期格式
     * @param num 几年
     * @return 几年后的日期
     */
    private  String getNextYear(String dateStr,String pattern,int num) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        try {
            Date date = sdf.parse(dateStr);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.YEAR, num);
            return sdf.format(cal.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    public String getDatetime(){
        Random random=new Random();
        int inum=  random.nextInt(900)+100;
        return new  SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString()+inum;
    }

    public Map<String,String> getUserMap(String userids, String currentUserid){
        Map<String,String> map=new HashMap<>();
        if(StringUtils.isEmpty(userids)){
            return map;
        }
        String username="";
        String usrlogins="";

        String[] userarray=userids.split(",");
        for (String userid:userarray) {
            try {
                User user = new User(Integer.parseInt(userid));
                if(user!=null){
                    usrlogins+=usrlogins== "" ? JAVATools.getHrmworkcode(user.getLoginid()):","+JAVATools.getHrmworkcode(user.getLoginid());
                    username+=username=="" ? user.getUsername():","+user.getUsername();
                }
            }catch (Exception exo){
                System.out.println("user数据有误："+userids);
            }
        }
        if(StringUtils.isNotEmpty(currentUserid)){
            try {
                User user = new User(Integer.parseInt(currentUserid));
                if(user!=null){
                    usrlogins+=usrlogins== "" ? JAVATools.getHrmworkcode(user.getLoginid()):","+JAVATools.getHrmworkcode(user.getLoginid());
                    username+=username=="" ? user.getUsername():","+user.getUsername();
                }
            }catch (Exception exo){
                System.out.println("user数据有误："+userids);
            }
        }
        map.put("username",username);
        map.put("usrlogins",usrlogins);
        return map;
    }

    /**
     * 获取水印后文件docid
     * @param user
     * @param fileId
     * @param content
     * @return
     */
    private int getWarterMarkDocid(User user,String fileId, String content){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();

        int docid = -1;
        String secId = Util.null2String(pb.getPropName("seal.license.watermark.secId"));
        bs.writeLog("fileId:"+fileId+" secId:"+secId+" content:"+content);

        RecordSet rs = new RecordSet();
        String sql = "select imageFileId from docImageFile where docId = ? order by versionId desc";
        rs.executeQuery(sql, new Object[]{fileId});
        int flag = -1;
        if(rs.next()) {
            flag = rs.getInt(1);
        }
        bs.writeLog("flag:"+flag);

        try{
            ImageFileManager imageFileManager = new ImageFileManager();
            imageFileManager.resetParameter();
            if(flag != -1) {
                imageFileManager.getImageFileInfoById(flag);
                String imageFileName = imageFileManager.getImageFileName();
                String fileType = imageFileName.contains(".")?imageFileName.substring(imageFileName.lastIndexOf(".")):".pdf";
                OfficedWatermark officedWatermark = new OfficedWatermark();
                String fillstyle = bs.getPropValue("water_setting", "fillstyle");
                String font = bs.getPropValue("water_setting", "font");
                String width = bs.getPropValue("water_setting", "width");
                String height = bs.getPropValue("water_setting", "height");
                String rotate = bs.getPropValue("water_setting", "rotate");
                String opacity = bs.getPropValue("water_setting", "opacity");
                HashMap paramMap = new HashMap();
                if(!fillstyle.isEmpty()) {
                    paramMap.put("fillstyle", fillstyle);
                }
                if(!font.isEmpty()) {
                    paramMap.put("font", font);
                }
                if(!width.isEmpty()) {
                    paramMap.put("width", Integer.valueOf(Util.getIntValue(width)));
                }
                if(!height.isEmpty()) {
                    paramMap.put("height", Integer.valueOf(Util.getIntValue(height)));
                }
                if(!rotate.isEmpty()) {
                    paramMap.put("rotate", Double.valueOf(Util.getDoubleValue(rotate)));
                }
                if(!opacity.isEmpty()) {
                    paramMap.put("opacity", Float.valueOf(Util.getFloatValue(opacity)));
                }

                String waterType = OfficedWatermark.WATER_TYPE_PDF;
                if(fileType.toLowerCase().equals(".pdf")) {
                    waterType = OfficedWatermark.WATER_TYPE_PDF;
                } else if(!fileType.toLowerCase().equals(".doc") && !fileType.toLowerCase().equals(".docx")) {
                    waterType = OfficedWatermark.WATER_TYPE_IMG;
                } else {
                    waterType = OfficedWatermark.WATER_TYPE_WORD;
                }

                InputStream inputStream = officedWatermark.addWaterInputStream(flag, fileType, waterType, content, paramMap);
                if(inputStream == null) {
                    bs.writeLog("加水印失败！");
                }else{
                    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.getBOS(inputStream).toByteArray());
                    if(!secId.isEmpty()) {
                        CreateDocUtil createDocUtil = new CreateDocUtil();
                        int secid = Util.getIntValue(secId);
                        docid = createDocUtil.createDocByInputStream(byteArrayInputStream, secid, imageFileName, user);
                        byteArrayInputStream.reset();
                    }
                    byteArrayInputStream.close();
                }
                inputStream.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return docid;
    }

    private ByteArrayOutputStream getBOS(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            int index;
            while((index = bufferedInputStream.read()) != -1) {
                outputStream.write(index);
            }
            bufferedInputStream.close();
        } catch (Exception e) {

        }

        return outputStream;
    }

    /**
     * 用印类型分类
     * @param user
     * @param requestid
     * @param docids
     * @param yzType
     * @return
     */
    public String sortESealType(User user, String requestid, String docids, String yzType){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        bs.writeLog("sortESealType start:"+requestid);
        JSONObject resobject=new JSONObject();

        try{
            String tableName = JAVATools.getMaintable(requestid);
            String mainid = "";
            String sql = "select id from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
            }
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }

            List<String> oldTypeDocidList = new ArrayList<>();
            List<String> newTypeDocidList = new ArrayList<>();
            for(String docid:Arrays.asList(docids.split(","))){
                //电子用印方式
                String dzyyfs = "";
                sql = "select dzyyfs from "+tableName+"_dt7 where mainid = '"+mainid+"' and wjmc = '"+docid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    dzyyfs = Util.null2String(rs.getString("dzyyfs"));
                }
                if("0".equals(dzyyfs)||"1".equals(dzyyfs)){//电子件/防伪打印件
                    oldTypeDocidList.add(docid);
                }else if("2".equals(dzyyfs)){//对手方电子件
                    newTypeDocidList.add(docid);
                }
            }

            if(oldTypeDocidList.size()>0){
                String oldTypeDocids = String.join(",",oldTypeDocidList);
                bs.writeLog("sortESealType oldTypeDocids:"+oldTypeDocids);
                String result = sendFromApplicationFile(user,requestid,oldTypeDocids,yzType);
                JSONObject res = JSONObject.parseObject(result);
                String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
                if(!"200".equals(status)){
                    return result;
                }
            }

            if(newTypeDocidList.size()>0){
                String newTypeDocids = String.join(",",newTypeDocidList);
                bs.writeLog("sortESealType newTypeDocids:"+newTypeDocids);
                String result = sendFromApplicationFileNew(user,requestid,newTypeDocids,yzType);
                JSONObject res = JSONObject.parseObject(result);
                String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
                if(!"200".equals(status)){
                    return result;
                }
            }

        }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","送e-seal用印失败");
            return resobject.toJSONString();
        }

        bs.writeLog("sortESealType end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    /**
     * 新用印申请触发电子签章-文件
     * @param user
     * @param requestid
     * @param docids
     * @return
     */
    public String sendFromApplicationFileNew(User user, String requestid, String docids, String yzType){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        bs.writeLog("sendFromApplicationFileNew start:"+requestid);

        try{
            ManualSignEntity manualSignEntity = initialization(user,requestid);
            String appid = Util.null2String(pb.getPropName("AutoSign.appId.New"));//应用ID
            String secret = Util.null2String(pb.getPropName("AutoSign.secret.New"));//秘钥
            manualSignEntity.setAppId(appid);
            manualSignEntity.setSecret(secret);
            manualSignEntity.setAutoSignState("DISABLE");
            String code = "";
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));//骑缝章
            if("LH".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeLH"));//统一信用代码-联合
            }else if("ZG".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZG"));//统一信用代码-资管
                sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfzZG"));//骑缝章
            }else if("CX".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeCX"));//统一信用代码-创新
            }else if("ZJ".equals(yzType)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZJ"));//统一信用代码-紫金
            }else{
                code = Util.null2String(pb.getPropName("AutoSign.code"));//统一信用代码
            }

            String tableName = JAVATools.getMaintable(requestid);
            MessageDetailLog messageDetailLog = new MessageDetailLog(tableName);

            String mainid = "";
            String yz = "";
            String sql = "select id,yz from "+tableName+" where requestid = "+requestid;
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                mainid = Util.null2String(rs.getString("id"));
                yz = Util.null2String(rs.getString("yz"));
            }
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }else if(StringUtils.isEmpty(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }

            //签署方信息
            String yzcode = getSignCode(yz,yzType);
            if ("".equals(yzcode)) {
                resobject.put("status","500");
                resobject.put("error","未找到对应的印章ID");
                return resobject.toJSONString();
            }
            if("ZB".equals(yzType)||"ZG".equals(yzType)){
                yzcode+=","+sealIdqfz;
            }
            Signer signer = new Signer();
            signer.setCode(code);
            signer.setCodeType("USC");
            signer.setRevokeFlag("false");
            signer.setSealId(yzcode);
            signer.setSignNum("1");
            signer.setOwnerType("INSIDE");
            signer.setSignatoryType("ENTERPRISE");
            signer.setKeyWord("华泰证券股份有限公司签章");
            signer.setSignMethod("TRUSTEESHIP");
            signer.setSignedExamine("DISABLE");
            signer.setEmail(user.getEmail());
            Map<String,String> seals = new HashMap<>();
            seals.put("sealId",yzcode);
            signer.setSeals(seals);

            //用印文件列表
            List<DocSign> docSignList = new ArrayList<>();
            for(String docid:Arrays.asList(docids.split(","))){
                DocSign docSign = new DocSign();
                String pdfid = getPdfid(docid);
                if(StringUtils.isEmpty(pdfid)){
                    resobject.put("status","500");
                    resobject.put("error","查询文件结果为null,请检查参数");
                    return resobject.toJSONString();
                }else {
                    String update_sql="update "+tableName+"_dt7 set zpdfhwj = '"+pdfid+"' where mainid = '"+mainid+"' and wjmc ='"+docid+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);
                }

                //文件类型
                String doctype = Util.null2String(pb.getPropName("ManualSign.doctype.New"));
                docSign.setDocType(doctype);
                //签署类型
                docSign.setSignMethod("ORDER");
                //交付类型
                docSign.setEffectType("NOWATERMARK");

                //签署方信息
                List<Signer> signerList = new ArrayList<>();
                signerList.add(signer);
                docSign.setSigners(signerList);

                //文件路径-文件名称
                String imagefilename = "";
                String filerealpath = "";
                String iszip = "";
                sql = "select imagefilename,filerealpath,iszip from imagefile where imagefileid = '"+pdfid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    imagefilename = Util.null2String(rs.getString("imagefilename"));
                    filerealpath = Util.null2String(rs.getString("filerealpath"));
                    iszip = Util.null2String(rs.getString("iszip"));
                }else{
                    resobject.put("status","500");
                    resobject.put("error","查询转pdf文件报错");
                    return resobject.toJSONString();
                }
                bs.writeLog("imagefilename:"+imagefilename);
                bs.writeLog("filerealpath:"+filerealpath);
                bs.writeLog("iszip:"+iszip);
                if(StringUtils.isNotBlank(filerealpath)){
                    File file = new File(filerealpath);
                    String result = uploadFileEseal(file,imagefilename,iszip);
                    if(StringUtils.isEmpty(result)){
                        resobject.put("status","500");
                        resobject.put("error","上传文件到存储网关接口返回为空");
                        return resobject.toJSONString();
                    }
                    JSONObject resultObj = JSONObject.parseObject(result);
                    String status = Util.null2String(resultObj.get("status"));//标识200-成功,否则失败
                    String message = Util.null2String(resultObj.get("message"));
                    String fileid = Util.null2String(resultObj.get("fileid"));
                    bs.writeLog("status:"+status);
                    bs.writeLog("message:"+message);
                    bs.writeLog("fileid:"+fileid);
                    if(!"1".equals(status)){
                        resobject.put("status","500");
                        resobject.put("error","上传文件到存储网关失败");
                        return resobject.toJSONString();
                    }
                    docSign.setUniqueKey(fileid);
                }
                docSign.setFileNameDisplay(imagefilename);


                sql = "select id from "+tableName+"_dt7 where mainid = '"+mainid+"' and wjmc = '"+docid+"'";
                bs.writeLog(sql);
                rs.executeQuery(sql);
                if(rs.next()){
                    //文件编码
                    String id = Util.null2String(rs.getString("id"));
                    String signDocid = id+"_"+docid+"_"+getDatetime();
                    docSign.setDocId(signDocid);
                    String update_sql = "update "+tableName+"_dt7 set yyid = '"+signDocid+"' where id = '"+id+"'";
                    bs.writeLog(update_sql);
                    rs.executeUpdate(update_sql);
                }
                docSignList.add(docSign);
            }
            manualSignEntity.setDocSigns(docSignList);
            Map<String,Object> requestMap = new HashMap<>();
            requestMap.put("sealFlow",manualSignEntity);
            bs.writeLog("requestMap:"+JSON.toJSONString(requestMap));
            messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(requestMap),"1",messageDetailLog.Other);

            //触发手动签章
            String response = htUtil.ManualSignPostNew(JSON.toJSON(requestMap).toString());
            bs.writeLog(response);
            if(StringUtils.isEmpty(response)){
                resobject.put("status","500");
                resobject.put("error","手动签章接口返回结果为空");
                return resobject.toJSONString();
            }
            JSONObject res = JSONObject.parseObject(response);
            String status = Util.null2String(res.get("code"));//标识200-成功,否则失败
            String message = Util.null2String(res.get("msg"));
            String esealRequestid = Util.null2String(res.get("requestId"));
            bs.writeLog("status:"+status);
            bs.writeLog("message:"+message);
            bs.writeLog("esealRequestid:"+esealRequestid);
            if(!"0".equals(status)){
                resobject.put("status","500");
                resobject.put("error","送e-seal用印失败");
                updateSignStatus(tableName+"_dt7",mainid,docids,"4");
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                return resobject.toJSONString();
            }
            updateSignStatus(tableName+"_dt7",mainid,docids,"2");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","送e-seal用印失败");
            return resobject.toJSONString();
        }

        bs.writeLog("sendFromApplicationFileNew end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    /**
     * 上传文件(对手方电子用印)
     *
     * @param file
     * @return 响应结果
     */
    public String uploadFileEseal(File file, String imagefilename, String iszip) {
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        HTUtil htUtil = new HTUtil();
        String result = "";

        bs.writeLog("uploadFileEseal----->Start");
        bs.writeLog("file:" + file.getName());
        try {
            InputStream inputstream = null;
            if (iszip.equals("1"))
            {
                ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(file));
                if (zipInputStream.getNextEntry() != null) {
                    inputstream = new BufferedInputStream(zipInputStream);
                }
            } else {
                inputstream = new BufferedInputStream(new FileInputStream(file));
            }
            String url = Util.null2String(pb.getPropName("jtxt.base.url")) + "/weaver/seal/uploadFileEseal";
            bs.writeLog("url:" + url);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.addBinaryBody("file",htUtil.InputStream2Byte(inputstream),ContentType.MULTIPART_FORM_DATA, imagefilename);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (Exception e) {
            bs.writeLog("uploadFileEseal捕获异常：", e);
        }
        bs.writeLog("uploadFileEseal response：" + result);
        bs.writeLog("uploadFileEseal----->End");
        return result;
    }
}
