package com.engine.htxc.eseal.uinterface;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
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.commonutil.user.UserHt;
import com.engine.htxc.eseal.config.EsealConfig;
import static com.engine.htxc.eseal.type.EffectType.*;
import static com.engine.htxc.eseal.type.Esealresult.ERROR;
import static com.engine.htxc.eseal.type.Esealresult.SUCCESS;

import com.engine.htxc.eseal.dao.EsealTableLinkDao;
import com.engine.integration.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
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.wps.doccenter.convert.DocTypeConvert;
import weaver.wps.doccenter.utils.Tools;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>提供用印流程所需要的通用子方法。需要用印的流程继承该类</p>
 * @author K1810015
 * @version 1.0.0
 * @ClassName EsealInit.java
 * @createTime 2022年06月20日 15:09:00
 */
public class EsealInit extends Service {



    public User user;

    public String id;

    public String fileid = "id";

    public String docids = "";
    public String tablename;
    public int detailnum;
    public String detailname="";
    public String responsevalue = "";

    public Map<String, Object> maintable;

    public List<Map<String, Object>> deteillist;

    public EsealConfig esealConfig;

    public String url;

    public PropBean pb = new PropBean();

    public JSONObject retjsonobject = new JSONObject();

    public String requestvalue = "";

    public Boolean flag=false;

    public boolean autopdf=false;

    public String autopdfname="";

    public void init(Map<String, Object> map, User user) {
        id = Util.null2String(map.get("id"));
        detailnum = Util.getIntValue(Util.null2String(map.get("detailnum")), -1);
        tablename = Util.null2String(map.get("tablename"));
        detailname=tablename+"_dt"+detailnum;
        String docid = Util.null2String(map.get("docid"));
        if ("".equals(id) || detailnum <= 0 || user == null) {
            return;
        }
        docids=docid;
        if (esealConfig == null) {
            esealConfig = new EsealConfig();
        }
        esealConfig.linktalbeenum=tablename;
        esealConfig.operator = new UserHt(user.getUID());
        this.user = user;
        if (StringUtils.isBlank(tablename)) {
            String tablenamevalue = JAVATools.getMaintable(id);
            this.tablename = tablenamevalue;
            this.fileid = "requestid";
        }
        if (StringUtils.isBlank(tablename)) {
            return;
        }
        String sql = "select * from " + tablename + " where 1=1";
        Map<String, String> mainmap = new HashMap<>(1);
        mainmap.put(fileid, id);
        maintable = JAVATools.GetTableToMap(sql, mainmap);
        String detailsql = "select detail.* from " + tablename + "_dt" + detailnum + " detail left join " + tablename + " dt on dt.id=detail.mainid where dt." + fileid + "='" + id + "' ";
        if (!StringUtils.isBlank(docid)) {
            detailsql += "and detail.wjmc in (" + Arrays.stream(docid.split(",")).map(item -> "'" + item + "'").collect(Collectors.joining(",")) + ")";
        }
        deteillist = JAVATools.GetTableToListMap(detailsql, null);
    }

