package com.engine.htsc.seal.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.seal.entity.DocSign;
import com.engine.htsc.seal.entity.ManualSignEntity;
import com.engine.htsc.seal.entity.Signer;
import com.engine.htsc.seal.service.SendManualSignService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.HrmUserVarify;
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.wpscenter.impl.ConvertDocToPdf;
import weaver.wps.officed.ConvertToPdf;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 手动签章流程接口
 */
public class SendManualSignAction  {

    private Log log = LogFactory.getLog(this.getClass());

    private   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @POST
    @Path("/sendManualSign")
    @Produces({MediaType.TEXT_PLAIN})
    public String receiveSeal(@Context HttpServletRequest request, @Context HttpServletResponse response){
        RecordSet rs = new RecordSet();

        JSONObject resobject=new JSONObject();
        PropBean pb = new PropBean();
     //   public String execute(RequestInfo requestInfo) {
        HTUtil htUtil = new HTUtil();
        String requestid = Util.null2String(request.getParameter("requestid"));
        String tabledetail ="";
        String docids = Util.null2String(request.getParameter("docid"));


     /*   String requestid = Util.null2String(requestInfo.getRequestid());//流程请求ID*/    //流程标题
       // String requestName = Util.null2String(requestInfo.getRequestManager().getRequestname());
    //    String requestName="测试名称";
        String requestName=  new  SimpleDateFormat("yyyyMMddmmssdd").format(new Date()).toString();

        String sqlrequestname="select requestName from  workflow_requestbase where requestid ="+requestid;
            rs.execute(sqlrequestname);
            if(rs.next()){
                requestName= Util.null2String(rs.getString("requestName"));
            }
        requestName=JAVATools.lengthsub(requestName,0,100);
        String tableName = JAVATools.getMaintable(requestid);

        if(docids!=""){
            tabledetail =GetDetaiMainid(requestid,docids,tableName+"_dt1");

        }
      //  String tableName = Util.null2String(requestInfo.getRequestManager().getBillTableName());

        //当前操作人（印章管理员）
        MessageDetailLog messageDetailLog=new MessageDetailLog(tableName);

        User usersinet = HrmUserVarify.getUser(request, response);

        log.info("手动签章流程接口-----START----" + requestid+"当前操作人是:"+usersinet.getLastname());
        try {

            //应用ID
            String appid = Util.null2String(pb.getPropName("AutoSign.appId"));
            //秘钥
            String secret = Util.null2String(pb.getPropName("AutoSign.secret"));
            //统一信用代码
            String code = Util.null2String(pb.getPropName("AutoSign.code"));
            //统一信用代码
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));



            String sql = "  select  * from "+tableName+"  where requestid = "+requestid;

