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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.seal.lhht.Service.WorkflowSealLhhtService;
import com.engine.htsc.seal.web.RedisTools;
import org.apache.commons.lang.StringUtils;
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.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xf
 * @version 1.0.0
 * @ClassName workflowSealLhhtServiceImpl.java
 * @createTime 2021年12月13日 16:08:00
 */
public class WorkflowSealLhhtServiceImpl extends Service implements WorkflowSealLhhtService {

    @Override
    public String receiveSeal(JSONObject recordsObject, String requestid, String workflowType) {
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        JSONObject apidatas = new JSONObject();
        bs.writeLog("receiveSeal start:"+requestid);

        String ManualSigndoctype = pb.getPropName("ManualSign.doctype");

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

            String docSigns = recordsObject.getString("docSigns");
            JSONArray docSignsArray = JSONArray.parseArray(docSigns);
            for(int i=0;i<docSignsArray.size();i++){
                JSONObject docSignObject = (JSONObject)docSignsArray.get(i);
                String status = docSignObject.get("status").toString();
                String signers = docSignObject.get("signers").toString();
                String docid = docSignObject.get("docId").toString();
                String docType = docSignObject.get("docType").toString();
                bs.writeLog("docid:"+docid);
                bs.writeLog("status:"+status);

                if(ManualSigndoctype.equals(docType)){//手动用印
                    boolean signersFlag = true;
                    JSONArray signersArray = JSONArray.parseArray(signers);
                    for(int j=0;j<signersArray.size();j++){
                        JSONObject signObject = (JSONObject)signersArray.get(i);
                        String signStatus = signObject.get("status").toString();
                        if("7".equals(signStatus)){//签署失败
                            signersFlag = false;
                        }
                    }

                    //yyzt:0-未用印，1-不用印，2-用印中，3-已用印，4-用印失败，5-拒签
                    if(!signersFlag){
                        updateSignStatus(workflowType,requestid,tableName,"4",docid,"");
                        messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.fail);
                    }else{
                        if("5".equals(status)){//已完成
                            messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.success);
                            return save(workflowType,requestid,tableName,docSignObject);
                        }else if("6".equals(status)){//拒签
                            updateSignStatus(workflowType,requestid,tableName,"5",docid,"");
                            messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.refuse);
                        }else if("7".equals(status)){//添加水印完成（水印添加成功，合同才可签署）
                            messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.watermark);
                        }else if("8".equals(status)){//添加水印失败
                            updateSignStatus(workflowType,requestid,tableName,"4",docid,"");
                            messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.fail);
                        }else{
                            messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.Other);
                        }

                    }
                }else{//自动用印
                    messageDetailLog.writLogsnotretrun(requestid,recordsObject.toJSONString(),"2",messageDetailLog.Other);
                }
                apidatas.put("data", "签署文件保存成功");
                apidatas.put("status", "200");
            }
        }catch (Exception e){
            e.printStackTrace();
            apidatas.put("resultMsg","异常");
            apidatas.put("status", "-1");
        }

        bs.writeLog("receiveSeal end:"+requestid);
        return apidatas.toJSONString();
    }

    private void updateSignStatus(String workflowType, String requestid, String tableName, String yyzt, String docidStr, String yyhwj){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        String detailid = docidStr.split("_")[0];
        String docId = docidStr.split("_")[1];
        bs.writeLog("workflowType:"+workflowType);
        bs.writeLog("detailid:"+detailid);
        bs.writeLog("docId:"+docId);
        if(StringUtils.isNotEmpty(detailid)&&StringUtils.isNotEmpty(docId)){
            //获得流程当前状态
            String currentnodetype = "";
            String sql = "select currentnodetype from workflow_requestbase where requestid = '"+requestid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            if(rs.next()){
                currentnodetype = Util.null2String(rs.getString("currentnodetype"));
            }
            if("3".equals(currentnodetype)){//已办结
                String update_sql = "update uf_yyxx set yywj = '"+yyhwj+"' where yyid = '"+docidStr+"'";
                bs.writeLog(update_sql);
                rs.executeUpdate(update_sql);
            }
                //总部用印申请，不确定类型，两张明细表都更新一次
                String update_sql = "update "+tableName+"_dt7 set yyzt = '"+yyzt+"', yyhwj = '"+yyhwj+"' where yyid = '"+docidStr+"'";
                bs.writeLog(update_sql);
                rs.executeUpdate(update_sql);

                update_sql = "update "+tableName+"_dt8 set yyzt = '"+yyzt+"', yyhwj = '"+yyhwj+"' where yyid = '"+docidStr+"'";
                bs.writeLog(update_sql);
                rs.executeUpdate(update_sql);

        }

    }

    /**
     * 保存用印成功的文件
     * @param requestid
     * @param tablename
     * @param docSignObject
     */
    private String save(String workflowType, String requestid, String tablename, JSONObject docSignObject){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        JSONObject apidatas = new JSONObject();

        String yywj_signfile=pb.getPropName("yywj_signfile");
        String returnsignetfile= pb.getPropName("returnsignetfile");

        try{
            UploadDocUtil uploadDocUtil = new UploadDocUtil();

            String docidStr = docSignObject.get("docId").toString();
            String detailid = docidStr.split("_")[0];
            String docId = docidStr.split("_")[1];

            String fileId = "";
            String dzyyfs = getDzyyfs(workflowType,tablename,docidStr);
            if("1".equals(dzyyfs)){//防伪打印件
                JSONArray rxfFilesArray = docSignObject.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{//电子件
                JSONArray signedFileArray = docSignObject.getJSONArray("signedFile");
                for (int j=0;j<signedFileArray.size();j++) {
                    JSONObject signedObject = signedFileArray.getJSONObject(j);
                    fileId = signedObject.getString("fileId").replace("/oa", yywj_signfile);
                }
            }
            bs.writeLog("docId:"+docId);
            bs.writeLog("fileId:"+fileId);
            if(StringUtils.isEmpty(fileId)){
                bs.writeLog("newdocid没有获取到:"+docId);
                apidatas.put("status", "200");
                return apidatas.toString();
            }

            long currentTime = System.currentTimeMillis();
            String realPath = returnsignetfile+requestid+"_"+docId+"_"+currentTime;
            bs.writeLog("realPath:"+realPath);

            int newdocid =-1;
            int newimagefileid=-1;
            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");
            bs.writeLog("newdocid:"+newdocid);

            if(newdocid<0){
                bs.writeLog("newdocid没有获取到:"+newdocid);
                apidatas.put("resultMsg","newdocid没有获取到");
                apidatas.put("status", "201");
                return apidatas.toString();
            }

            updateSignStatus(workflowType,requestid,tablename,"3",docidStr,String.valueOf(newdocid));

            Jedis jedis = RedisTools.GetJedis();
            String rediskey = workflowType+"_redis_key";
            try{
                int counts=0;
                int expireTime=Util.getIntValue(Util.null2String(pb.getPropName("RedisExpiretime")));
                boolean redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,requestid,expireTime);
                bs.writeLog("redis开始状态:"+redisfalg+",requestid:"+requestid);
                while (redisfalg==false && counts<10) {
                    Thread.sleep(500);
                    counts++;
                    redisfalg=RedisTools.TryGetDistributedLock(jedis,rediskey,requestid,expireTime);
                }
                bs.writeLog("redis结束状态:"+redisfalg+",requestid:"+requestid);
                if(redisfalg){
                    updateMainTable(workflowType,requestid,tablename,String.valueOf(newdocid));
                }
            }catch (Exception e){
                bs.writeLog(rediskey+"保存失败"+e.getMessage());
            }finally {
                bs.writeLog(rediskey+"解锁开始");
                RedisTools.releaseDistributedLock(jedis,rediskey,requestid);
                bs.writeLog(rediskey+"解锁结束");
                bs.writeLog(rediskey+"释放锁开始");
                jedis.close();
                bs.writeLog(rediskey+"释放锁结束");
            }

            apidatas.put("resultMsg","签署文件保存成功");
            apidatas.put("status", "200");

            new UploadDocSyncUtil(newimagefileid,imagefilename,realfilepath).start();
        }catch (Exception e){
            e.printStackTrace();
            bs.writeLog(e);
            apidatas.put("resultMsg","异常");
            apidatas.put("status", "-1");
        }
        return apidatas.toJSONString();
    }

    /**
     * 更新主表电子用印件
     * @param requestid
     * @param tableName
     */
    public void updateMainTable(String workflowType,String requestid, String tableName, String newDzyyj){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();

        List<String> dzyyjList = new ArrayList<>();
        String mainid = "";
        String dzyyj = "";
        String sql = "select id from "+tableName+" where requestid = '"+requestid+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            mainid = Util.null2String(rs.getString("id"));
        }

             sql = "select yyhwj from "+tableName+"_dt7 where mainid = '"+mainid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while (rs.next()){
                String yyhwj = Util.null2String(rs.getString("yyhwj"));
                if(StringUtils.isNotEmpty(yyhwj)){
                    dzyyjList.add(yyhwj);
                }
            }

            sql = "select yyhwj from "+tableName+"_dt8 where mainid = '"+mainid+"'";
            bs.writeLog(sql);
            rs.executeQuery(sql);
            while (rs.next()){
                String yyhwj = Util.null2String(rs.getString("yyhwj"));
                if(StringUtils.isNotEmpty(yyhwj)){
                    dzyyjList.add(yyhwj);
                }
            }


        dzyyj = org.apache.commons.lang3.StringUtils.join(dzyyjList,",");
        bs.writeLog("dzyyj:"+dzyyj);

        String update_sql = "update "+tableName+" set dzyyj = '"+dzyyj+"' where requestid = '"+requestid+"'";
        bs.writeLog(update_sql);
        rs.executeUpdate(update_sql);
    }

    /**
     * 获得电子用印方式
     * @param workflowType
     * @param tablename
     * @param docidStr
     * @return
     */
    private String getDzyyfs(String workflowType, String tablename, String docidStr){
        RecordSet rs = new RecordSet();

        String dzyyfs = "";
             String sql = "select dzyyfs from "+tablename+"_dt7 where yyid = '"+docidStr+"'";
            rs.executeQuery(sql);
            if(rs.next()){
                dzyyfs =  Util.null2String(rs.getString("dzyyfs"));
            }else{
                sql = "select dzyyfs from "+tablename+"_dt8 where yyid = '"+docidStr+"'";
                rs.executeQuery(sql);
                if(rs.next()){
                    dzyyfs =  Util.null2String(rs.getString("dzyyfs"));
                }
            }


        return dzyyfs;
    }


}