    /**
     * @throws
     * @title 封装默认的数据
     * @author K1810015
     * @updateTime 2022/6/21 17:42
     * @Remark
     */
    public JSONObject dataload() {

        if (maintable == null || maintable.size() <= 0 ||
                deteillist == null || deteillist.size() <= 0) {
            return null;
        }
        if (esealConfig == null) {
            esealConfig = new EsealConfig();
        }
        String doctype = pb.getPropName("eseal.contract.doctype");
        esealConfig.docType = doctype;
        Map mainmap = new HashMap(1);
        esealConfig.map.forEach((key, value) -> {
            mainmap.put(key, this.maintable.get(Util.null2String(value)));
        });

         String flownum=Util.null2String(mainmap.get("flowNum"));
        if(!StringUtils.isBlank(flownum)){
            EsealTableLinkDao esealTableLinkDao=new EsealTableLinkDao();
            Map<String,Object> esealinkmap=new HashMap<>(1);
            esealinkmap.put("flownum",flownum);
            esealTableLinkDao.insertlink(esealinkmap,esealConfig);

        }
        List detaillistnew = new ArrayList();
        this.deteillist.forEach((Map<String, Object> detailmap) -> {
            Map<String, Object> detailmapnew = new HashMap<>(5);

            String id = Util.null2String(detailmap.get("id"));
            String wjmc = Util.null2String(detailmap.get("wjmc"));
            String dzyyfs = Util.null2String(detailmap.get("dzyyfs"));
            int dsmdy = Util.getIntValue(Util.null2String(detailmap.get("dsmdy")), -1);

            if ("0".equals(dzyyfs) || "1".equals(dzyyfs) || "2".equals(dzyyfs) || "3".equals(dzyyfs)) {
                //获取文件名称的信息
                Map<String, Object> filemap = getfilemap(wjmc);
                if (filemap != null) {
                    detailmapnew.put("uniqueKey", filemap.get("fileid"));
                    detailmapnew.put("fileNameDisplay", filemap.get("imagefilename"));
                    String docid= filemap.get("imagefileid")+ DateUtil.format(DateTime.now(),"yyyyMMddHHmmss");
                    updateyyid(id,docid);
                    detailmapnew.put("docId",docid);
                    if ("0".equals(dzyyfs)) {
                        esealConfig.effectType=ELECTRONIC;
                    } else if ("1".equals(dzyyfs)) {
                        if (dsmdy > 0 && esealConfig.acrossSealSkipPage.size() - 1 >= dsmdy) {
                            detailmapnew.put("acrossSealSkipPage", Util.null2String(esealConfig.acrossSealSkipPage.get(dsmdy)));
                        }
                        esealConfig.effectType=PAPER;
                        String yqxdyr = Util.null2String(detailmap.get("yqxdyr"));
                        String fwdyfs = Util.null2String(detailmap.get("fwdyfs"));
                        detailmapnew.put("printNum", fwdyfs);
                        detailmapnew.put("printuser", yqxdyr);
                    }else if("2".equals(dzyyfs)){
                        esealConfig.effectType=NOWATERMARK;
                    }else if("3".equals(dzyyfs)){
                        esealConfig.effectType=ELECTRONIC;
                        esealConfig.esealtype="online";
                        esealConfig.counterpartyids=Util.null2String(this.maintable.get("htdsf"));
                    }
                    detailmapnew.put("effectType", esealConfig.effectType);
                    detaillistnew.add(detailmapnew);
                }

            }

        });
        Map<String, Object> map = esealConfig.signUsermap().flowOwnermapmap().docSigns(detaillistnew).map;
        map.put("appId", pb.getPropName("eseal.contract.appid"));
        map.put("secret", pb.getPropName("eseal.contract.secret"));
        if (mainmap != null && mainmap.size() > 0) {
            mainmap.forEach((key, value) -> {
                map.put(Util.null2String(key), Util.null2String(value));
            });
        }
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject;
    }


    public void sendpost(String body) {
        CustomizeLog.printLog(body);

        String response = "";

        try {
            PropBean pb = new PropBean();
            if (StringUtils.isBlank(url)) {
                url=Util.null2String(pb.getPropName("eseal.url"));
            }
            CustomizeLog.printLog(url);
            requestvalue=body;
            response = new HTUtil().httpPostRaw(url, body, null, null);
            flag=true;
        } catch (Exception e) {

        }

        responsevalue = response;
    }

    public void callbacktble(String tablename,String fileidvalue,String where) {
        flag=false;
        if(StringUtils.isBlank(tablename) || StringUtils.isBlank(fileidvalue) || StringUtils.isBlank(where)){
            return;
        }
        MessageDetailLog messageDetailLog=new MessageDetailLog("uf_htqc");
        try{
        if (StringUtils.isBlank(responsevalue)) {
            retjsonobject.put("status", "500");
            retjsonobject.put("error", "手动签章接口返回结果为空");
            return ;
        }
        JSONObject res = JSONObject.parseObject(responsevalue);
            //标识200-成功,否则失败
        String msg = Util.null2String(res.get("msg"));
        Map<String,String> wheremap=new HashMap<>(1);
        wheremap.put("id",id);
        String updateSql = "update "+this.tablename+"_dt"+this.detailnum+" set yyzt = ''{0}'',qrdzyy = ''{1}''";
        if (!"success".equals(msg)) {
            retjsonobject.put("status", "500");
            retjsonobject.put("error", "送e-seal用印失败");
            updateSql= MessageFormat.format(updateSql,ERROR.getValue(),"0");
            updateSql=updateSql+where;
            String reqvalue=requestvalue;

            messageDetailLog.writeinseertLogs(id, reqvalue, "1", messageDetailLog.fail, messageDetailLog.success, responsevalue);
            updatestatus(updateSql);
            flag=false;
            return ;
        }
            updateSql= MessageFormat.format(updateSql,SUCCESS.getValue(),"1");
            updateSql=updateSql+where;
            updatestatus(updateSql);
            messageDetailLog.writeinseertLogs(id,requestvalue, "1", messageDetailLog.success, messageDetailLog.success, responsevalue);
            flag=true;
        }
        catch(Exception e)
        {
            e.printStackTrace();
            retjsonobject.put("status", "500");
            retjsonobject.put("error", "送e-seal用印失败");
        }
}

    public Boolean updatestatus(String sql){
        if(StringUtils.isBlank(sql) || sql.indexOf("where")<0){
            return false;
        }
       RecordSet rs=new RecordSet();
       Boolean flag= rs.execute(sql);
       return flag;
    }