            rs.execute(sql);
            if(rs.getArray().size()<=0){
                resobject.put("status","500");
                resobject.put("error","查询结果为null,请检查参数");
                return resobject.toJSONString();
            }
            rs.next();
            //String yywj = Util.null2String(rs.getString("yywj"));
          String datetimes= new  SimpleDateFormat("_yyyyMMddmmssdd").format(new Date()).toString();
           // String flowNum = Util.null2String(rs.getString("id")+datetimes);
            String flowNum = Util.null2String(rs.getString("id"));
            String yz = Util.null2String(rs.getString("yz"));
            String ngr = Util.null2String(rs.getString("ngr"));
            String lcbh = Util.null2String(rs.getString("lcbh"));
            String szjg = Util.null2String(rs.getString("szjg"));
            String zgjgdeptid=Util.null2String(pb.getPropName("zgjgdeptid"));
            if(zgjgdeptid.equals(szjg)){
                code = Util.null2String(pb.getPropName("AutoSign.codeZG"));
                sealIdqfz= Util.null2String(pb.getPropName("ManualSign.sealIdqfzZG"));
            }
            // requestName = Util.null2String(rs.getString("lcbt"));
            if(!"".equals(flowNum)){  //id不能为空
                if("".equals(yz)){
                    resobject.put("status","500");
                    resobject.put("error","请选择印章后提交");
                    return resobject.toJSONString();
                }else{
                    JSONObject obj = new JSONObject();
                    obj.put("appId",appid);
                    obj.put("secret",secret);
                    obj.put("flowName",requestName);
                    obj.put("flowNum",lcbh);//这里流程编号修改成requestid
                 //   obj.put("needWatermark","ENABLE");//水印
                    JSONObject flowOwnerObj = new JSONObject();
                     flowOwnerObj.put("flowSendTime",sdf.format(new Date()));
                    DepartmentComInfo dc = new DepartmentComInfo();
                    User ngrUser=new User();
                    if(!"".equals(ngr)){
                         ngrUser=new User(Util.getIntValue(ngr));
                    }
                    if(ngrUser==null||ngrUser.getUID()==0){
                        ngrUser=usersinet;
                    }
                    //部门编码
                    String orgId = Util.null2String(dc.getDepartmentCode(ngrUser.getUserDepartment()+""));
                    flowOwnerObj.put("orgId",orgId);
                    //部门编码
                    String orgName = Util.null2String(dc.getDepartmentName(ngrUser.getUserDepartment()+""));
                    flowOwnerObj.put("orgName",orgName);
                    //姓名
                    String personName = ngrUser.getLastname();
                    //工号
                    String personNum = JAVATools.getHrmworkcode(ngrUser.getLoginid());
                    personName+="("+personNum+")";
                    flowOwnerObj.put("personName",personName);
                    flowOwnerObj.put("personNum",personNum);
                    obj.put("flowOwner",flowOwnerObj);
        JAVATools.SetCmdwritelog("用印登记单","faqiren:"+flowOwnerObj.toJSONString());
                    JSONArray docSignsArr = new JSONArray();

            List<Map<String,String>> yywjmap= getdetail(flowNum,tableName,tabledetail);
            if(yywjmap==null||yywjmap.size()<=0){
                return null;
            }

//            //将对手方用印的文件分出去
//            Map<String,Object> resultMap = sortEsealType(yywjmap,requestid,usersinet);
//            String newSealResult = (String)resultMap.get("result");
//            String newSealMessage = (String)resultMap.get("message");
//            if("error".equals(newSealResult)){
//                return newSealMessage;
//            }else {
//                Boolean continueFlag = (Boolean)resultMap.get("continue");
//                if(continueFlag){
//                    yywjmap = (List<Map<String,String>>)resultMap.get("newMapList");
//                }else{
//                    return newSealMessage;
//                }
//            }

           List<Map<String,Object>> yyztlist=new ArrayList<>();
           for (Map<String,String> docmap :yywjmap) {
               String docaaray = docmap.get("wjmc").toString();
               String pdfdocid = docmap.get("docid").toString();
               String dsmdy = docmap.get("dsmdy").toString();
               String dzyyfs = docmap.get("dzyyfs").toString();
               String yqxdyr= docmap.get("yqxdyr").toString();
               String fwdyfs=docmap.get("fwdyfs").toString();
               String detailid=docmap.get("detailid").toString();
               String yyfs=docmap.get("yyfs").toString();

               for (String docid : docaaray.split(",")) {
                   if(docid==""){
                       break;
                   }
                   Map<String,String>mapdoc=new HashMap<>();
                   mapdoc.put("detailid",detailid);
                   mapdoc.put("pdfdocid",pdfdocid);
                 mapdoc.put("requestid",requestid);
                 mapdoc.put("docid",docid);
                 mapdoc.put("code",code);
                   mapdoc.put("yyfs",yyfs);
                yqxdyr=JAVATools.AddStrToUser(yqxdyr,usersinet);
                 mapdoc.put("yqxdyr",yqxdyr);
                 mapdoc.put("fwdyfs",fwdyfs);
                 mapdoc.put("sealIdqfz",sealIdqfz);
                 mapdoc.put("yz",yz);
                 mapdoc.put("dsmdy",dsmdy);
                JAVATools.SetCmdwritelog("用印登记单-用印方式：","用印方式："+yyfs);
                   if("3".equals(yyfs)){
                       for(int i=0;i<2;i++){
                           //判断有没有成功的，如果是重新发送那么成功的则不送用印
                           if(SignStatusutil.isSendManualauto(tableName,detailid,Util.null2String(i))){
                             //  mapdoc.put("docid",docid+"_"+i);
                               mapdoc.put("dzyyfs",Util.null2String(i));
                               JSONObject docObj = getdocs(mapdoc);
                               JAVATools.SetCmdwritelog("用印登记单","是否走到可以合并的步骤"+docObj.toJSONString());
                               if(docObj==null||(docObj.get("error")!=null&&docObj.get("error")!="")){
                                   JAVATools.SetCmdwritelog("用印登记单","是否走到可以合并的步骤"+docObj.toJSONString());
                                   callbackdetailzt(tableName+"_dt1",yyztlist);
                                   return docObj.toJSONString();
                               }
                               docSignsArr.add(docObj);
                                String docidvalue=docid;
                                JAVATools.SetCmdwritelog("查看docid",docObj.toJSONString());
                               JAVATools.SetCmdwritelog("查看docid",docObj.get("docId").toString());
                               if(docObj.get("docId")!=null&&!"".equals(docObj.get("docId").toString())){
                                   docidvalue=docObj.get("docId").toString();
                               }
                               setdetaildoc(tableName+"_dt2",requestid,mapdoc,docidvalue);
                               updatedetailzt(tableName+"_dt1",detailid,Util.null2String(i));
                               Map<String,Object> historymap=new HashMap<>();
                               historymap.put("dzyyfs",Util.null2String(i));
                               historymap.put("detailid",detailid);
                               yyztlist.add(historymap);
                           }

                       }

                   }else{
                       mapdoc.put("dzyyfs",dzyyfs);
                       JSONObject docObj = getdocs(mapdoc);
                       JAVATools.SetCmdwritelog("用印登记单","是否走到可以合并的步骤"+docObj.toJSONString());
                       if(docObj==null||(docObj.get("error")!=null&&docObj.get("error")!="")){
                           return docObj.toJSONString();
                       }
                       String docidvalue=docObj.get("docId").toString();
                       setdetaildoc(tableName+"_dt2",requestid,mapdoc,docidvalue);
                       docSignsArr.add(docObj);
                   }

               }
           }

                    obj.put("docSigns",docSignsArr);
                    obj.put("signUserId",usersinet.getLoginid());
                    obj.put("signUserName",usersinet.getLastname());
                    messageDetailLog.writLogsnotretrun(requestid,obj.toString(),"1",messageDetailLog.Other);
                    JAVATools.SetCmdwritelog("objtostring"+obj.toString());
                    String sendresponse = htUtil.ManualSignPost(obj.toJSONString());//返回结果
                    if("".equals(sendresponse)){
                        failcalback(requestid,tabledetail,tableName);
                        resobject.put("status","500");
                        resobject.put("error","手动签章接口返回结果为空");
                        return resobject.toJSONString();
                    }
                    JSONObject res = JSONObject.parseObject(sendresponse);
                    String status = Util.null2String(res.get("status"));//标识  200：成功   否则失败
                    String message = Util.null2String(res.get("message"));
                    log.info("手动签章响应状态："+status);
                    log.info("手动签章响应信息："+message);
                    if(!"200".equals(status)){
                        failcalback(requestid,tabledetail,tableName);
                        resobject.put("status","500");
                        resobject.put("error","用印失败");
                        return resobject.toJSONString();
                    }
                    JSONObject data = JSONObject.parseObject(Util.null2String(res.get("data")));
                    JSONArray docIdsArr = JSONArray.parseArray(Util.null2String(data.get("docIds")));
                    RecordSet rs_up = new RecordSet();
                    String docidStr = "";
                    for(int i=0;i<docIdsArr.size();i++){
                        if("".equals(docidStr)){
                            docidStr = Util.null2String(docIdsArr.get(i));
                        }else{
                            docidStr += "," + Util.null2String(docIdsArr.get(i));
                        }
                    }
                    setDetail(requestid,tabledetail,tableName);
                    messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,sendresponse);
                }

            }
        } catch (Exception e) {
            failcalback(requestid,tabledetail,tableName);
            messageDetailLog.writLogsnotretrun(requestid,e.getMessage(),"1",messageDetailLog.error);
            e.printStackTrace();

            resobject.put("status","500");
            resobject.put("error","手动签章接口异常，请联系系统管理员！");
            return resobject.toJSONString();
        }
        log.info("手动签章流程接口-----END-----" + requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();


    }

    public void setdetaildoc(String tablename,String requestid, Map<String,String> map,String docid){
        Map<String,String> detailmap=new HashMap<>();
        String mainid= JAVATools.getMaintableid(requestid);
        //  deletesealdt2(tablename,mainid,map);
        detailmap.put("mainid",mainid);
        detailmap.put("dtoneid",map.get("detailid"));
        detailmap.put("wjmc",map.get("pdfdocid"));
        detailmap.put("dzyylx",map.get("dzyyfs"));
        detailmap.put("docid",docid);
        JAVATools.Excetesql(detailmap,tablename);
    }
    private  void deletesealdt2(String tablename,String mainid,Map<String,String> map){
      try {
          if ("".equals(tablename) || "".equals(mainid) || map == null || map.size() <= 0) {
              return;
          }
          String detailid = Util.null2String(map.get("detailid"));
          if ("".equals(detailid)) {
              return;
          }
          String sql = "delete from " + tablename + " where mainid=? and dtoneid=?";
          RecordSet rs = new RecordSet();
          JAVATools.SetCmdwritelog("delseal", "sql:" + sql + "Params:mainid" + detailid + "-dtoneid:" + detailid);
          rs.executeUpdate(sql, mainid, detailid);
      }catch (Exception e){
          JAVATools.SetCmdwritelog("delsealerror",e.getMessage());
      }
    }
