package com.engine.htsc.seal.lhht.Service.Impl;

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 com.engine.htsc.seal.lhht.Service.SeallhhtService;
import org.apache.commons.lang.StringUtils;
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.wps.officed.ConvertToPdf;
import weaver.wps.officed.OfficedWatermark;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author xf
 * @version 1.0.0
 * @ClassName SeallhhtService.java
 * @createTime 2021年12月13日 10:50:00
 */
public class SeallhhtServiceimpl extends Service implements SeallhhtService {
   private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



   @Override
   public String sendLhhtSeal(User user,Map<String,Object> paramsmap){

      if("0".equals(Util.null2String(paramsmap.get("sealtype")))){
         //走
         return sendsealzd(user,paramsmap);
      }else{
         //
         return  sendsealFile(user,paramsmap);
      }


   }


   /**
    * 联合用印申请触发电子签章-证照
    * @param user

    * @return
    */
   public String sendsealzd(User user,Map<String,Object> paramsmap){
      String requestid =Util.null2String(paramsmap.get("requestid"));
      String fzids =Util.null2String(paramsmap.get("docids"));
      //String yzType=Util.null2String(paramsmap.get("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 = "";
         //  if("LH".equals(yzType)){
         code = Util.null2String(pb.getPropName("AutoSign.codeLH"));//统一信用代码-联合
//         }else{
//            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 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);
               if ("".equals(yzcode)) {
                  resobject.put("status","500");
                  resobject.put("error","未找到对应的印章ID");
                  return resobject.toJSONString();
               }
//               if("ZB".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 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

    * @return
    */
   public String sendsealFile(User user,Map<String,Object> paramsmap){
      PropBean pb = new PropBean();
      BaseBean bs = new BaseBean();
      RecordSet rs = new RecordSet();
      String requestid=Util.null2String(paramsmap.get("requestid"));
      String docids=Util.null2String(paramsmap.get("docids"));
      HTUtil htUtil = new HTUtil();
      JSONObject resobject=new JSONObject();
      bs.writeLog("sendFromApplicationFile start:"+requestid);

      try{
         ManualSignEntity manualSignEntity = initialization(user,requestid);
         String code = "";
         //  if("LH".equals(yzType)){
         code = Util.null2String(pb.getPropName("AutoSign.codeLH"));//统一信用代码-联合
//         }else{
//            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+"_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);
            if ("".equals(yzcode)) {
               resobject.put("status","500");
               resobject.put("error","未找到对应的印章ID");
               return resobject.toJSONString();
            }

            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 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用印失败");
            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();
   }

   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);
      }
   }

   //
   /**
    * 印章ID转印章编号
    * @param signid 印章ID
    * @return 印章编号
    */
   private String getSignCode(String signid){
      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 {
//         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;
   }


   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 "";
      }
   }

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

      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);
            if(pdfid<=0){
               pdfid =convertToPdf.getDownloadPDFUrl(imagefileid,imagefilename,false);
            }
         }
         bs.writeLog("pdfid:"+pdfid);
         return String.valueOf(pdfid);
      }else {
         return null;
      }
   }


   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 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 user
    * @param requestid
    * @return
    */
   private 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;
   }

   /**
    * 获取水印后文件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, imageFileName, 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;
   }


   /**
    * 获得印章签署方
    * @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;
   }

   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;
   }

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

   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;
   }

}


