package com.engine.htsc.smsd.dao;

import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.htsc.smsd.util.AddDataUtil;
import com.greenpineyu.fel.function.operator.Add;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.Util;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class AddByLcbhCMD extends AbstractCommonCommand<Map<String, Object>> {
    Logger logger = LoggerFactory.getLogger(AddByLcbhCMD.class);

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    public AddByLcbhCMD(Map<String, Object> params) {
        this.params = params;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        logger.info("===========进入Dao层AddByLcbhCMD方法===================");
        Map<String, Object> result = new HashMap<>();
        final String[] mainFields = {"lcbh", "hjxxjezfmx", "ngr", "szbm", "lclx"};
        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        String sql;
        String lcbh = Util.null2String(params.get("lcbh")).replaceAll(" ","");
        logger.info("=============获取到的流程编号是：" + lcbh);
        // 1、确认此付款流程编号是否在预付款台账报表中已经存在数据
        sql = "select count(*) as counts from uf_PrepayMageAccRep where fklcbh = '" + lcbh + "'";
        rs.executeQuery(sql);
        if (rs.next()) {
            if ("0".equals(Util.null2String(rs.getString("counts")))) {
                // 2、付款流程数据搜集准备插入预付款台账表
                // 2.1、获取流程编号对应的主表名
                String mainTableName = AddDataUtil.getMaintableName("lcbh", lcbh);
                if ("".equals(mainTableName)) {
                    result.put("isSuccess", "false");
                    result.put("message", "流程编号不存在，请重新输入");
                } else {
                    // 3、确认流程是否已办结
                    String lcbjsj = AddDataUtil.isFinished(lcbh, mainTableName);
                    if (!"".equals(lcbjsj)) {
                        // 4、获取需要插入台账的数据    "lcbh","hjxxjezfmx","ngr","szbm"
                        Map<String, Object> mainInfo = AddDataUtil.getMainInfo(mainFields, lcbh, mainTableName);
                        // 流程编号-lcbh
                        String jbr = Util.null2String(mainInfo.get("ngr"));
                        String jbbm = Util.null2String(mainInfo.get("szbm"));
                        String lclx = Util.null2String(mainInfo.get("lclx"));
                        String lczbm = Util.null2String(getLczbmByLcbh(lcbh));

                        String htbh = AddDataUtil.getDtFieldValue("HTBH", "4", lcbh, mainTableName);
                        String skf = AddDataUtil.getDtFieldValue("skdw", "11", lcbh, mainTableName);
                        String fyqrlcbh = "";
                        String kpf = "";
                        String yfkje = "".equals(Util.null2String(mainInfo.get("hjxxjezfmx"))) ? "0.00" : Util.null2String(mainInfo.get("hjxxjezfmx"));
                        String yhxje = "0.00";
                        // 因为已核销金额默认为0，所以待核销金额默认为已付款金额
                        String dhxje = yfkje;
                        // 0是1否
                        String sfyq = "".equals(AddDataUtil.getSfyq(lcbjsj)) ? "1" : "0";
                        String yqts = "".equals(AddDataUtil.getSfyq(lcbjsj)) ? "0" : AddDataUtil.getSfyq(lcbjsj);
                        // 流程requetsId
                        String requestId = AddDataUtil.getRequestIdByLcbh(lcbh, mainTableName);
                        // 付款状态，默认为1，待付款
                        String fkzt = "1";
                        // 建模权限所需字段
                        String formmodeid = "";
                        String modedatacreater = "1";
                        String modedatacreatertype = "0";
                        String modeuuid = UUID.randomUUID().toString();
                        rs.execute("select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = 'uf_PrepayMageAccRep'");
                        if (rs.next()) {
                            formmodeid = Util.null2String(rs.getString("id"));
                        }
                        try {
                            rst.setAutoCommit(false);
                            String insertSql = "insert into uf_PrepayMageAccRep(REQUTID,fklcbh,jbr,jbbm,lcbjsj,htbh,skf,fyqrlcbh," +
                                    "kpf,yfkje,yhxje,dhxje,sfyq,yqts,formmodeid,modedatacreater,modedatacreatertype,modeuuid,FKZT,LCLX,LCZBM) " +
                                    "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                            writeLog("即将执行的insert sql 是：insert into uf_PrepayMageAccRep(REQUTID,fklcbh,jbr,jbbm,lcbjsj,htbh,skf,fyqrlcbh," +
                                    "kpf,yfkje,yhxje,dhxje,sfyq,yqts,formmodeid,modedatacreater,modedatacreatertype,modeuuid) " +
                                    "VALUES ('" + requestId + "','" + lcbh + "','" + jbr + "','" + jbbm + "','" + lcbjsj + "','" + htbh + "','" + skf + "','" + fyqrlcbh + "','" + kpf + "','" + yfkje + "','" + yhxje + "','" + dhxje + "','" + sfyq + "','" + yqts + "','" + formmodeid + "','" + modedatacreater + "','" + modedatacreatertype + "','" + modeuuid + "')");
                            rst.executeUpdate(insertSql, requestId, lcbh, jbr, jbbm, lcbjsj, htbh, skf, fyqrlcbh,
                                    kpf, yfkje, yhxje, dhxje, sfyq, yqts, formmodeid, modedatacreater, modedatacreatertype, modeuuid, fkzt, lclx, lczbm);
                            rst.commit();
                            // 权限重构
                            int dataId = AddDataUtil.getDataIdByUUID(modeuuid, "uf_PrepayMageAccRep");
                            ModeRightInfo modeRightInfo = new ModeRightInfo();
                            modeRightInfo.editModeDataShare(1, Integer.parseInt(formmodeid), dataId);
                            result.put("isSuccess", "true");
                            result.put("message", "新增成功");
                        } catch (Exception e) {
                            e.getMessage();
                            writeLog("============新增过程发生错误：" + e.getMessage());
                            result.put("isSuccess", "false");
                            result.put("message", "新增失败，更新过程发生错误，请联系管理员");
                        }
                    } else {
                        result.put("isSuccess", "false");
                        result.put("message", "流程未办结，暂不能发起新增，请重新输入");
                    }
                }
            } else {
                result.put("isSuccess", "false");
                result.put("message", "付款流程信息已存在");
            }
        } else {
            result.put("isSuccess", "false");
            result.put("message", "付款流程重复性检验发生错误，请联系管理员处理");
        }
        return result;
    }


    private String getLczbmByLcbh(String lcbh) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.tablename from workflow_bill t1,workflow_base t2,workflow_requestbase t3  where t1.id =t2.formid and t2.id = t3.workflowid and t3.REQUESTMARK = ?";
        rs.executeQuery(sql,lcbh);
        if (rs.next()){
            return Util.null2String(rs.getString("tablename"));
        }else {
            return "";
        }
    }
}