/*
 dzjyyzt,fwjyyzt
* */
    public void updatedetailzt(String tablename,String detailid,String dzyyfs){
        RecordSet rs=new RecordSet();
        String sql="";
        if("0".equals(dzyyfs)){
            sql="update "+tablename+" set dzjyyzt=1 where id='"+detailid+"'";
        }else if("1".equals(dzyyfs)){
            sql="update "+tablename+" set fwjyyzt=1 where id='"+detailid+"'";
        }
        if(!"".equals(sql)){
         JAVATools.SetCmdwritelog("用印件修改状态:","sql:"+sql);
            rs.execute(sql);
        }
    }

    public void callbackdetailzt(String tablename,List<Map<String,Object>> detaillist){
        if(detaillist==null || detaillist.size()<=0){
            return ;
        }
        RecordSet rs=new RecordSet();
        detaillist.forEach((Map<String, Object> map)->{
            String dzyyfs=Util.null2String(map.get("dzyyfs"));
            String detailid=Util.null2String(map.get("detailid"));
            if(!StringUtils.isBlank(dzyyfs) && !StringUtils.isBlank(detailid)){
                String sql="";
                if("0".equals(dzyyfs)){
                    sql="update "+tablename+" set dzjyyzt='' where id in '"+detailid+"'";
                }else if("1".equals(dzyyfs)){
                    sql="update "+tablename+" set fwjyyzt='' where id in'"+detailid+"'";
                }
                if(!"".equals(sql)){
                    JAVATools.SetCmdwritelog("用印件修改状态:","sql:"+sql);
                    rs.execute(sql);
                }
            }

        });

    }


    public JSONObject getdocs(Map<String,String> mapdoc){
        JSONObject docObj = new JSONObject();//正文对象
        JSONObject resobject= new JSONObject();
       String detailid= mapdoc.get("detailid");
        String pdfdocid= mapdoc.get("pdfdocid");
        String requestid=mapdoc.get("requestid");;
        String docid=mapdoc.get("docid");;
        String code=mapdoc.get("code");;
        String yyfs=mapdoc.get("yyfs");
        String dzyyfs=mapdoc.get("dzyyfs");;
        String yqxdyr=mapdoc.get("yqxdyr");;
        String fwdyfs=mapdoc.get("fwdyfs");;
        String sealIdqfz=mapdoc.get("sealIdqfz");
        String dsmdy=mapdoc.get("dsmdy");
        String yz=mapdoc.get("yz");;
        PropBean pb = new PropBean();
       // if(doc_yyfs==null||"".equals(doc_yyfs)){
            docObj.put("docId", detailid+"_"+pdfdocid+getDatetime());  //将之前docid代替为imageid使用

        //文件类型
        String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));;


        docObj.put("docType", doctype);
        JAVATools.SetCmdwritelog("用印件开始转正文:","requestid:"+requestid+"docid:"+docid+"detailid:"+detailid);
        Map<String, String> pdfMap = getLatestVersionPDF(requestid, docid);
        if (pdfMap.isEmpty()) {
            resobject.put("status","500");
            resobject.put("error","上传挂载正文PDF文件出错");
            return resobject;
        }
        String fileAttachPatch = pdfMap.get("mountpath");//挂载出去的地址
        docObj.put("fileAttachPatch", fileAttachPatch);
        String fileNameDisplay = pdfMap.get("imagefilename");//文件名称
        docObj.put("fileNameDisplay", fileNameDisplay);


        docObj.put("signMethod", "ORDER");
        JSONArray signersArr = new JSONArray();
        JSONObject signersObj = new JSONObject();
        signersObj.put("code", code);
        signersObj.put("codeType", "USC");
        signersObj.put("revokeFlag", "false");
    JAVATools.SetCmdwritelog("手动用印单","开始做dzyyfs的判断了");

        if("0".equals(dsmdy)){
            docObj.put("acrossSealSkipPage", "DISABLE"); //单面打印
        }else if("1".equals(dsmdy)){
            docObj.put("acrossSealSkipPage", "ENABLE"); //双面打印
        }


        if ("0".equals(dzyyfs)) { //电子件
            docObj.put("effectType", "ELECTRONIC"); //
        } else if ("1".equals(dzyyfs) ||("3".equals(yyfs))) {  //电子防伪件
            docObj.put("effectType", "PAPER");
            // Integer userid= Util.getIntValue(yqxdyr);
            // if(userid!=-1){
            Map<String,String> map= getUserMap(yqxdyr);

            if(map!=null&&map.size()>0){
                /*  User use=new User(userid);*/
                JSONObject printSettingobj=new JSONObject();
                printSettingobj.put("personName", map.get("username"));
                printSettingobj.put("personNum",map.get("usrlogins") );
                printSettingobj.put("printNum", fwdyfs);
                docObj.put("printSetting",printSettingobj);
            }


        }else if("2".equals(dzyyfs)){//对手方用印
            docObj.put("effectType", "NOWATERMARK");
        }else{
            resobject.put("status","500");
            resobject.put("error","请选择电子件！！！");
            return resobject;
        }



        String yzcode = getSignCode(yz);
        if ("".equals(yzcode)) {
            resobject.put("status","500");
            resobject.put("error","未找到对应的印章ID");
            return resobject;
        }
        yzcode+=","+sealIdqfz;
        signersObj.put("sealId", yzcode);  //印章id
        signersObj.put("signNum", "1");
        signersObj.put("ownerType", "INSIDE");
        signersObj.put("signatoryType", "ENTERPRISE");
        signersObj.put("keyWord", "华泰证券股份有限公司签章");
        signersObj.put("signMethod", "TRUSTEESHIP");
        signersObj.put("signedExamine", "DISABLE");
        signersArr.add(signersObj);
        docObj.put("signers", signersArr);
        docObj.put("validityStartDate", sdf.format(new Date()));
        docObj.put("validityEndDate", getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));
   JAVATools.SetCmdwritelog("手动用印件","docobject:"+docObj.toJSONString());
    return docObj;
    }


    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 value="";
        Map<String,String> map=new HashMap<>();
        if("".equals(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);
            }
        }
        map.put("username",username);
        map.put("usrlogins",usrlogins);
        return map;
    }


    private String GetDetaiMainid(String mainrequestid,String docid,String tablename){
        RecordSet rs = new RecordSet();
       String mainid= JAVATools.getMaintableid(mainrequestid);
       JAVATools.SetCmdwritelog("获取用印登记单的id",mainid);
        String value="";
        String sql="select  wm_concat_old(id) id from "+tablename+" where Mainid='"+mainid+"' and wjmc in （"+docid+")";
        //获取主表id
        JAVATools.SetCmdwritelog("获取用印登记单明细表的sql：",sql);
        rs.execute(sql);
        if(rs.next()){
            value=  Util.null2String(rs.getString("id"));
        }
        return value;
    }

    private List<Map<String,String>> getdetail(String mainid,String tablename,String tabledetailid){
        List<Map<String,String>> maplist=new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sqlvalue="";
        if("".equals(tabledetailid)||tabledetailid.length()<=0){
             sqlvalue="select id,yyfs,sfyy,wjmc,dsmdy,dzyyfs,zpdfhwj,yqxdyr,fwdyfs from "+tablename+"_dt1 where mainid in ("+mainid+")";
        }else{
            sqlvalue="select id,yyfs,sfyy,wjmc,dsmdy,dzyyfs,zpdfhwj,yqxdyr,fwdyfs from "+tablename+"_dt1 where mainid in ("+mainid+") and id in ("+tabledetailid+")";

        }

        rs.execute(sqlvalue);
        if(rs.getArray().size()<=0){
            return  maplist;
        }
        while (rs.next()){
            Map<String,String> mapdetail=new HashMap<>();
            String detailid=Util.null2String(rs.getString("id"));
            String wjmc=Util.null2String(rs.getString("wjmc"));
            if(detailid==""||wjmc==""){
                break;
            }
            //测试
       //     String pdfwjmc=Util.null2String(rs.getString("zpdfhwj"));
            for (String fileid:wjmc.split(",")) {
                Map<String,String> pdfwjmcmap= getAcction(fileid,detailid,tablename+"_dt1");
                if(pdfwjmcmap==null||pdfwjmcmap.size()<=0){
                    break;
                }
                String pdfwjmcdocd=pdfwjmcmap.get("docid");
                String pdfwjmc=pdfwjmcmap.get("pdfid");
                mapdetail.put("sfyy",Util.null2String(rs.getString("sfyy")));
                mapdetail.put("wjmc",pdfwjmc);
                mapdetail.put("docid",pdfwjmcdocd);
                mapdetail.put("detailid",detailid);
                mapdetail.put("dsmdy",Util.null2String(rs.getString("dsmdy")));
                mapdetail.put("dzyyfs",Util.null2String(rs.getString("dzyyfs")));
                mapdetail.put("yqxdyr",Util.null2String(rs.getString("yqxdyr")));
                mapdetail.put("fwdyfs",Util.null2String(rs.getString("fwdyfs")));
                mapdetail.put("yyfs",Util.null2String(rs.getString("yyfs")));
                maplist.add(mapdetail);
            }


        }

        return  maplist;
    }

    /**
     * 读取最新版本的正文文件并上传至指定目录
     * @param requestid 流程请求ID
     * @param fileids 文档ID
     * @return 结果集合
     */
    public Map<String,String> getLatestVersionPDF(String requestid,String fileids){
        Map<String,String> map = new HashMap<>();

        PropBean pb = new PropBean();
        try{
            //取最大版本的正文信息
            String sql = "        select f.imagefileid,f.imagefilename from imagefile f  " +
                    " where f.imagefileid in     (?)";
            System.out.println("----------sqlmanualsignaction:------------"+sql+":---"+fileids);
            JAVATools.SetCmdwritelog("sqlmanualsignaction",sql+":---"+fileids);

            RecordSet rs = new RecordSet();
            rs.executeQuery(sql,fileids);
            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){
                //    postfix="."+imagefilenamehz.split(".")[imagefilenamehz.split(".").length-1];
                    if(imagefilenamehz.indexOf(".")>0){
                        postfilename=imagefilenamehz.substring(0,imagefilenamehz.lastIndexOf("."));
                    }

                }
                postfix=".pdf";
//                String imagefilename = Util.null2String(rs.getString("imagefilename"));
                String imagefilename = imagefileid+postfix;
                String imagefilepostname="";
                if(!"".equals(postfilename)){
                    imagefilepostname=postfilename+postfix;
                }else{
                    imagefilepostname=imagefileid+postfix;
                }
                JAVATools.SetCmdwritelog("手动用印登记","走到了这一步："+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)){
                    log.info("获取的用印上传共享目录为空！");
                    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();
                }
