package weaver.interfaces.htsc.fzjgfjsc;

import com.alibaba.fastjson.JSON;
import com.engine.htsc.meeting.util.Common;
import com.engine.htsc.payment.log.PaymentLogger;
import com.engine.htsc.payment.log.PaymentLoggerFactory;
import com.engine.htsc.payment.util.AssertUtil;
import com.engine.htsc.payment.util.CommonAPI;
import com.engine.htsc.payment.util.PayUtil;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;
import java.util.*;
import java.util.stream.Collectors;

public class fzjgAffix implements Action {

    private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(fzjgAffix.class);
    private final HTUtil htUtil = new HTUtil();


    @Override
    public String execute(RequestInfo requestInfo) {

        try {
            new Thread(() -> {
                try {
                    logger.info("开始延时");
                    Thread.sleep(30 * 1000L);
                    logger.info("延时结束");
                    String requestid = requestInfo.getRequestid();
                    RequestManager rm = requestInfo.getRequestManager();
                    String tableName = rm.getBillTableName();
                    int workflowid = Integer.parseInt(requestInfo.getWorkflowid());
                    //得到流程ID、流程编号、操作者ID
                    String sql = "select t1.workflowid,t3.lcbh as requestmark ,t2.workcode from workflow_requestbase t1\n" +
                            "left join hrmresource t2 " +
                            "on t1.creater = t2.id " +
                            "left join " + tableName + " t3 " +
                            "on t1.requestid = t3.requestid " +
                            "where t1.requestid =?";
                    Map<String, String> paramsProtoType = CommonAPI.querySingleRow(sql, requestid);

                    Map<String, String> pdfParams = copy(paramsProtoType);
                    pdfParams.put("requestid", requestid);
                    pdfParams.put("modeid", printModeId(workflowid));
                    //sendPDF
                    sendPDF(pdfParams);

                    Map<String, String> affixParams = copy(paramsProtoType);
                    //上传的附件fileID
                    affixParams.put("appendices", getWorkflowAffixes(tableName, requestid));
                    // sendAffix
                    sendAffix(affixParams);
                } catch (Exception e) {
                    logger.error(String.format("网报流程办结后写入PDF出错 requestid: %s", requestInfo.getRequestid()), e);
                }
            }).start();
            return SUCCESS;
        } catch (Exception e) {
            logger.error(e);
            return SUCCESS;
        }
    }

    //附件功能
    private void sendAffix(Map<String, String> params) throws Exception {
        logger.info("开始同步附件 params" + JSON.toJSONString(params));
        //流程编号
        AssertUtil.isEmpty(params.get("requestmark"), "requestmark为空");
        //操作者工号
        AssertUtil.isEmpty(params.get("workcode"), "workcode为空");
        if (AssertUtil.isEmpty(params.get("appendices"))) {
            logger.info("sendAffix 附件为空");
            return;
        }
        //附件
        Map<String, Object> paras = new HashMap<>();
        paras.put("billid", params.get("requestmark"));
        paras.put("workcode", params.get("workcode"));
        paras.put("fileids", params.get("appendices"));
        logger.info(String.format("sendAffix appendices langChao in: %s", JSON.toJSONString(paras)));
        String langChaoResponse = htUtil.SendImageWithAffix(paras);
        logger.info(String.format("sendAffix appendices langChao out: %s", JSON.toJSONString(langChaoResponse)));
    }

    private Map<String, String> copy(Map<String, String> prototype) {
        return new HashMap<>(prototype);
    }

    private String getWorkflowAffixes(String tableName, String requestid) throws Exception {
        //选择逻辑
        String selectSql = String.format("select xzkzc from %s where requestid = ?", tableName);
        Map<String, String> fjCheckResult = CommonAPI.querySingleRow(selectSql, requestid);
        logger.info("+分支机构+选中的附件ID:" + fjCheckResult.values().stream().filter(AssertUtil::isNotEmpty).collect(Collectors.joining(",")));
        //附件数据汇总
        return fjCheckResult.values().stream().filter(AssertUtil::isNotEmpty).collect(Collectors.joining(","));

    }

    //pdf功能
    private void sendPDF(Map<String, String> params) throws Exception {
        logger.info("开始同步审批单 params" + JSON.toJSONString(params));
        AssertUtil.isEmpty(params.get("requestmark"), "requestmark为空");
        AssertUtil.isEmpty(params.get("workcode"), "workcode为空");
        AssertUtil.isEmpty(params.get("modeid"), "modeid为空");
        AssertUtil.isEmpty(params.get("requestid"), "requestid为空");
        //生成审批单PDF
        String path = Common.saveProcessPDFWithReturnFilePath(params.get("modeid"), params.get("requestid"), params.get("requestmark"));
        //浪潮
        Map<String, Object> paras = new HashMap<>();
        paras.put("billid", params.get("requestmark"));
        paras.put("workcode", params.get("workcode"));
        paras.put("filePath", path);
        logger.info(String.format("sendPDF langChao in: %s", JSON.toJSONString(paras)));
        String langChaoResponse = htUtil.SendImageWithInputStream(paras);
        logger.info(String.format("sendPDF langChao out: %s", JSON.toJSONString(langChaoResponse)));
        logger.info("开始审批单结束");
    }

    private String printModeId(int workflowid) throws Exception {
        String sql = " select t2.unnumber,t1.modeid from workflow_printset t1\n" +
                "    left join workflow_nodebase t2\n" +
                "    on t1.nodeid = t2.id\n" +
                "    where type =1\n" +
                "    and printenable =1\n" +
                "    and t2.nodename = '办结'\n" +
                "    and t1.isactive = 1\n" +
                "    and t1.orderid = 0\n" +
                "    and t2.unnumber = ?";
        try {
            Map<String, String> pa = CommonAPI.querySingleRow(sql,
                    PayUtil.getUnNumberByWorkFlowId(workflowid) + "_bj");
            return pa.get("modeid");
        } catch (Exception e) {
            throw new IllegalArgumentException(String.format("workflowid:%s,没有对应的办结打印模板 ", workflowid));
        }

    }
}
