package com.engine.htsc.seal.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.ServiceUtil;
import com.engine.htsc.seal.lhht.Service.Impl.WorkflowSealLhhtServiceImpl;
import com.engine.htsc.seal.lhht.Service.WorkflowSealLhhtService;
import com.engine.htsc.seal.service.ManualSignHandleService;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.util.UploadDocUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class WorkflowSealAction {

    /**
     * 查询人员待办
     * @param request
     * @param response
     * @return
     */
    @GET
    @Path("/receiveSeal")
    @Produces({MediaType.TEXT_PLAIN})
    public String receiveSeal(@Context HttpServletRequest request, @Context HttpServletResponse response){

        JSONObject apidatas = new JSONObject();

        BaseBean bb = new BaseBean();
        bb.writeLog("获取到消息！！！！" );
        PropBean pb = new PropBean();
        String ManualSigndoctype=pb.getPropName("ManualSign.doctype");
        String AutoSigndocType=pb.getPropName("AutoSign.docType");
        String yywj_signfile=pb.getPropName("yywj_signfile");
        bb.writeLog("获取用印文件路径:"+yywj_signfile);
        //获取用户
        String recordvalue = Util.null2String(request.getParameter("recordvalue"));


        try {

            if(!"".equals(recordvalue))
            {
                bb.writeLog("接收到用印文件请求消息！！！！" );

                JSONObject recordsObject = JSONObject.parseObject(recordvalue);
                bb.writeLog("recordvalue:"+recordvalue);
                String flowNum = recordsObject.getString("flowNum");

                //判断流程-如果是用印登记单流程就继续，如果不是就转到service
                String requestid = JAVATools.getRequestidByRequestMark(flowNum);
                String workflowid = JAVATools.getWorkflowidByRequestid(requestid);
                String workflowType = pb.getWorkflowUnNumberByid(workflowid);

                if("lhht".equals(workflowType) || "jjhyy".equals(workflowType)){
                    WorkflowSealLhhtService workflowSealLhhtService = ServiceUtil.getService(WorkflowSealLhhtServiceImpl.class);
                    return workflowSealLhhtService.receiveSeal(recordsObject,requestid,workflowType);
                }



                if(!"yydjb".equals(workflowType)){
                    ManualSignHandleService manualSignHandleService = ServiceUtil.getService(ManualSignHandleService.class);
                    return manualSignHandleService.receiveSeal(recordsObject,requestid,workflowType);
                }

                //将编号转成id
                flowNum=JAVATools.GetBhtorequestid(flowNum);
                bb.writeLog("接收到用印文件请flowNum:"+flowNum);
                String docSigns = recordsObject.getString("docSigns");
                String tablename= "";
                String status="";
                String signers="";
                String docid="";
                JSONArray jsonArray = JSONArray.parseArray(docSigns);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    status=jsonObject.get("status").toString();
                    signers=jsonObject.get("signers").toString();
                    docid=jsonObject.get("docId").toString();
                    if (ManualSigndoctype.equals(jsonObject.get("docType"))) {
                       // flowNum = flowNum.split("_")[0].toString();
                        tablename = getMaintable(flowNum);
                        if (!failflowSet(signers, tablename, flowNum, recordvalue,docid)) {
                            apidatas.put("data", "签署失败文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        } else if ("7".equals(status)) {
                            //加载水印
                            watermarkSet(tablename, flowNum, recordvalue);
                            //拒签
                          //  refuseSet(tablename, flowNum, recordvalue, jsonObject.get("docType").toString(), ManualSigndoctype);
                            apidatas.put("data", "签文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        } else if ("8".equals(status)) {
                            //加载水印失败，则失败
                            watermarkfail(tablename, flowNum, recordvalue,docid);
                            //拒签
                            //  refuseSet(tablename, flowNum, recordvalue, jsonObject.get("docType").toString(), ManualSigndoctype);
                            apidatas.put("data", "签文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        }else if ("6".equals(status)) {
                            //拒签
                            refuseSet(tablename, flowNum, recordvalue);

                            autoError(tablename,flowNum,"2",docid);
                            apidatas.put("data", "签文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        }else if("5".equals(status)){
                            //手动用印
                            return  ManualRetrun(recordvalue);
                        }else {
                            OtherManual(tablename, flowNum, recordvalue);                          //  apidatas.put("data", "签文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        }
                    }else{
                        //自动
                        if ("7".equals(status)) {
                            //加载水印
                            watermarkSet(tablename, flowNum, recordvalue);
                            //拒签
                            //  refuseSet(tablename, flowNum, recordvalue, jsonObject.get("docType").toString(), ManualSigndoctype);
                            apidatas.put("data", "签文件保存成功！！！");
                            apidatas.put("status", "200");
                            return apidatas.toJSONString();
                        }else if("5".equals(status)) {
                            tablename = getMaintable(flowNum);
                            bb.writeLog("开始自动用印了印文件请求消息！！！！");
                            MessageDetailLog messageDetailLog = new MessageDetailLog(tablename);
                            messageDetailLog.writLogsnotretrun(flowNum, recordvalue, "2", messageDetailLog.success);
                            return AutoSignReturn(docSigns, flowNum, yywj_signfile);
                        }
                    }
                }
            }else{
                apidatas.put("resultMsg","接口参数为空");
                apidatas.put("status", "-1");
            }
        }catch (Exception e){
            bb.writeLog("e99999:"+e);
            apidatas.put("resultMsg","异常");
            apidatas.put("status", "-1");
        }
        return apidatas.toJSONString();
    }

    //是否用印失败
   public boolean failflowSet(String signers,String tablename,String request,String value,String docid) {
        boolean flag=true;
       System.out.println("开始判断是否用印失败:" + signers);
        JSONArray jsonArray = JSONArray.parseArray(signers);
       for (int i = 0; i < jsonArray.size(); i++) {
           JSONObject jsonObject = (JSONObject) jsonArray.get(i);
          if("7".equals(jsonObject.get("status").toString())){
               flag=false;
               //将明细表里的数据状态置为失败
              MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
              messageDetailLog.writLogsnotretrun(request,value,"2",messageDetailLog.fail);
            //  if(ManualSigndoctype.equals(doctype)){
                  //签章失败！
              new  ManualworkflowAction().callbackflow(value,"4");
              //}
              autoError(tablename,request,"3",docid);
           }
       }
       return  flag;
   }

    //水印.不做任何处理。只写入日志
    public void watermarkSet(String tablename,String request,String value){
        MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
        messageDetailLog.writLogsnotretrun(request,value,"2",messageDetailLog.watermark);
    }

    //水印失败，则失败
    public void watermarkfail(String tablename,String request,String value,String docid){
        MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
        messageDetailLog.writLogsnotretrun(request,value,"2",messageDetailLog.fail);
        new  ManualworkflowAction().callbackflow(value,"4");
        autoError(tablename,request,"3",docid);
    }

    //拒签。将数据库明细表的值修改
    public void refuseSet(String tablename,String request,String value){
        MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
        messageDetailLog.writLogsnotretrun(request,value,"2",messageDetailLog.refuse);
        //if(ManualSigndoctype.equals(doctype)){
            //如果是手动用印，那么将数据置为拒签
          new  ManualworkflowAction().callbackflow(value,"5");

       // }
    }




    public void autoError(String tablename,String requestid,String dzyyzt,String docid){

        String mainid=JAVATools.getMaintableid(requestid);
        RecordSet rs=new RecordSet();
        String sql="select * from "+tablename+"_dt2 where docid='"+docid+"' and mainid='"+mainid+"'";
        rs.execute(sql);
       if(rs.getCounts()<=0){
           JAVATools.SetCmdwritelog("手动用印类型为null","sql:"+sql);
           return;
       }
        String dtoneid="";
        String dzyylx="";

        if (rs.next()) {
            dtoneid= Util.null2String(rs.getString("dtoneid"));
            dzyylx= Util.null2String(rs.getString("dzyylx"));
        }
        if("".equals(dtoneid)||"".equals(dzyylx)){
            JAVATools.SetCmdwritelog("手动用印类型为null","sql:"+sql);
            return;
        }
        String udpatesql="";
        if ("0".equals(dzyylx)) {
            udpatesql="update "+tablename+"_dt1 set dzjyyzt=? where id='"+dtoneid+"'";
        }else if("1".equals(dzyylx)){
            udpatesql="update "+tablename+"_dt1 set fwjyyzt=? where id='"+dtoneid+"'";
        }
        if(!"".equals(udpatesql)){
            JAVATools.SetCmdwritelog("用印单失败之后状态的回写：",udpatesql+" params:"+dzyyzt);
            rs.executeQuery(udpatesql,dzyyzt);

        }
    }

    public void OtherManual(String tablename,String request,String value){
        MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
        messageDetailLog.writLogsnotretrun(request,value,"2",messageDetailLog.Other);
    }





    public String AutoSignReturn(String docSigns,String flowNum,String yywj_signfile){
        JSONObject apidatas = new JSONObject();
        UploadDocUtil uploadDocUtil = new UploadDocUtil();
        String docId = "";
        String fileId = "";
        String codeType="";
        BaseBean bb = new BaseBean();
             if (!"".equals(docSigns)) {
            JSONArray jsonArray = JSONArray.parseArray(docSigns);
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                docId = jsonObject.getString("docId");
                JSONArray signedFileArray = jsonObject.getJSONArray("signedFile");
                for (int j = 0; j < signedFileArray.size(); j++) {
                    JSONObject signedObject = signedFileArray.getJSONObject(j);
                    fileId = signedObject.getString("fileId").replace("/oa", yywj_signfile);
                }
                System.out.println("fileId:" + fileId);
            }
        }

        long currentTime = System.currentTimeMillis();
        String returnsignetfile= new PropBean().getPropName("returnsignetfile");
        String realpath = returnsignetfile + flowNum + "_" + docId + "_" + currentTime;
        bb.writeLog("realpath:" + realpath);
        //数据接收到！！！

        int newdocid =-1;
        int newimagefileid=-1;
        String imagefilename="";
        String realfilepath="";
        System.out.println( "-----------------------------");
        System.out.println( "docid:"+docId+"fileId:"+fileId+"realpath:"+realpath);
        Map<String,String>  mapnew=uploadDocUtil.uploadFile(docId, fileId, realpath);

       if(mapnew.size()<=0){
           bb.writeLog("newdocid没有获取到:"+newdocid);
           apidatas.put("resultMsg","newdocid没有获取到");
           apidatas.put("status", "201");
           return apidatas.toJSONString();
       }
        newdocid=Integer.parseInt(mapnew.get("newdocid").toString());
        newimagefileid=Integer.parseInt(mapnew.get("newimagefileid").toString());
        imagefilename=mapnew.get("imagefilename").toString();
        realfilepath=mapnew.get("imagefilename").toString();
        if(newdocid<0){
            bb.writeLog("newdocid没有获取到:"+newdocid);
            apidatas.put("resultMsg","newdocid没有获取到");
            apidatas.put("status", "201");
            return apidatas.toJSONString();
        }
        //将输入写入主表zwyy中
        SetMmainable(flowNum,newdocid);
        uploadDocUtil.Callbackgateway(newimagefileid,imagefilename,realfilepath);
        apidatas.put("data","请求成功！！！");
        apidatas.put("status", "200");

        return apidatas.toJSONString();
/*        Map<String,String> map=new HashMap<>();
        map.put("requestid",flowNum);
        map.put("docid",docId);
        map.put("newdocid",String.valueOf(newdocid));
        map.put("yyimagefileid",String.valueOf(newimagefileid));
        bb.writeLog("newdocid:" + newdocid);*/


    }
    public String ManualRetrun(String recordvalue){
        ManualworkflowAction manualworkflowAction=new ManualworkflowAction();
        return manualworkflowAction.Manualworkflow(recordvalue);
    }



    //获取doctype
    public String getdoctype(String sgnersarray){
        JSONArray jsonArray = JSONArray.parseArray(sgnersarray);
        String doctype="";
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            doctype=jsonObject.get("doctype").toString();
        }
        return doctype;
    }

    public boolean SetMmainable(String reqid,int zzyy){
        boolean flag=true;
        BaseBean bbbasebean = new BaseBean();
        try {
                RecordSet rs = new RecordSet();
            String formid =getMaintable(reqid);

            String sqlvalue = "update " + formid + " set zwyy='" + zzyy + "' where requestid=" + reqid;
            bbbasebean.writeLog("用印调用反馈回来的数据是ypfk:"+sqlvalue);
            rs.execute(sqlvalue);
        }catch (Exception exo){
            flag=false;
            bbbasebean.writeLog("用印调用反馈报错ypfkbc:"+exo.getMessage());
        }
        return flag;
    }

    public String getMaintable(String reqid){
        RecordSet rs = new RecordSet();
        String sql = " select abs(t.formid) as formid \n" +
                " from workflow_base t\n" +
                " inner join workflow_requestbase l on l.workflowid = t.id\n" +
                " where l.requestid=" + reqid + "";
        rs.execute(sql);
        String formid = "formtable_main_";

        if (rs.next()) {
            formid = formid + com.weaver.general.Util.getIntValues(rs.getString("formid"));
        }
        return formid;
    }
    //保存到建模表里
    public boolean Setmodelrms(Map<String,String> Map){
        boolean flag=true;
        String requestid=Map.get("requestid").toString();
        String docid=Map.get("docid").toString();
        String newdocid=Map.get("newdocid").toString();
        String yyimagefileid=Map.get("yyimagefileid").toString();
        RecordSet rs = new RecordSet();
        String connsum="";
        String sqlvalue="select count(*) as counsum from uf_rmsjmb  where requestid='"+requestid+"' and docid='"+docid+"'";
        rs.execute(sqlvalue);
        if (rs.next()) {
            connsum= rs.getString("counsum");
        }
        if(connsum=="0"){
            //新增数据
            String insertSql = "insert into uf_rmsjmb(requestid,docid,yydocid,yyimagefileid) values(?,?,?,?)";
            flag=  rs.executeUpdate(insertSql,new Object[]{requestid,docid,newdocid,yyimagefileid});

        }else{
            //修改数据
            String insertSql = "update uf_rmsjmb set yydocid=?,yyimagefileid=? where requestid=? and docid=?";
            flag=  rs.executeUpdate(insertSql,new Object[]{newdocid,yyimagefileid,requestid,docid});
        }
        return flag;
    }




}
