package weaver.interfaces.htsc.payment.common;

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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;
import java.util.stream.Collectors;

public class LangChaoSendByMode extends BaseCronJob {
    private Log log = LogFactory.getLog(this.getClass());
    private static final PaymentLogger logger = PaymentLoggerFactory.getLogger(LangChaoSendByMode.class);
    private final HTUtil htUtil = new HTUtil();
    @Override
    public void execute() {
        RecordSet rs = new RecordSet();
        RecordSet rsUp = new RecordSet();
        log.info("======定时任务定时获取uf_SyncWavApproForm建模表数据同步浪潮审批单======");

           logger.info("======uf_SyncWavApproForm建模表数据同步浪潮审批单开始======");
            //先同步PDF
           String sql = "SELECT id,REQUESTID,TABLENAME,WORKFLOWID FROM uf_SyncWavApproForm " +
                   "WHERE SFYTB = 1 AND tblx = 'PROCESS_PDF' AND trunc ( to_date ( BJSJ , 'yyyy-MM-dd HH24:mi:ss') ) <= trunc ( sysdate - 1 )";
           rs.execute(sql);
           while (rs.next()){
               try {
                   int id = Util.getIntValue(rs.getString("id"));
                   String requestid = Util.null2String(rs.getString("REQUESTID"));
                   String tableName = Util.null2String(rs.getString("TABLENAME"));
                   int workflowid = Util.getIntValue(rs.getString("WORKFLOWID"));
                   String sqlPdf = "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(sqlPdf, requestid);
                   Map<String, String> pdfParams = copy(paramsProtoType);
                   pdfParams.put("requestid", requestid);
                   pdfParams.put("modeid", printModeId(workflowid));
                   //sendPDF
                   sendPDF(pdfParams);
                   //更新建模表字段
                   String sqlUpdate = "UPDATE uf_SyncWavApproForm SET SFYTB = 0 WHERE id = "+id;
                   rsUp.executeUpdate(sqlUpdate);
               }catch(Exception e) {
                   e.printStackTrace();
                   new BaseBean().writeLog("定时任务定时获取uf_SyncWavApproForm建模表数据同步浪潮审批单 失败"+e.getStackTrace());
               }
           }


            //同步附件
            String sqlFj = "SELECT id,REQUESTID,TABLENAME,WORKFLOWID FROM uf_SyncWavApproForm " +
                    "WHERE SFYTB = 1 AND tblx = 'PROCESS_AFFIX' AND trunc ( to_date ( BJSJ , 'yyyy-MM-dd HH24:mi:ss') ) <= trunc ( sysdate - 1 )";
            rs.execute(sqlFj);
            while (rs.next()) {
                try {
                    int id = Util.getIntValue(rs.getString("id"));
                    String requestid = Util.null2String(rs.getString("REQUESTID"));
                    String tableName = Util.null2String(rs.getString("TABLENAME"));
                    String sqlPdf = "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(sqlPdf, requestid);
                    Map<String, String> affixParams = copy(paramsProtoType);
                    affixParams.put("appendices", getWorkflowAffixes(tableName, requestid));
                    // sendAffix
                    sendAffix(affixParams);
                    //更新建模表字段
                    String sqlUpdate = "UPDATE uf_SyncWavApproForm SET SFYTB = 0 WHERE id = " + id;
                    rsUp.executeUpdate(sqlUpdate);
                } catch (Exception e) {
                    e.printStackTrace();
                    new BaseBean().writeLog("定时任务定时获取uf_SyncWavApproForm建模表数据同步浪潮审批单 失败" + e.getStackTrace());
                }
            }
    }

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

    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));
        }

    }

    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 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 String getWorkflowAffixes(String tableName, String requestid) throws Exception {
        PropBean pp = new PropBean();
        String budgetTableName = pp.getPropName("attach.selected.flowid");
        List<String> splitWorkNum = Arrays.asList(budgetTableName.split(","));
        String  workNumSql = String.format(" select t2.unnumber from WORKFLOW_REQUESTBASE t1\n" +
                "left join workflow_base t2 on t1.workflowid=t2.id\n" +
                "where t1.requestid = ? ");
        Map<String, String> workUnNumber = CommonAPI.querySingleRow(workNumSql, requestid);
        String unnumber = workUnNumber.get("unnumber");
        if(splitWorkNum.contains(unnumber)){
            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(","));
        }else {
            String billid = tableName.substring(tableName.lastIndexOf("_")).replace("_", "-");
            String sql = "select wm_concat_old(FIELDNAME) field from workflow_billfield b where b.fieldhtmltype=6 and b.billid=?";
            String field = CommonAPI.querySingleFieldWithPlaceholder(sql, "field", billid);
            if (AssertUtil.isEmpty(field)) {
                return "";
            }
            String need = "fjsc1,fjsc2,fjsc3,fj1";
            List<String> ready = new ArrayList<>();
            String[] split = field.split(",");
            List<String> needDel = Arrays.asList(need.split(","));
            for (String s : split) {
                if (!needDel.contains(s)) {
                    ready.add(s);
                }
            }
            field = String.join(",",ready);
            sql = String.format("select %s from %s where requestid = ?", field, tableName);
            Map<String, String> fjResult = CommonAPI
                    .querySingleRow(sql, requestid);
            //附件数据汇总
            return fjResult.values().stream()
                    .filter(AssertUtil::isNotEmpty)
                    .collect(Collectors.joining(","));
        }
    }
}
