package weaver.interfaces.htsc.jjhtyfk;

import com.engine.htsc.payment.util.PayUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.util.HT_WorkflowInfo;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author Weaver.SongYuchen
 * @Date 2022-04-01
 * @Description 合同金额反写进用印流程，建立更新日志表
 */
public class UpdateContractAmountAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        writeLog("================================ UpdateContractAmountAction ================================");
        RecordSet rs = new RecordSet();
        String requestId = requestInfo.getRequestid();
        String tableName = requestInfo.getRequestManager().getBillTableName();

        try {
            Map<Object, Object> mainInfo = getMainInfo(requestInfo);
            String yyRequestId = Util.null2String(mainInfo.get("xzht")); //获取主表用印流程请求Id

            writeLog("用印流程requestId：" + yyRequestId);

            HT_WorkflowInfo HT_WorkflowInfo = new HT_WorkflowInfo();
            String formTableName = HT_WorkflowInfo.getFormTableByRequestid(yyRequestId); //根据请求Id获取用印流程表名
            writeLog("用印流程表名: " + formTableName);

            //获取用印流程已付金额
            double yfje = 0.0;
            String sql = "select yfje from " + formTableName + " where requestid = '" + yyRequestId + "'";
            writeLog("sql: " + sql);
            rs.execute(sql);
            if (rs.next()) {
                writeLog("已付金额： " + Util.null2String(rs.getString("yfje")));
                if ("".equals(Util.null2String(rs.getString("yfje")))) { //已付金额为空
                    yfje = 0.0;
                } else {
                    yfje = Double.parseDouble(Util.null2String(rs.getString("yfje")));
                }
            }

            //获取付款流程本次支付金额
            double bcsqje = 0.0;
            writeLog("本次支付金额：" + Util.null2String(getDtData(tableName, requestId, "bqzfje", "4")));
            if ("".equals(Util.null2String(getDtData(tableName, requestId, "bqzfje", "4")))) {
                bcsqje = 0.0;
            } else {
                bcsqje = Double.parseDouble(Util.null2String(getDtData(tableName, requestId, "bqzfje", "4")));
            }

            double updateJe = yfje + bcsqje;
            writeLog("更新至用印流程的金额：" + updateJe);
            //更新用印流程已付金额（已付金额 = 本次支付金额 + old已付金额）
            sql = "update " + formTableName + " set yfje = " + updateJe + " where requestid = '" + yyRequestId + "'";
            writeLog("sql: " + sql);
            if (rs.executeQuery(sql)) {
                //更新成功后继续更新建模表（保存更新日志）
                writeLog("用印流程已付金额更新成功");
                RecordSetTrans rst = new RecordSetTrans();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                LocalDateTime now = LocalDateTime.now();
                String gxsj = now.format(dateTimeFormatter); //更新时间
                String gxje = String.valueOf(bcsqje + yfje); //更新金额
                String formmodeid = "";
                String modedatacreater = "1"; //模块创建人id
                String modedatacreatertype = "0"; //创建人类型
                String modeuuid = UUID.randomUUID().toString();
                try {
                    rs.execute("select k.id from modeinfo k inner join workflow_bill l on formid = l.id where l.tablename = 'uf_tyfkjegxrzb'");
                    if (rs.next()) {
                        formmodeid = Util.null2String(rs.getString("id")); //模块id
                    }
                    rst.setAutoCommit(false);
                    sql = "insert into uf_tyfkjegxrzb(gxje, lcid, gxsj, formmodeid, " +
                            "modedatacreater, modedatacreatertype, modeuuid) values(?, ?, ?, ?, ?, ?, ?)";
                    writeLog("sql: " + sql);
                    rst.executeUpdate(sql, gxje, requestId, gxsj, formmodeid, modedatacreater, modedatacreatertype, modeuuid);
                    rst.commit();
                    int dataId = PayUtil.getDataIdByUUID(modeuuid);
                    ModeRightInfo modeRightInfo = new ModeRightInfo();
                    modeRightInfo.editModeDataShare(1, Integer.parseInt(formmodeid), dataId);
                    writeLog("=====执行成功=====");
                } catch (Exception e) {
                    rst.rollback();
                    writeLog("更新日志表失败");
                    requestInfo.getRequestManager().setMessageid("100");
                    requestInfo.getRequestManager().setMessagecontent("更新日志表失败");
                    return Action.FAILURE_AND_CONTINUE;
                }
            } else {
                writeLog("更新已付金额失败");
                requestInfo.getRequestManager().setMessageid("101");
                requestInfo.getRequestManager().setMessagecontent("更新已付金额失败");
                return Action.FAILURE_AND_CONTINUE;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writeLog("error: " + e.getMessage());
            requestInfo.getRequestManager().setMessageid("102");
            requestInfo.getRequestManager().setMessagecontent("error: " + e.getMessage());
            return Action.FAILURE_AND_CONTINUE;
        }
        return Action.SUCCESS;
    }

    /**
     * 查询主表信息
     *
     * @param requestInfo
     * @return
     */
    public static Map<Object, Object> getMainInfo(RequestInfo requestInfo) {
        Map<Object, Object> map = new HashMap<>();
        Property[] property = requestInfo.getMainTableInfo().getProperty();
        for (int i = 0; i < property.length; i++) {
            map.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
        }
        return map;
    }

    /**
     * 查询明细表某个字段信息
     *
     * @param mainTableName
     * @param requestid
     * @param dtFieldName
     * @param dtTableNum
     * @return
     */
    private static String getDtData(String mainTableName, String requestid, String dtFieldName, String dtTableNum) {
        String mainid = "";
        String dtFieldValue = "";
        RecordSet rsFun = new RecordSet();
        String sql = "select id from " + mainTableName + " where requestid = '" + requestid + "'";
        new BaseBean().writeLog(sql);
        rsFun.execute(sql);
        if (rsFun.next()) {
            mainid = Util.null2String(rsFun.getString("id"));
        }
        if (!"".equals(mainid)) {
            sql = "select " + dtFieldName + " from " + mainTableName + "_dt" + dtTableNum + " where mainid = '" + mainid + "'";
            new BaseBean().writeLog(sql);
            rsFun.execute(sql);
            if (rsFun.next()) {
                dtFieldValue = rsFun.getString(dtFieldName);
            }
        }
        return dtFieldValue;
    }
}
