package com.engine.htsc.seal.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
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.UploadDocSyncUtil;
import weaver.interfaces.htsc.util.UploadDocUtil;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class ManualworkflowAction {


    public String Manualworkflow(String recordvalue){
        JSONObject apidatas = new JSONObject();
        PropBean pb = new PropBean();
        BaseBean bb = new BaseBean();
        String dzyyfs="";
        String yywj_signfile=pb.getPropName("yywj_signfile");
        bb.writeLog("开始走手动用印！！！！" );

        try {
            UploadDocUtil uploadDocUtil = new UploadDocUtil();
            if(!"".equals(recordvalue))
            {
                JSONObject recordsObject = JSONObject.parseObject(recordvalue);
                String flowNum =recordsObject.getString("flowNum");
                flowNum=JAVATools.GetBhtorequestid(flowNum);
                String docSigns = recordsObject.getString("docSigns");
                String tablename=  getMaintable(flowNum);
                MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
                messageDetailLog.writLogsnotretrun(flowNum,recordvalue,"2",messageDetailLog.success);
                String docId = "";
                String detailid="";
                String docdetailid="";
                String fileId = "";
                if (!"".equals(docSigns)) {
                    JSONArray jsonArray = JSONArray.parseArray(docSigns);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        docdetailid = jsonObject.getString("docId");
                        if(docdetailid.split("_").length>1){
                            detailid=docdetailid.split("_")[0];
                            docId=docdetailid.split("_")[1];
                        }
                        if(isPAPER(flowNum,detailid,docdetailid)){
                            dzyyfs="1";
                            JSONArray rxfFilesArray = jsonObject.getJSONArray("rxfFiles");
                            if(rxfFilesArray!=null&&rxfFilesArray.size()>0){
                                for (int j = 0; j < rxfFilesArray.size(); j++) {
                                    JSONObject signedObject = rxfFilesArray.getJSONObject(j);
                                    fileId = signedObject.getString("rxfFilePath").replace("/oa", yywj_signfile);
                                }
                            }
                        } else{
                            dzyyfs="0";
                            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);
                    }
                }
                //过去没有fileid数据，比如防伪打印件下面的pdf文件
                if("".equals(fileId)){
                    bb.writeLog("newdocid没有获取到:"+fileId);
                    apidatas.put("status", "200");
                    return apidatas.toString();
                }
                //去重操作
//                if(!distinctseal(tablename,detailid,docId,dzyyfs)){
//                    bb.writeLog("重复文件");
//                    apidatas.put("status", "200");
//                    return apidatas.toString();
//                }

                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;
                System.out.println( "-----------------------------");
                System.out.println( "docid:"+docId+"fileId:"+fileId+"realpath:"+realpath);
                Map<String,String> mapnew=uploadDocUtil.ManualSignuploadFile(docId, fileId, realpath);
                newdocid=Integer.parseInt(mapnew.get("newdocid"));
                newimagefileid=Integer.parseInt(mapnew.get("newimagefileid"));
                String imagefilename=mapnew.get("imagefilename");
                String realfilepath=mapnew.get("realfilepath");
                if(newdocid<0){
                    bb.writeLog("newdocid没有获取到:"+newdocid);
                    apidatas.put("resultMsg","newdocid没有获取到");
                    apidatas.put("status", "201");
                    return apidatas.toString();
                }
                Jedis jedis = RedisTools.GetJedis();
                String rediskey="yydjb_redis_key";
                try{
                    int counts=0;
                    int expireTime=Util.getIntValue(Util.null2String(pb.getPropName("RedisExpiretime")));
                    boolean redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,flowNum,expireTime);
                    JAVATools.SetCmdwritelog("yydjbredis开始状态:"+redisfalg+"flowNum:"+flowNum);
                    while (redisfalg==false && counts<10) {
                        Thread.sleep(500);
                        counts++;
                        redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,flowNum,expireTime);
                    }
                    JAVATools.SetCmdwritelog("yydjbredis结束状态:"+redisfalg+"flowNum:"+flowNum);
                    if(redisfalg){
                        if(!SignStatusutil.isAutoSingetType(tablename,detailid)){
                            //如果不是公文防伪打印件逻辑
                            JAVATools.SetCmdwritelog("如果不是公文防伪打印件逻辑flowNum:"+flowNum);
                            new SignStatusutil().SetMmainable(flowNum,detailid,newdocid,docId);
                        }else{
                            //公文防伪打印件逻辑
                            JAVATools.SetCmdwritelog("公文防伪打印件逻辑flowNumflowNum:"+flowNum);
                            new SignStatusutil().SetSussmage(tablename,detailid,dzyyfs,docId,flowNum,newdocid);
                        }
                    }

                }catch (Exception exo){
                    JAVATools.SetCmdwritelog("用印登记单保存失败"+exo.getMessage());
                }finally {
                    JAVATools.SetCmdwritelog("用印登记单解锁开始");
                    RedisTools.releaseDistributedLock(jedis,rediskey,flowNum);
                    JAVATools.SetCmdwritelog("用印登记单解锁结束");
                    JAVATools.SetCmdwritelog("用印登记单释放锁开始");
                    jedis.close();
                    JAVATools.SetCmdwritelog("用印登记单释放锁结束");
                }




                // uploadDocUtil.Callbackgateway(newimagefileid,imagefilename,realfilepath);
                //通过异步多线程的方式
                new UploadDocSyncUtil(newimagefileid,imagefilename,realfilepath).start();
                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);
            }else{
                apidatas.put("resultMsg","接口参数为空");
                apidatas.put("status", "-1");
            }
        }catch (Exception e){
            bb.writeLog("e99999:"+e);
            apidatas.put("resultMsg","异常");
            apidatas.put("status", "-1");
        }
        apidatas.put("data","数据获取成功");
        apidatas.put("status", "200");
        return apidatas.toJSONString();
    }

    //判断数据是否入库
    public boolean distinctseal(String tablename,String requestid,String detailid,String docid,String dzyyfs){
    int expireTime=1000;
    int counts=0;
    String rediskey="redisseal_lock";
    try {
    boolean flag = false;
    Jedis jedis = RedisTools.GetJedis();
    boolean redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,requestid,expireTime);
    while (redisfalg==false && counts>10) {
        Thread.sleep(1000);
        counts++;
        redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,requestid,expireTime);
    }
    if(redisfalg){
        if (!SignStatusutil.isAutoSingetType(tablename, detailid)) {
            //如果不是电子用印件或者防伪打印件去重逻辑
            //只需要判断明细表的用印状态即可
            flag = SignStatusutil.ISsucess(tablename, detailid);
        } else {
            //公文防伪打印件逻辑去重逻辑
            //需要判断
            flag = SignStatusutil.IsPAPERSucess(tablename, detailid, dzyyfs);
        }
    }

    return flag;

    }catch (Exception exo){
        return false;
    }
    }


    //如果失败或者拒签，回写状态值
    public String callbackflow(String recordvalue,String statustype){
        JSONObject apidatas = new JSONObject();

        PropBean pb = new PropBean();
        BaseBean bb = new BaseBean();
        RecordSet rs=new RecordSet();
        String yywj_signfile=pb.getPropName("yywj_signfile");
        bb.writeLog("手动用失败或拒签！！！！"+statustype );

        try {
            UploadDocUtil uploadDocUtil = new UploadDocUtil();
            if(!"".equals(recordvalue))
            {
                JSONObject recordsObject = JSONObject.parseObject(recordvalue);
                String flowNum = recordsObject.getString("flowNum");
                flowNum=JAVATools.GetBhtorequestid(flowNum);
                //   String flowNum=flowNumsiplit.split("_")[0].toString();
                String docSigns = recordsObject.getString("docSigns");
                String tablename=  getMaintable(flowNum);
                //MessageDetailLog messageDetailLog=new MessageDetailLog(tablename);
                //messageDetailLog.writLogsnotretrun(flowNum,recordvalue,"2",messageDetailLog.success);
                String docId = "";
                String detailid="";
                String docdetailid="";

                String fileId = "";
                if (!"".equals(docSigns)) {
                    JSONArray jsonArray = JSONArray.parseArray(docSigns);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        docdetailid = jsonObject.getString("docId");
                        detailid="";
                        if(docdetailid.split("_").length>1){
                            detailid=docdetailid.split("_")[0];
                        }
                        if(!"".equals(detailid)){
                            String sql="update "+tablename+"_dt1 set yyzt="+statustype+"  where id in("+detailid+")";
                            System.out.println("拒签或是失败的sql是"+sql);
                            rs.execute(sql);
                        }

                    }
                }
            }else{
                apidatas.put("resultMsg","接口参数为空");
                apidatas.put("status", "-1");
            }
        }catch (Exception e){
            bb.writeLog("e99999:"+e);
            apidatas.put("resultMsg","异常");
            apidatas.put("status", "-1");
        }
        apidatas.put("data","数据获取成功");
        apidatas.put("status", "200");
        return apidatas.toJSONString();
    }

    public boolean isPAPER(String reqid,String detailid,String docid){
        RecordSet rs = new RecordSet();
        BaseBean blog=  new  BaseBean();
        boolean flag=false;
        String formid =getMaintable(reqid);

        //判断是
        if(SignStatusutil.isAutoSingetType(formid,detailid)){
            String  sqlvalue = "select count(*) papercount from "+formid+"_dt2 where dzyylx=1 and dzyylx='1' and docid='"+docid+"' and dtoneid='"+detailid+"'";
            JAVATools.SetCmdwritelog("判断是不是防伪打印件",sqlvalue);
            rs.execute(sqlvalue);
            if(rs.next()){
                if(!"0".equals(Util.null2String(rs.getString("papercount")))){
                    flag=true;
                }
            }
            return  flag;
        }

        String  sqlvalue = "select count(*) papercount from "+formid+"_dt1 where dzyyfs=1 and id=" + detailid;
        blog.writeLog("sqlisPAPER是:"+sqlvalue+"req:"+reqid+"detailid:"+detailid);
        rs.execute(sqlvalue);
        if(rs.next()){
            if(!"0".equals(Util.null2String(rs.getString("papercount")))){
                flag=true;
            }
        }
        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;
    }


}