    /**
     * @title 明细表修改状态
     * @author K1810015 
     * @updateTime 2022/6/21 15:18 
     * @Remark 
     * @throws 
     */
    public void updatestatus(Map<String,String> setmap,String detailid){

       CustomizeLog.printLog("detailid："+detailid+"setmap"+setmap);
       if(setmap==null || setmap.size()<=0 ){
           CustomizeLog.printLog("参数为空");
       }
       Map<String,String> wheremap=new HashMap<>(1);
       if(StringUtils.isBlank(detailid)){
           wheremap.put("mainid",this.id);
       }else{
           wheremap.put("id",detailid);
       }
       JAVATools.Updatesql(setmap,this.tablename+"_dt"+this.detailnum,wheremap);
    }


    public Map<String,Object> getfilemap(String wjmc){
        String sql =" select t.maincategory,t.docsubject,t.seccategory,t.docextendname,l.imagefilename,t.doctype,p.filesize, " +
                " l.docfiletype,p.iszip,p.fileid,p.imagefiletype,p.imagefileid,p.filerealpath,t.doccreaterid " +
                " from docdetail t " +
                " inner join docimagefile l on l.docid = t.id " +
                " inner join imagefile p on p.imagefileid = l.imagefileid " +
                " where docid=? and versionid IN(select max(versionid) from DocImageFile where docid=? ) ";
        Map<String, Object> map= new DbTools().getsqltomap(sql,wjmc,wjmc);
        if(map==null || map.size()<=0){
            return null;
        }
        int newimagefileid=0;
        int imagefileid=Util.getIntValue(Util.null2String(map.get("imagefileid")),-1);
        if(autopdf &&!StringUtils.isBlank(autopdfname)){
            Map<String,Object> autofileidmap =getautopdf(Util.null2String(imagefileid));
            if(autofileidmap!=null && autofileidmap.size()>0){
                Map<String,Object> retmap=new HashMap<>(3);
                retmap.put("fileid",autofileidmap.get("fileid"));
                retmap.put("imagefilename",autofileidmap.get("name"));
                retmap.put("imagefileid",newimagefileid);
                CustomizeLog.printLog(retmap.toString());
                return retmap;
            }
        }
        String docsubject=Util.null2String(map.get("docsubject"));
        String imagefilename=Util.null2String(map.get("imagefilename"));
        String fileid=Util.null2String(map.get("fileid"));
        if(StringUtils.isBlank(imagefilename) ||StringUtils.isBlank(docsubject) || imagefilename.split("\\.").length<=1 ){
            return null;
        }
        String doctype=imagefilename.split("\\.")[imagefilename.split("\\.").length-1];
        if("pdf".equals(doctype.toLowerCase())){
            if(StringUtils.isBlank(fileid)){
                fileid=GatewayUtil.sendGateway(imagefileid,docsubject+".pdf");
            }
        }else{
            JSONArray jsonArray=new JSONArray();
            CustomizeLog.printLog("imagefileid:"+imagefileid+"docsubject"+docsubject);
            Map<String,String>  pdfmap = new HashMap(5);
            String oldImagefilenamepdf = (!Tools.isEmptyOrNull(imagefilename) && imagefilename.contains(".") ? imagefilename.substring(0, imagefilename.lastIndexOf(".")) : imagefilename) + ".pdf";
            pdfmap.put("imagefileid", imagefileid + "");
            pdfmap.put("fromMould","ecology");
            pdfmap.put("fileName", imagefilename);
            pdfmap.put("targetFileFormat", "PDF");
            pdfmap.put("targetFilename", oldImagefilenamepdf);
            DocTypeConvert convertDocToPdf = new DocTypeConvert(this.user);
            newimagefileid= convertDocToPdf.convertDocType(pdfmap);
            if(newimagefileid>0){
              fileid=GatewayUtil.sendGateway(imagefileid,docsubject+".pdf");
              imagefilename=oldImagefilenamepdf;
            }
        }
        Map<String,Object> retmap=new HashMap<>(3);
        retmap.put("fileid",fileid);
        retmap.put("imagefilename",imagefilename);
        retmap.put("imagefileid",newimagefileid);
        CustomizeLog.printLog(retmap.toString());
        return retmap;
    }

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

    private Map<String,Object> getautopdf(String imagefileid){
        Map<String,Object> rmap=new HashMap<>(2);
        String sql="select * from "+ autopdfname+" where 1=1 and imagefileid=?";
        Map<String,Object> retmap=new DbTools().getsqltomap(sql,imagefileid);
        if(retmap==null || retmap.size()<=0){
            return rmap;
        }
        rmap.put("fileid",retmap.get("wgid"));
        rmap.put("name",retmap.get("name"));
        return rmap;
    }


    public void updateyyid(String detailid, String yyid){
        Map<String,String> setmap=new HashMap<>(1);
        setmap.put(this.esealConfig.detailyyid, yyid);
        Map<String,String> wheremap=new HashMap<>(1);
        wheremap.put("id",detailid);
        DbTools dbTools=new DbTools();
        dbTools.updateSql(this.detailname,setmap,wheremap);
    }
}
