package weaver.interfaces.workflow.action.javacode;

import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.general.BaseBean;
import weaver.soa.workflow.request.RequestInfo;

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

/**
 * Online custom action interface
 * 分行发文推送合规系统(测试环境)
 */
public class Action20231008023243 extends BaseBean implements Action{
    /**
     * After selecting aciton after the process path node, this method will be executed after the node is submitted.
     */
    @Override
    public String execute(RequestInfo request) {

        try {
            String insertsql = "INSERT INTO uf_tohgLog(REQUEST, CONTENT, ZT, ML, DDSJ, TSSJ, FJML, ZWID, FJID) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )";
            DepartmentComInfo departmentComInfo = new DepartmentComInfo();
            //公文标题
            String requestname = request.getRequestManager().getRequestname();
            String requestId = request.getRequestid();
            //  4：获取表单名称
            String tablename = request.getRequestManager().getBillTableName();

            //  5：查找表单内容
            RecordSet rs = new RecordSet();
            rs.execute("select * from " + tablename + " where requestid =  " + requestId);
            rs.next();
            //是否推送合规    0 - 否    1 - 是
            int isTohg = Util.getIntValue(rs.getString("tohg"), 1);
            if (isTohg == 0){
                return Action.SUCCESS;
            }
            //id：表单主键
            String mainid = rs.getString("id");

            //公文编号
            String fwwh = rs.getString("bh");
            //发文部门名称
            String ngbm = rs.getString("ngbm");
            //成文时间
            String cwrq = rs.getString("cwrq");
            String ngr = rs.getString("ngr");
            // String  zw = rs.getString("zw");   //word格式
            //生成的pdf
            String  zw = rs.getString("dwd");
            String  fj = rs.getString("fj");
            User user = new User(Integer.parseInt(ngr));
            //拼接数据
            String subcompanyid = departmentComInfo.getSubcompanyid1(ngbm);
            String departmentNames = departmentComInfo.getAllParentDepartmentBlankNames(ngbm, subcompanyid, "-");
            departmentNames = "天津银行股份有限公司-"+departmentNames;
            String context = "";
            String flag = "|";
            context = requestname + flag + fwwh + flag +departmentNames + flag + cwrq +flag+ user.getLoginid()+flag+user.getLastname()+flag;
            //获取文件命
            Map<String, String> fjName = getIdIMIDName(fj);
            Map<String, String> zwName = getIdIMIDName(zw);
            String fjStr = "";
            String zwStr = "";
            //附件
            ArrayList<String> fileNameList = new ArrayList<>();
            Set<Map.Entry<String, String>> entries = fjName.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String filename = entry.getValue();
                if (fileNameList.contains(filename)){
                    String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : "";
                    if(tepName!=null&&!"".equals(tepName)){
                        String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : "";
                        filename = tepName + "_"+entry.getKey()+"."+extNameTemp;

                    }
                }else {
                    fileNameList.add(filename);
                }
                fjStr = fjStr + "&&"+ filename;
            }
            if (fjStr.startsWith("&&")){
                fjStr = fjStr.substring(2);
            }
            fileNameList.clear();
            //正文
            Set<Map.Entry<String, String>> zwEntries = zwName.entrySet();
            for (Map.Entry<String, String> entry : zwEntries) {
                String filename = entry.getValue();
                if (fileNameList.contains(filename)){
                    String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : "";
                    if(tepName!=null&&!"".equals(tepName)){
                        String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : "";
                        filename = tepName + "_"+entry.getKey()+"."+extNameTemp;
                    }
                }else {
                    fileNameList.add(filename);
                }
                zwStr = zwStr + "&&" + filename;
            }
            if (zwStr.startsWith("&&")){
                zwStr = zwStr.substring(2);
            }
            context = context+zwStr+flag+fjStr+flag+requestId+flag;
            Date date = new Date();
            String time = new SimpleDateFormat("yyyy-MM-dd hh:mm").format(date);
            rs.executeUpdate(insertsql,requestId,context,0,null,time,null,null,zw,fj);
        } catch (Exception e) {
            writeLog(e.getMessage()+ "||||||异常流程id==="+request.getRequestid());
            e.printStackTrace();
            //不管是否推送成功,都返回成功,不影响流程流转
            return Action.SUCCESS;
        }
        // boolean error = false;
        // if (error) {
        //     request.getRequestManager().setMessageid("90001");
        //     request.getRequestManager().setMessagecontent("System Abnormal Termination Process Submission！");
        // }
        return Action.SUCCESS;
    }

    public static Map<String,String> getIdIMIDName(String ids   ){
        Map<String,String> idimageIDMap = new HashMap<>();
        String sql = "select docid,df.imagefilename filename from docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID in ("+ids+")";
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        while (recordSet.next()){
            String docid = Util.null2String(recordSet.getString("docid"));
            String filename = Util.null2String(recordSet.getString("filename"));
            idimageIDMap.put(docid,filename);
        }
        return idimageIDMap;
    };

}