package com.engine.htsc.seal.jjhyy.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.htsc.jjhyy.service.impl.JjhyybaseServiceImpl;
import com.engine.htsc.seal.common.SendesealBuilder;
import com.engine.htsc.seal.entity.DocSign;
import com.engine.htsc.seal.entity.ManualSignEntity;
import com.engine.htsc.seal.entity.PrintSetting;
import com.engine.htsc.seal.entity.Signer;
import com.engine.htsc.seal.jjhyy.dao.JjhyyDao;
import com.engine.htsc.seal.jjhyy.service.JjhyySealService;
import org.apache.commons.lang.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.GlobatTools.MessageDetailLog;

import com.engine.htsc.seal.util.*;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author K1810015
 * @version 1.0.0
 * @ClassName JjhyySealService.java
 * @createTime 2022年03月14日 15:42:00
 */
public class JjhyySealServiceImpl extends Service implements JjhyySealService {
    /** 写入log表 */
    private MessageDetailLog messageDetailLog =null;
    /** 日期格式 */
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**  eseal通用方法  */
    private EsealUtil esealUtil=new EsealUtil();

    /** 接口入参地址 */
    @Override
    public String sendjjhyySeal(Map<String, Object> map,User user) {
        if("0".equals(Util.null2String(map.get("sealtype")))){
            /**  证照方法 */
            return sendsealzd(user,map);
        }else{
            /**  文件方法 */
            return  sendsealFile(user,map);
        }

    }

