package weaver.interfaces.htsc.cwtz;

import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.payment.dao.BudgetDao;
import com.engine.htsc.payment.enums.BudgetNodeType;
import com.engine.htsc.payment.util.PayUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetDataSource;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.company.DepartmentComInfo;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddBudgetMidTable extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String back;
        RecordSet rs = new RecordSet();
        String sql = "";
        String billStatus = BudgetNodeType.FINISH.getValue();
        String requestid = requestInfo.getRequestid();
        writeLog("获取的requestid是：" + requestid + ",billStatus是：" + billStatus);
        try {
//            表单数据获取
            String tableName = getTableNameByRequestId(requestid);
            sql = "select LCBH from " + tableName + " where REQUESTID=" + requestid;
            rs.executeQuery(sql);
            boolean isItFlag = false;
            String title = "";
            if (rs.next()) {
                title = rs.getString("LCBH");
            }
            String yskmTable = tableName + "_DT2";
            boolean b = doBudgetMiddleTablePrivate(title, billStatus, null, yskmTable, tableName, isItFlag);
            if (b) {
                back = SUCCESS;
            } else {
                back = FAILURE_AND_CONTINUE;
                requestInfo.getRequestManager().setMessagecontent("流程流转异常：浪潮预算中间库同步异常");
            }
        } catch (Exception e) {
            back = FAILURE_AND_CONTINUE;
            e.printStackTrace();
        }
        return back;
    }

    /**
     * 根据requestid获取主表名
     */
    public String getTableNameByRequestId(String requestId) {
        RecordSet rs = new RecordSet();
        rs.execute("select t1.tablename from workflow_bill t1,workflow_base t2,workflow_requestbase t3 \n where t1.id =t2.formid and t2.id = t3.workflowid and t3.requestid = " +
                requestId);
        String table = "";
        if (rs.next()) {
            table = Util.null2String(rs.getString("tablename"));
        }
        return table;
    }

    /**
     * 确认预算中间表中是否有重复数据
     */
    private boolean doBudgetMiddleTablePrivate(String requestMark, String billStatus, String fbizdate, String budgetKmTable, String mainTable, boolean isIt) {
        PropBean pp = new PropBean();
        BudgetDao budgetDao = new BudgetDao();
        writeLog("付款流程,预算中间表更新\n  @requestMark=" + requestMark + ",billStatus=" + billStatus +
                ",budgetKmTable=" + budgetKmTable + "@");
        if (StringUtils.isBlank(requestMark) || StringUtils.isBlank(billStatus) || StringUtils.isBlank(budgetKmTable)) {
            writeLog("更新失败,原因:流程编号或单据状态为空");
            return false;
        }
        try {
//            获取外部数据源
            String budgetTableName = pp.getPropName("BudgetTableName");
            String nameIsExist = budgetDao.fNameIsExist(budgetTableName, requestMark);
            writeLog("预算数据是否存在sql @" + nameIsExist + "@");
            RecordSetDataSource rsd = new RecordSetDataSource("BudgetRecords");
            rsd.execute(nameIsExist);
            if (rsd.next() && StringUtils.isNotBlank(requestMark)) {
                String deleteAll = String.format("delete from %s where FNAME='%s'",
                        budgetTableName, requestMark);
                rsd.executeUpdateWithDatasource(deleteAll, "BudgetRecords");
                insertBudgetMiddleTablePrivate(requestMark, billStatus, fbizdate, budgetKmTable, mainTable, isIt, rsd);
            } else {
                insertBudgetMiddleTablePrivate(requestMark, billStatus, fbizdate, budgetKmTable, mainTable, isIt, rsd);
            }
            return true;
        } catch (Exception e) {
            e.getMessage();
            writeLog("数据添加失败，原因是：" + e);
            return false;
        }
    }

    /**
     * 向财务中心表写入数据
     */
    private boolean insertBudgetMiddleTablePrivate(String requestMark, String billStatus, String fbizdate, String budgetKmTable, String mainTable, boolean isIt, RecordSetDataSource rsd) throws Exception {
        writeLog("预算信息不存在，执行更新方法 insertBudgetMiddleTable\n @requestMark=" + requestMark + ",billStatus=" + billStatus + "@");
        Map<String, Object> budgetBody = getBudgetBodyPrivate(requestMark, mainTable, budgetKmTable, isIt);
        writeLog("获取的表单数据是：" + JSONObject.toJSONString(budgetBody));
        //主表数据
        List<Object> mainInfo = (List<Object>) budgetBody.get("main");
        writeLog("主表数据是：" + JSONObject.toJSONString(mainInfo));
        //预算数据
        List<List<Object>> dtInfo = (List<List<Object>>) budgetBody.get("dt");
        writeLog("明细表的记录数：" + dtInfo.size());
        writeLog("他们的值是：" + JSONObject.toJSONString(dtInfo));
        if (dtInfo.size() == 0) {
            writeLog("插入预算表中止,因为科目信息为空");
            return false;
        }
//        //年
//        DateTimeFormatter dfOnlyYear = DateTimeFormatter.ofPattern("yyyy");
//        //当前操作时间
//        DateTimeFormatter dfDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            String budgetTableName = new PropBean().getPropName("BudgetTableName");
            for (List<Object> singleValue : dtInfo) {
                List<Object> insertValues = new ArrayList<>();
                insertValues.add(billStatus);
                insertValues.addAll(mainInfo);
                insertValues.addAll(singleValue);
                writeLog("即将插入预算中间表的数据是：" + JSONObject.toJSONString(insertValues));
                String insert = insertMiddleTablePrivate(budgetTableName);
                writeLog("插入中间表的sql语句是：" + insert);
                RecordSet recordSet = new RecordSet();
                recordSet.executeUpdateWithDatasource(insert, "BudgetRecords", insertValues);
            }
            return true;
        } catch (Exception e) {
            writeLog("insertBudgetMiddleTable异常, [" + e + "]");
            return false;
        }
    }

    /**
     * 获取插入表中的数据
     */
    private Map<String, Object> getBudgetBodyPrivate(String requestMark, String main, String budgetKmTable, boolean isItFlag) throws Exception {
        Map<String, Object> res = new HashMap<>();
        writeLog("付款流程表名: @" + main + "@");
        writeLog("付款预算表名: @" + budgetKmTable + "@");
        RecordSet rs = new RecordSet();
        String mainInfo = getMainInfoSql(main, requestMark);
        writeLog("获取主表的sql语句是:" + mainInfo);
        rs.executeQuery(mainInfo);
        List<Object> mainValues = new ArrayList<>();

        String mainId = "";
        if (rs.next()) {
            mainValues.add(requestMark);
            //流程编码
            mainValues.add(Util.null2String(rs.getString("REQUESTNAME")));
            //拟稿人名称
            mainValues.add(Util.null2String(rs.getString("LASTNAME")));
            mainValues.add(Util.null2String(rs.getString("RZRQ").substring(0, 4)));
            mainValues.add(Util.null2String(rs.getString("RZRQ")) + " 00:00:00");
            mainId = Util.null2String(rs.getString("ID"));
        }
        writeLog("主表数据: @" + mainValues + "@");
        res.put("main", mainValues);
        //获取预算科目明细表数据
        String budgetKmTableInfo = getKmTableInfoSql(budgetKmTable, mainId);
        writeLog("获取预算科目明细表的sql是：" + budgetKmTableInfo);
        DepartmentComInfo dc = new DepartmentComInfo();
        rs.executeQuery(budgetKmTableInfo);
        //所有明细科目数据 add dtValues 单行明细科目数据
        List<List<Object>> allDtValues = new ArrayList<>();
        while (rs.next()) {
            //单行明细科目数据
            List<Object> dtValues = new ArrayList<>();
            String yskm = Util.null2String(rs.getString("yskm"));
            if (yskm.isEmpty()) {
                dtValues.add("");
                dtValues.add("");
            } else {
                String trueYskm = yskm.split("_")[1];
                dtValues.add(trueYskm);
                dtValues.add(PayUtil.superBudgetSubject(trueYskm));
            }
//            不含税金额
            String je = Util.null2String(rs.getString("je"));
            dtValues.add(je);
//            未税金额
            dtValues.add(je);
//            税金
            dtValues.add("0");
//           实际报销金额
            dtValues.add("0");
//            差旅报销金额
            dtValues.add("0");
//            是否超预算
            String sfcys = Util.null2String(rs.getString("sfcys"));
            if ("0".equals(sfcys)) {
                dtValues.add("否");
            } else if ("1".equals(sfcys)) {
                dtValues.add("是");
            } else {
                dtValues.add("");
            }
            dtValues.add("否");
            dtValues.add("");
            dtValues.add("");
//            华泰部门code
            String fycdbm = Util.null2String(rs.getString("fycdbm"));
            String departmentCode = dc.getDepartmentCode(fycdbm);
            dtValues.add(departmentCode);
            allDtValues.add(dtValues);
        }
        writeLog("预算表数据" + budgetKmTable + "  @" + allDtValues + "@");
        res.put("dt", allDtValues);
        return res;
    }

    /**
     * 获取财务调整主表数据sql
     */
    private String getMainInfoSql(String main, String requestMark) {
        return new SQL() {{
            SELECT_DISTINCT("t1.ID,t1.LCBH,t1.RZRQ,t2.REQUESTNAME,t3.LASTNAME,t4.DEPARTMENTCODE");
            FROM(main + " t1");
            LEFT_OUTER_JOIN("workflow_requestbase t2 on t1.requestid=t2.requestid");
            LEFT_OUTER_JOIN("hrmresource t3 on t1.ngr=t3.id");
            LEFT_OUTER_JOIN("hrmdepartment t4 on t3.departmentid=t4.id");
            WHERE("t1.lcbh='" + requestMark + "'");
        }}.toString();
    }

    /**
     * 获取财务调整预算科目信息
     */
    private String getKmTableInfoSql(String budgetKmTable, String mainId) {
        return new SQL() {{
            SELECT("fycdbm,je,sfcys,yskm");
            FROM(budgetKmTable);
            WHERE("MAINID=" + mainId);
        }}.toString();
    }

    /**
     * 插入中间表
     *
     * @param tableName 表名
     * @return sql
     */
    private String insertMiddleTablePrivate(String tableName) {
        return new SQL() {{
            INSERT_INTO(tableName);
            VALUES("FBILLSTATUS,FNAME,FBILLTITLE,FPESONNAME," +
                            "YSND,FBIZDATE,FITEMDETAILNUM," +
                            "FCOSTITEMNUM,FSJAMOUNT,FNOTAXAMOUNT,FTAXAMOUNT,FACTUALAMOUNT," +
                            "FSTANDARDAMOUNT,FOVERWEIGHT,\n" +
                            "ISITITEM,ITITEMCODE,ITITEMNAME,FDEPTNUMBER",
                    "?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?");
        }}.toString();
    }
}