//                file.createNewFile();
                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);
                map.put("imagefilename",imagefilepostname);
                map.put("realpath",path);
                String Signmountpath = Util.null2String(pb.getPropName("Signmountpath"));
                String mountpath=Signmountpath+folderName+"/"+imagefilename;
                map.put("mountpath",mountpath);
                JAVATools.SetCmdwritelog("手动用印登记","mountpath："+mountpath);

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

    public  Map<String,String> getAcction(String docid,String detailid,String mainid){
        RecordSet rs = new RecordSet();
        ConvertToPdf convertToPdf=new ConvertToPdf();
        ConvertDocToPdf convertDocToPdf = new ConvertDocToPdf();
        Map<String,String> map=new HashMap<>();
        String rsdetail="";
        String docidids="";
       // String sql="select imagefileid,imagefilename,docid from DocImageFile where docid in ("+docid+")";
        String sql = "select imagefileid,imagefilename,docid  from (select * from DocImageFile t where docid in ("+docid+") order by operatedate desc,operatetime desc ) where ROWNUM <= 1";

        rs.execute(sql);
        if(rs.getArray().size()<=0){
            return  null;
        }
        while (rs.next()){
           int imagefileid= Integer.parseInt(rs.getString("imagefileid"));
            String imagefilename=  Util.null2String(rs.getString("imagefilename"));
            if(!"".equals(imagefilename)){
                imagefilename=imagefilename.toLowerCase();
            }
            docidids= rs.getString("docid");
            int imagepdfid=0;
            int imagefileleng= imagefilename.split("\\.").length;
            if(imagefileleng>0) {
                imagefileleng=imagefileleng-1;
            }
            System.out.println("----------houzhunming:------------imagefileleng"+imagefileleng+":---imagefilename"+imagefilename);
            System.out.println("----------houzhunming:---------name:"+imagefilename.split("\\.")[imagefileleng]+"------");

            if("pdf".equals(imagefilename.split("\\.")[imagefileleng])){
                imagepdfid=imagefileid;
                }else{
                imagepdfid =convertToPdf.getDownloadPDFUrl(imagefileid,imagefilename,false);
//                imagepdfid = convertDocToPdf.ConvertToPDF(imagefileid,imagefilename,true);
            }

            rsdetail+=imagepdfid+",";
        }
        if("".equals(rsdetail)){
            return null;
        }
        if(rsdetail.length()>0){
            rsdetail=rsdetail.substring(0,rsdetail.length()-1);
        }
        map.put("docid",docidids);
        map.put("pdfid",rsdetail);

        String sqlvalue="update "+mainid+" set zpdfhwj='"+rsdetail+"' where id="+detailid;
        rs.execute(sqlvalue);

        return map;

    }

    //失败之后状态回写
    public void failcalback(String reqeustid,String detailid,String tablename){
        RecordSet rs = new RecordSet();
        System.out.println("失败之后复写状态");
        System.out.println("reqeustid:" + reqeustid + "detailid:" + detailid + "tablename:" + tablename);
        if("".equals(tablename)){
            return;
        }
        try {
            String sql = "";
            if ("".equals(detailid)) {
                sql = "update " + tablename + "_dt1 set yyzt=4,fwjyyzt=3,dzjyyzt=3 where mainid in (select id from "+ tablename + " where requestid="+reqeustid+" )";
            } else {
                sql = "update " + tablename + "_dt1 set yyzt=4,fwjyyzt=3,dzjyyzt=3 where id in (" + detailid + ")";
            }
            System.out.println("sql:"+sql);
            rs.execute(sql);
        }catch (Exception exo){
            System.out.println("失败:"+exo.getMessage());
        }
        System.out.println("成功之后复写状态---end");
    }


    public void setDetail(String reqeustid,String detailid,String tablename){
        RecordSet rs = new RecordSet();
        System.out.println("成功之后复写状态");
        System.out.println("reqeustid:" + reqeustid + "detailid:" + detailid + "tablename:" + tablename);
        if("".equals(tablename)){
            return;
        }
        try {
            String sql = "";
            if ("".equals(detailid)) {
                sql = "update " + tablename + "_dt1 set yyzt=2 where mainid in (select id from "+ tablename + " where requestid="+reqeustid+" )";
            } else {
                sql = "update " + tablename + "_dt1 set yyzt=2 where id in (" + detailid + ")";
            }
            System.out.println("sql:"+sql);
            rs.execute(sql);
        }catch (Exception exo){
            System.out.println("失败:"+exo.getMessage());
        }
        System.out.println("成功之后复写状态---end");
    }

    /**
     * 印章ID转印章编号
     * @param signid 印章ID
     * @return 印章编号
     */
    private String getSignCode(String signid){
        RecordSet rs = new RecordSet();
        String yzbhvalue="";
        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) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 对手方用印用的逻辑，暂时用不上了
     * @param yywjmap
     * @param requestid
     * @param user
     * @return
     */
    private Map<String,Object> sortEsealType(List<Map<String,String>> yywjmap, String requestid, User user){
        Map<String,Object> resultMap = new HashMap<>();
        List<Map<String,String>> oldSealList = new ArrayList<>();
        List<Map<String,String>> newSealList = new ArrayList<>();
        for (Map<String,String> docmap :yywjmap) {
            String dzyyfs = docmap.get("dzyyfs").toString();

            if("0".equals(dzyyfs)||"1".equals(dzyyfs)){//电子件/防伪打印件
                oldSealList.add(docmap);
            }else if("2".equals(dzyyfs)){//对手方电子件
                newSealList.add(docmap);
            }
        }

        if(newSealList.size()>0){
            String result = sendFromApplicationFileNew(newSealList,requestid,user);
            JSONObject res = JSONObject.parseObject(result);
            String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
            if(!"200".equals(status)){
                resultMap.put("result","error");
                resultMap.put("message",result);
                return resultMap;
            }else {
                resultMap.put("result","success");
                resultMap.put("message",result);
            }
        }

        if(oldSealList.size()>0){
            resultMap.put("continue",true);
            resultMap.put("newMapList",oldSealList);
        }else{
            resultMap.put("continue",false);
        }

        return resultMap;
    }

    /**
     * 新用印申请触发电子签章-文件
     * @param sealMap
     * @return
     */
    public String sendFromApplicationFileNew(List<Map<String,String>> sealMap, String requestid, User user){
        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{
            SendManualSignService sendManualSignService = ServiceUtil.getService(SendManualSignService.class);

            ManualSignEntity manualSignEntity = sendManualSignService.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 = 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();
            }

            //签署方信息
            String yzcode = getSignCode(yz);
            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");
            signer.setEmail(user.getEmail());
            Map<String,String> seals = new HashMap<>();
            seals.put("sealId",yzcode);
            signer.setSeals(seals);

            //用印文件列表
            List<DocSign> docSignList = new ArrayList<>();
            List<String> idList = new ArrayList<>();
            for(Map<String,String> docmap :sealMap){
                DocSign docSign = new DocSign();
                String pdfid = docmap.get("wjmc");
                String docid = docmap.get("docid");
                String id = docmap.get("detailid");
                idList.add(id);

                //文件类型
                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 = sendManualSignService.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);

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

                docSignList.add(docSign);

//                Map<String,String>mapdoc=new HashMap<>();
//                mapdoc.put("detailid",id);
//                mapdoc.put("pdfdocid",pdfid);
//                mapdoc.put("dzyyfs","3");
//                setdetaildoc(tableName+"_dt2",requestid,mapdoc,docid);
            }
            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用印失败");
                failcalback(requestid,String.join(",",idList),tableName);
                messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
                return resobject.toJSONString();
            }
            setDetail(requestid,String.join(",",idList),tableName);
            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();
    }

}