    /**
     * 联合用印申请触发电子签章-证照
     * @param user

     * @return
     */
    public String sendsealzd(User user,Map<String,Object> paramsmap){
        String requestid =Util.null2String(paramsmap.get("requestid"));
        String fzids =Util.null2String(paramsmap.get("docids"));
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        JAVATools.SetCmdwritelog("JjhyySealServiceImpl-sendsealFile:"+requestid+":fzids"+fzids);
        try{
            ManualSignEntity manualSignEntity = esealUtil.initialization(user,requestid);
            String code = "";
            /**统一信用代码- 基金会*/
            code = Util.null2String(pb.getPropName("jjhyy.esealcode"));
            /**骑缝章*/
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));
            String tablename = JAVATools.getMaintable(requestid);
             messageDetailLog = new MessageDetailLog(tablename);
            Map<String,Object> yymparamsap= new HashMap<>(2);
            yymparamsap.put("requestid",requestid);
            yymparamsap.put("tablename",tablename);
            Map<String,Object> yymap= JjhyyDao.getyy(yymparamsap);
            if(yymap==null || yymap.size()<=0){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }
           String mainid = Util.null2String(yymap.get("id"));
           String yz = Util.null2String(yymap.get("yz"));
           String zzyongtu = Util.null2String(yymap.get("zzyongtu"));
            if(StringUtils.isEmpty(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }
            if(StringUtils.isEmpty(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }
            String content = new SimpleDateFormat("yyyy-MM-dd").format(new Date())+" "+zzyongtu;
            List<DocSign> docSignList = new ArrayList<>();
            for(String fzid:fzids.split(",")){
                DocSign docSign = new DocSign();
                Map<String,Object> mainbodyparamsmap=new HashMap<>(3);
                mainbodyparamsmap.put("tablename",tablename);
                mainbodyparamsmap.put("mainid",mainid);
                mainbodyparamsmap.put("fzid",fzid);
                Map<String,Object> mainbodymap= JjhyyDao.getmaintablelist(mainbodyparamsmap);
                if(mainbodymap!=null && mainbodymap.size()>0){
                    String id = Util.null2String(mainbodymap.get("id"));
                    String docid = Util.null2String(mainbodymap.get("wjmc"));
                    int newDocid = esealUtil.getWarterMarkDocid(user,docid,content);
                    bs.writeLog("wartermark newdocid:"+newDocid);
                    if(newDocid==-1){
                        resobject.put("status","500");
                        resobject.put("error","添加证照用途水印失败");

                     return resobject.toJSONString();
                    }
                    String pdfid = esealUtil.getPdfid(String.valueOf(newDocid));
                    if(StringUtils.isEmpty(pdfid)){
                        resobject.put("status","500");
                        resobject.put("error","查询文件结果为null,请检查参数");
                       return resobject.toJSONString();
                    }

                    //文件类型
                    String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));
                    docSign.setDocType(doctype);
                    //签署类型
                    docSign.setSignMethod("ORDER");
                    //签署开始时间-签署结束时间
                    docSign.setValidityStartDate(sdf.format(new Date()));
                    docSign.setValidityEndDate(esealUtil.getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));
                    //签署方信息
                    List<Signer> signerList = new ArrayList<>();
                    String yzcode = esealUtil.getSignCode(yz);
                    if ("".equals(yzcode)) {
                        resobject.put("status","500");
                        resobject.put("error","未找到对应的印章ID");
                        return resobject.toJSONString();
                    }
                    Signer signer = new Signer();
                    signer.setCode(code);
                    signer.setCodeType("USC");
                    signer.setRevokeFlag("false");
                    signer.setSealId(yzcode);
                    signer.setSignNum("1");
                    signer.setOwnerType("INSIDE");
                    signer.setSignatoryType("ENTERPRISE");
                    signer.setKeyWord("华泰证券股份有限公司签章");
                    signer.setSignMethod("TRUSTEESHIP");
                    signer.setSignedExamine("DISABLE");
                    signerList.add(signer);
                    docSign.setSigners(signerList);

                    //文件路径-文件名称
                    Map<String, String> pdfMap = esealUtil.getLatestVersionPDF(requestid, pdfid);
                    if (pdfMap.isEmpty()) {
                        resobject.put("status","500");
                        resobject.put("error","上传挂载正文PDF文件出错");
                        return resobject.toJSONString();
                    }
                    docSign.setFileAttachPatch(pdfMap.get("mountpath"));
                    docSign.setFileNameDisplay(pdfMap.get("imagefilename"));

                    //文件编码
                    String signDocid = id+"_"+docid+"_"+esealUtil.getDatetime();
                    docSign.setDocId(signDocid);
                    Map<String,Object> detailyyidmap=new HashMap<>(3);
                    detailyyidmap.put("tablename",tablename+"_dt8");
                    detailyyidmap.put("signDocid",signDocid);
                    detailyyidmap.put("id",id);
                    JjhyyDao.updateyystatus(detailyyidmap);
                    /**骑缝章是否跳页加盖 */
                    String dsmdy = Util.null2String(mainbodymap.get("dsmdy"));
                    /** 0单面打印 --1双面打印    */
                    if("0".equals(dsmdy)){
                        docSign.setAcrossSealSkipPage("DISABLE");
                    }else if("1".equals(dsmdy)){
                        docSign.setAcrossSealSkipPage("ENABLE");
                    }
                    /**交付类型 */
                    String dzyyfs = Util.null2String(mainbodymap.get("dzyyfs"));
                    /**0电子件--1电子防伪件*/
                    if("0".equals(dzyyfs)){
                        docSign.setEffectType("SINGLEWATERMARK");
                    }else if("1".equals(dzyyfs)){
                        docSign.setEffectType("PAPER");
                        String yqxdyr = Util.null2String(mainbodymap.get("yqxdyr"));
                        Map<String,String> map= esealUtil.getUserMap(yqxdyr,String.valueOf(user.getUID()));
                        if(map!=null&&map.size()>0){
                            //防伪打印信息
                            PrintSetting printSetting = new PrintSetting();
                            String fwdyfs = Util.null2String(mainbodymap.get("fwdyfs"));
                            printSetting.setPersonName(map.get("username"));
                            printSetting.setPersonNum(map.get("usrlogins"));
                            printSetting.setPrintNum(fwdyfs);
                            docSign.setPrintSetting(printSetting);
                        }
                    }else{
                        resobject.put("status","500");
                        resobject.put("error","请选择电子用印方式");
                        return resobject.toJSONString();
                    }
                }
                docSignList.add(docSign);
            }

            manualSignEntity.setDocSigns(docSignList);
            JAVATools.SetCmdwritelog("JjhyySealServiceImpl:"+ JSON.toJSONString(manualSignEntity));

            //触发手动签章
            Map<String,Object> collbackMap=new HashMap<>(4);
            collbackMap.put("tablename",tablename);
            collbackMap.put("mainid",mainid);
            collbackMap.put("fzids",fzids);
            collbackMap.put("requestid",requestid);

           String bodyvalue= SendesealBuilder.getSendeseal(JSONArray.toJSON(manualSignEntity).toString()).sendeseal().responsevalue;
                 //   .callback("",collbackMap);
            collbackMap.put("response",bodyvalue);
            boolean flag= callback(collbackMap);
           if(!flag){
               resobject.put("status","500");
               resobject.put("error","用印失败");
               return resobject.toJSONString();
           }
             }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","处理异常");
            return resobject.toJSONString();
        }

        JAVATools.SetCmdwritelog("JjhyySealServiceImpl end:"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }


    /**
     * @title callback
     * @author K1810015
     * @updateTime 2022/3/21 14:35
     * @Remark 证照用印回调函数
     * @throws
     */
    public boolean callback(Map<String,Object> map){

        String response = Util.null2String(map.get("response"));
        String tablename = Util.null2String(map.get("tablename"));
        String mainid = Util.null2String(map.get("mainid"));
        String fzids = Util.null2String(map.get("fzids"));
        String requestid = Util.null2String(map.get("requestid"));
        JAVATools.SetCmdwritelog("callback查看参数："+"response:"+response+"tablename:"+tablename+"mainid:"+mainid+" fzids:"
        +fzids+" requestid:"+requestid);
        JAVATools.SetCmdwritelog(response);
        if(StringUtils.isEmpty(response)){
            return false;
        }
        JSONObject res = JSONObject.parseObject(response);
        /**标识200-成功,否则失败*/
        String status = Util.null2String(res.get("status"));
        String message = Util.null2String(res.get("message"));

        if(!"200".equals(status)){
            JjhyyDao.updateSignStatusForLicense(tablename+"_dt8",mainid,fzids,"4");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
            return false;
        }
        JjhyyDao.updateSignStatusForLicense(tablename+"_dt8",mainid,fzids,"2");
        messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        return true;
    }


    /**
     * 联合用印申请触发电子签章-文件
     * @param user

     * @return
     */
    public String sendsealFile(User user,Map<String,Object> paramsmap){
        PropBean pb = new PropBean();
        BaseBean bs = new BaseBean();
        RecordSet rs = new RecordSet();
        String requestid=Util.null2String(paramsmap.get("requestid"));
        String docids=Util.null2String(paramsmap.get("docids"));
        HTUtil htUtil = new HTUtil();
        JSONObject resobject=new JSONObject();
        JAVATools.SetCmdwritelog("JjhyySealServiceImpl-sendsealFile:"+requestid+":docids"+docids);
        try{
            ManualSignEntity manualSignEntity = esealUtil.initialization(user,requestid);
            String code = "";
            /** 统一信用代码-联合  */
            code = Util.null2String(pb.getPropName("jjhyy.esealcode"));
            /** 骑缝章 */
            String sealIdqfz = Util.null2String(pb.getPropName("ManualSign.sealIdqfz"));
            String tablename = JAVATools.getMaintable(requestid);
             messageDetailLog = new MessageDetailLog(tablename);
            Map<String,Object> fileyyparamsmap=new HashMap<>();
            fileyyparamsmap.put("requestid",requestid);
            fileyyparamsmap.put("tablename",tablename);
            Map<String,Object> fileyymap= JjhyyDao.getfileyy(fileyyparamsmap);
            if(fileyymap==null|| fileyymap.size()<=0){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }
            String mainid = Util.null2String(fileyymap.get("id"));
            String yz = Util.null2String(fileyymap.get("yz"));
            if(StringUtils.isBlank(mainid)){
                resobject.put("status","500");
                resobject.put("error","查询流程结果为null,请检查参数");
                return resobject.toJSONString();
            }
            if(StringUtils.isBlank(yz)){
                resobject.put("status","500");
                resobject.put("error","请选择印章后提交");
                return resobject.toJSONString();
            }

            List<DocSign> docSignList = new ArrayList<>();
            List<String> docidList = Arrays.asList(docids.split(","));
            for(String docid:docidList){
                DocSign docSign = new DocSign();
                String pdfid = esealUtil.getPdfid(docid);

                if(StringUtils.isBlank(pdfid)){
                    resobject.put("status","500");
                    resobject.put("error","查询文件结果为null,请检查参数");
                    return resobject.toJSONString();
                }else {
                    Map<String,Object> sealfilewjmap=new HashMap<>();
                    sealfilewjmap.put("tablename",tablename+"_dt7");
                    sealfilewjmap.put("pdfid",pdfid);
                    sealfilewjmap.put("mainid",mainid);
                    sealfilewjmap.put("docid",docid);
                    JjhyyDao.sealfilewj(sealfilewjmap);
                }
                //文件类型
                String doctype = Util.null2String(pb.getPropName("ManualSign.doctype"));
                docSign.setDocType(doctype);
                //签署类型
                docSign.setSignMethod("ORDER");
                //签署开始时间-签署结束时间
                docSign.setValidityStartDate(sdf.format(new Date()));
                docSign.setValidityEndDate(esealUtil.getNextYear(sdf.format(new Date()), "yyyy-MM-dd HH:mm:ss", 30));

                //签署方信息
                List<Signer> signerList = new ArrayList<>();
                String yzcode = esealUtil.getSignCode(yz);
                if (StringUtils.isBlank(yzcode)) {
                    resobject.put("status","500");
                    resobject.put("error","未找到对应的印章ID");
                    return resobject.toJSONString();
                }
                Signer signer = new Signer();
                signer.setCode(code);
                signer.setCodeType("USC");
                signer.setRevokeFlag("false");
                signer.setSealId(yzcode);
                signer.setSignNum("1");
                signer.setOwnerType("INSIDE");
                signer.setSignatoryType("ENTERPRISE");
                signer.setKeyWord("华泰证券股份有限公司签章");
                signer.setSignMethod("TRUSTEESHIP");
                signer.setSignedExamine("DISABLE");
                signerList.add(signer);
                docSign.setSigners(signerList);

                //文件路径-文件名称
                Map<String, String> pdfMap = esealUtil.getLatestVersionPDF(requestid, pdfid);
                if (pdfMap.isEmpty()) {
                    resobject.put("status","500");
                    resobject.put("error","上传挂载正文PDF文件出错");
                    return resobject.toJSONString();
                }
                docSign.setFileAttachPatch(pdfMap.get("mountpath"));
                docSign.setFileNameDisplay(pdfMap.get("imagefilename"));


                Map<String,Object> mapfilemainmap=new HashMap<>();
                mapfilemainmap.put("tablename",tablename);
                mapfilemainmap.put("mainid",mainid);
                mapfilemainmap.put("docid",docid);
                Map<String,Object> mapfilemainbody=JjhyyDao.getfilemaintablebody(mapfilemainmap);
                    /** 文件编码  */
                    String id = Util.null2String(mapfilemainbody.get("id"));
                    String signDocid = id+"_"+docid+"_"+esealUtil.getDatetime();
                    docSign.setDocId(signDocid);
                    Map<String,Object> yyidMap=new HashMap<>();
                    yyidMap.put("id",id);
                    yyidMap.put("yyid",signDocid);
                    yyidMap.put("tablename",tablename+"_dt7");
                    JjhyyDao.updateyyidstatus(yyidMap);

                    /** 骑缝章是否跳页加盖 */
                    String dsmdy = Util.null2String(mapfilemainbody.get("dsmdy"));
                    if("0".equals(dsmdy)){//单面打印
                        docSign.setAcrossSealSkipPage("DISABLE");
                    }else if("1".equals(dsmdy)){//双面打印
                        docSign.setAcrossSealSkipPage("ENABLE");
                    }

                    /** 交付类型 */
                    String dzyyfs = Util.null2String(mapfilemainbody.get("dzyyfs"));
                    /** 0电子件  1电子防伪件 */
                    if("0".equals(dzyyfs)){
                        docSign.setEffectType("ELECTRONIC");
                    }else if("1".equals(dzyyfs)){
                        docSign.setEffectType("PAPER");
                        String yqxdyr = Util.null2String(mapfilemainbody.get("yqxdyr"));
                        Map<String,String> map= esealUtil.getUserMap(yqxdyr,String.valueOf(user.getUID()));
                        if(map!=null&&map.size()>0){
                            /** 防伪打印信息 */
                            PrintSetting printSetting = new PrintSetting();
                            String fwdyfs = Util.null2String(mapfilemainbody.get("fwdyfs"));
                            printSetting.setPersonName(map.get("username"));
                            printSetting.setPersonNum(map.get("usrlogins"));
                            printSetting.setPrintNum(fwdyfs);
                            docSign.setPrintSetting(printSetting);
                        }
                    }else{
                        resobject.put("status","500");
                        resobject.put("error","请选择电子用印方式");
                        return resobject.toJSONString();
                    }
                docSignList.add(docSign);
            }
            manualSignEntity.setDocSigns(docSignList);
            bs.writeLog("manualSignEntity:"+JSON.toJSONString(manualSignEntity));
            messageDetailLog.writLogsnotretrun(requestid,JSON.toJSONString(manualSignEntity),"1",messageDetailLog.Other);
            //触发手动签章
            Map<String,Object> collbackMap=new HashMap<>(4);
            collbackMap.put("tablename",tablename);
            collbackMap.put("mainid",mainid);
            collbackMap.put("docids",docids);
            collbackMap.put("requestid",requestid);
           String bodyvalue= SendesealBuilder.getSendeseal(JSONArray.toJSON(manualSignEntity).toString()).sendeseal().responsevalue;
            collbackMap.put("response",bodyvalue);
            boolean flag= sealFileCallback(collbackMap);
            if(!flag){
                resobject.put("status","500");
                resobject.put("error","用印失败");
                return resobject.toJSONString();
            }
              }catch(Exception e){
            e.printStackTrace();
            resobject.put("status","500");
            resobject.put("error","送e-seal用印失败");
            return resobject.toJSONString();
        }

        bs.writeLog("JjhyySealServiceImpl"+requestid);
        resobject.put("status","200");
        resobject.put("data","用印请求发送成功");
        return resobject.toJSONString();
    }

    public boolean sealFileCallback(Map<String,Object> map){
        String response=Util.null2String(map.get("response"));
        String tablename=Util.null2String(map.get("tablename"));
        String requestid=Util.null2String(map.get("requestid"));
        String mainid=Util.null2String(map.get("mainid"));
        String docids=Util.null2String(map.get("docids"));
        JAVATools.SetCmdwritelog("sealFileCallback查看参数："+"response:"+response+"tablename:"+tablename+"mainid:"+mainid+" fzids:"
                +docids+" requestid:"+requestid);
        if(StringUtils.isBlank(response)){
          return false;
        }
        JSONObject res = JSONObject.parseObject(response);
        String status = Util.null2String(res.get("status"));//标识200-成功,否则失败
        String message = Util.null2String(res.get("message"));
        if(!"200".equals(status)){
            esealUtil.updateSignStatus(tablename+"_dt7",mainid,docids,"4");
            messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.fail,messageDetailLog.success,response);
            return false;
        }
        esealUtil.updateSignStatus(tablename+"_dt7",mainid,docids,"2");
        messageDetailLog.writeinseertLogs(requestid,res.toString(),"1",messageDetailLog.success,messageDetailLog.success,response);
        return true;
    }



}
