package com.engine.htxc.eseal.responseaction.util;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.seal.web.ManualworkflowAction;
import com.engine.htxc.commonutil.db.DbTools;
import com.engine.htxc.commonutil.fileutil.GatewayUtil;
import com.engine.htxc.commonutil.log.CustomizeLog;
import com.engine.htxc.eseal.responseaction.config.ReponseSealConfig;
import com.engine.htxc.eseal.responseaction.num.EsealTypeEnum;
import org.apache.commons.lang.StringUtils;
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 java.util.*;
import java.util.stream.Collectors;

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName EsealPesUtil.java
 * @createTime 2022年06月26日 23:46:00
 */
public class EsealPesUtil extends Service {

    public String id = "";
    public String tablename = "";
    public String yzcode="";
    public ReponseSealConfig reponseSealConfig=new ReponseSealConfig();
    public String mainsignfieldname="htzwdzyyj";
    public String detailtable = "";
    public String detailid = "";
    public Map<String,Object> detailmap=new HashMap<>();
    public String detailtypefieldname = "yyzt";
    public String desealdocfieldname = "yyhwj";
    public String desealdocnum="1,3";
    public String detailyyid="yyid";
    public String detailelectronicfield="dzyyfs";
    public String detail="1,3";
    public MessageDetailLog messageDetailLog = null;

    public EsealPesUtil() {

    }
    public EsealPesUtil(String value) {
        tablename = value;
        messageDetailLog = new MessageDetailLog(value);
    }

    /**
     * <p>拒签。将数据库明细表的值修改</p>
     * @title refuseSet
     * @author K1810015
     * @updateTime 2022/9/13 13:49
     */
    public void refuseSet(String tablename, String request, String value) {
        messageDetailLog.writLogsnotretrun(request, value, "2", messageDetailLog.refuse);
        new ManualworkflowAction().callbackflow(value, "5");
    }

    /**
     * <p>水印.不做任何处理。只写入日志</p>
     * @title watermarkSet
     * @author K1810015
     * @updateTime 2022/9/13 13:49
     */
    public void watermarkSet(String tablename, String request, String value) {
        messageDetailLog.writLogsnotretrun(request, value, "2", messageDetailLog.watermark);
    }

    /**
     * <p>水印失败，则失败</p>
     * @title watermarkfail
     * @author K1810015
     * @updateTime 2022/9/13 13:48
     */
    public void watermarkfail(String tablename, String request, String value, String docid) {
        messageDetailLog.writLogsnotretrun(request, value, "2", messageDetailLog.fail);
        new ManualworkflowAction().callbackflow(value, "4");
    }


    public void updateSignStatus(String yyzt, String yyhwj) {

        if (StringUtils.isBlank(detailtable) || StringUtils.isBlank(yyzt)) {
            return;
        }
        Map<String, String> wheremap = new HashMap<>(1);
        wheremap.put("id", this.detailid);
        Map<String, String> setmap = new HashMap<>(2);
        setmap.put(detailtypefieldname, yyzt);
        setmap.put(desealdocfieldname, yyhwj);
        JAVATools.Updatesql(setmap, this.detailtable, wheremap);
    }

    public void updateMainTable(String newDzyyj){
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        List<String> dzyyjList = new ArrayList<>();
        String mainid = "";
        String dzyyj = "";
        String sql = "select id from "+this.tablename+" where id = '"+id+"'";
        bs.writeLog(sql);
        rs.executeQuery(sql);
        if(rs.next()){
            mainid = Util.null2String(rs.getString("id"));
        }

           String detailsql = "select wm_concat_old("+desealdocfieldname+") as "+desealdocfieldname+" from "+detailtable+" where mainid = '"+id+"' and yyzt=3";
            bs.writeLog(detailsql);
            rs.executeQuery(detailsql);
            if(rs.next()){
                String yyhwj = Util.null2String(rs.getString(desealdocfieldname));
                if(StringUtils.isNotEmpty(yyhwj)){
                    dzyyjList.addAll(Arrays.stream(yyhwj.split(",")).collect(Collectors.toList()));
                }
            }

        dzyyj = dzyyjList.stream().collect(Collectors.joining(","));
        bs.writeLog(mainsignfieldname+":"+dzyyj);
        String updateSql = "update "+tablename+" set  "+mainsignfieldname+"= '"+dzyyj+"' where id = '"+id+"'";
        bs.writeLog(updateSql);
        rs.executeUpdate(updateSql);
    }

    public String getDzyyfs(String docidStr){
        RecordSet rs = new RecordSet();

        String dzyyfs = "";
        String sql = "select "+detailelectronicfield+" from "+detailtable+" where "+detailyyid+" = '"+docidStr+"'";
        rs.executeQuery(sql);
        if(rs.next()){
            dzyyfs =  Util.null2String(rs.getString("dzyyfs"));
        }
        return dzyyfs;
    }

    public String getfiledocid(String fileid,String docidStr){
        RecordSet rs = new RecordSet();

        String docid = "";
        String sql = "select "+fileid+" from "+detailtable+" where "+detailyyid+" = '"+docidStr+"'";
        rs.executeQuery(sql);
        if(rs.next()){
            docid =  Util.null2String(rs.getString(fileid));
        }
        return docid;
    }

    public void getdetailid(String newDzyyj){
        DbTools dbTools=new DbTools();
        Arrays.stream(desealdocnum.split(",")).forEach((item)->{
            String detailsql = "select * from "+tablename+"_dt"+item+" where "+detailyyid+" = '"+newDzyyj+"'";
            Map<String,Object> dtmap= dbTools.getsqltomap(detailsql,null);
            if(dtmap!=null && dtmap.size()>0){
                String id = Util.null2String(dtmap.get("id"));
                if(!StringUtils.isBlank(id)){
                    this.detailid=id;
                    this.detailtable=tablename+"_dt"+item;
                    this.detailmap=dtmap;
                }
            }
        });

    }

    public String getSignCode(String id,String tablename){
        if(com.engine.integration.util.StringUtils.isBlank(id) || com.engine.integration.util.StringUtils.isBlank(tablename)){
            return "";
        }
        RecordSet rs = new RecordSet();
        String yzbhvalue="";
        rs.execute("select wm_concat_old(yzbh) as yzbh from "+tablename+" where id in ("+id+")");
        if (rs.getArray().size()<=0) {
            return "";
        }
        while(rs.next()){
            yzbhvalue=Util.null2String(rs.getString("yzbh")) ;
        }
        return yzbhvalue;
    }


    public void updatiltable(Map<String, String> setmap) {
        if (StringUtils.isBlank(detailtable) || StringUtils.isBlank(detailid)) {
            return;
        }
        Map<String, String> wheremap = new HashMap<>(1);
        wheremap.put("id", this.detailid);
        JAVATools.Updatesql(setmap, this.detailtable, wheremap);
    }

    /**
     * <p>获取dpf文件</p>
     * @title getesealpdffileid
     * @author K1810015
     * @updateTime 2022/9/13 13:48
     */
    public String getEsealPdfFileid(JSONObject docSignObject){
        StringBuilder fileId = new StringBuilder();
        JSONArray signedFileArray = docSignObject.getJSONArray("signedFile");
        for (int j = 0; j < signedFileArray.size(); j++) {
            JSONObject signedObject = signedFileArray.getJSONObject(j);
            fileId.append(signedObject.getString("fileId"));
        }
        return fileId.toString();
    }

    public String getEsealRxfFieldid(JSONObject docSignObject){
        StringBuilder fileId = new StringBuilder();
        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.append(signedObject.getString("rxfFilePath"));

            }
        }
        return  fileId.toString();
    }


    /**
     * <p>保存用印后文件</p>
     * @title savefileid
     * @author K1810015
     * @updateTime 2022/8/3 11:32
     * @throws
     */
    public int saveFileid(JSONObject docSignObject,
                           EsealTypeEnum esealTypeenum){
        int newdocid =-1;
        String docidStr = docSignObject.get("docId").toString();
        String fileNamedisplay=docSignObject.get("fileNameDisplay").toString();
        String oldFileNamedisplay=docSignObject.get("fileNameDisplay").toString();
        String fileId="";
        List<DateTime> list=new ArrayList<>();
        switch (esealTypeenum) {

            case Opponent:
                fileId=getEsealPdfFileid(docSignObject);
                break;
            case ESecurity:{
                //只是判断可不可保存，不一定返回的是pdf文件
                if(reponseSealConfig.securityautopdf){
                    fileId=getEsealPdfFileid(docSignObject);
                }
                if(StringUtils.isBlank(fileId)){
                    fileId=getEsealRxfFieldid(docSignObject);
                    if(fileNamedisplay.split("\\.").length>1){
                        fileNamedisplay=fileNamedisplay.substring(0,fileNamedisplay.lastIndexOf("."))+".RXF";
                    }

                }
                break;
            }
            case Electronics: {
                fileId=getEsealPdfFileid(docSignObject);
                break;
            }
            case Online:{
                fileId=getEsealPdfFileid(docSignObject);
                break;
            }
            default:
                break;
        }
        CustomizeLog.printLog("docId:"+this.detailid+"fileId:"+fileId.toString());
        if(StringUtils.isBlank(fileId)){
            CustomizeLog.printLog("newdocid没有获取到:"+this.detailid);
            return newdocid;
        }
        int olddocid= Util.getIntValue(Util.null2String(getfiledocid("wjmc",docidStr)),-1);
        newdocid= Util.getIntValue(GatewayUtil.getWayToDocId(fileId,fileNamedisplay,olddocid),-1);
        return newdocid;

    }


}


