package weaver.interfaces.htsc.ydbx;

import com.alibaba.fastjson.JSONObject;
import com.weaver.general.TimeUtil;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;

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

/**
 * @Author Weaver.SongYuchen
 * @Date 2022-06-24
 * @Description HTO-13027 移动报销-费用会计审核意见填报
 */
public class ExpenseAccountAuditAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        writeLog("=========================== 总部通用报销-费用会计审核意见填报 ===========================");
        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        PropBean pb = new PropBean();
        String requestid = requestInfo.getRequestid();
        String workflowid = requestInfo.getWorkflowid();
        String operatedate = TimeUtil.getCurrentDateString();
        String operatetime = TimeUtil.getOnlyCurrentTimeString();

        try {
            //审批结果
            String logtype = "";
            int agentorbyagentid = -1;
            //审批意见
            String remark = "";
            //部门名称
            String operatorDept = "16";
            String nodeid = "";
            //主表
            Map<Object, Object> mainInfo = getMainInfo(requestInfo);
            //操作人
            String receivedPersons = "数字员工";
            String operator = "11111112";
            String historydeptname = "计划财务部";
            String agenthistorydeptname = "计划财务部";
            String bsw = Util.null2String(mainInfo.get("bsw"));
            String ngr = Util.null2String(mainInfo.get("ngr"));
            String szbm = Util.null2String(mainInfo.get("szbm"));
            String retCode = Util.null2String(mainInfo.get("szygshjg"));
            String szygyj = Util.null2String(mainInfo.get("szygyj"));
            String isShowKSBXComment = pb.getPropName("isShowKSBXComment");
            writeLog("bsw: " + bsw + ", ngr: " + ngr + ", szbm: " + szbm + ", isShowKSBXComment: " + isShowKSBXComment);

            String sql = "select id from WORKFLOW_NODEBASE where UNNUMBER = 'zbtybx_szygsh'";
            rs.executeQuery(sql);
            if (rs.next()) {
                //步骤
                nodeid = Util.null2String(rs.getString("id"));
            }
            writeLog("requestid: " + requestid + ", workflowid: " + workflowid + ", operatedate: " + operatedate + ", operatetime: " + operatetime + ", receivedPersons: " + receivedPersons + ", nodeid: " + nodeid);

            //是否满足快速报销
            if ("ksbx".equals(bsw) && getKsbx(szbm)) {
                //HTO-13664 当isShowKSBXComment为true的时候，保留现有逻辑
                if ("true".equals(isShowKSBXComment)) {
                    if ("0".equals(retCode)) {
                        //接口返回通过
                        //审批结果——同意
                        logtype = "0";
                        //审批意见
                        remark = "自动审核";
                        rst.setAutoCommit(false);
                        String logSql = "insert into workflow_requestlog(requestid, workflowid, nodeid, logtype, operatedate, operatetime, agentorbyagentid, operator, receivedPersons, remark, operatorDept, historydeptname, agenthistorydeptname) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        rst.executeUpdate(logSql, requestid, workflowid, nodeid, logtype, operatedate, operatetime, agentorbyagentid, operator, receivedPersons, remark, operatorDept, historydeptname, agenthistorydeptname);
                        rst.commit();
                        writeLog("第三方接口返回值为成功");
                    } else {
                        //接口返回不通过
                        //审批结果——不同意
                        logtype = "3";
                        //审批意见
                        remark = szygyj;
                        rst.setAutoCommit(false);
                        String logSql = "insert into workflow_requestlog(requestid, workflowid, nodeid, logtype, operatedate, operatetime, agentorbyagentid, operator, receivedPersons, remark, operatorDept, historydeptname, agenthistorydeptname) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                        rst.executeUpdate(logSql, requestid, workflowid, nodeid, logtype, operatedate, operatetime, agentorbyagentid, operator, receivedPersons, remark, operatorDept, historydeptname, agenthistorydeptname);
                        rst.commit();
                        writeLog("第三方接口返回值为不成功");
                    }
                }
            } else {
                writeLog("流程不满足快速报销");
            }
        } catch (Exception e) {
            writeLog("error: " + e.getMessage());
            rst.rollback();
        }
        return 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 szbm
     * @return
     */
    private Boolean getKsbx(String szbm) {
        RecordSet rs = new RecordSet();
        String sfksbx = "";
        String sql = "select bm, sfksbx from uf_ksbxbm where bm = ?";
        rs.executeQuery(sql, szbm);
        if (rs.next()) {
            sfksbx = Util.null2String(rs.getString("sfksbx"));
        }
        if ("1".equals(sfksbx)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取报销人姓名
     *
     * @param ngr
     * @return
     */
    private String getBxrName(String ngr) {
        String lastName = "";
        RecordSet rs = new RecordSet();
        String sql = "select lastname from hrmresource where id = ?";
        rs.executeQuery(sql, ngr);
        if (rs.next()) {
            lastName = Util.null2String(rs.getString("lastname"));
        }
        writeLog("获取的报销人姓名是：" + lastName);
        return lastName;
    }

    /**
     * 获取报销人工号
     *
     * @param ngr
     * @return
     */
    private String getBxrWorkCode(String ngr) {
        String workCode = "";
        RecordSet rs = new RecordSet();
        String sql = "select workcode from hrmresource where id = ?";
        rs.executeQuery(sql, ngr);
        if (rs.next()) {
            workCode = Util.null2String(rs.getString("workcode"));
        }
        writeLog("获取报销人工号是：" + workCode);
        return workCode;
    }

    /**
     * 获取银行名称
     *
     * @param khx
     * @return
     */
    private String getBankNameByCardNum(String khx) {
        String bankName = "";
        RecordSet rs = new RecordSet();
        String sql = "select YXMC from uf_khh where lxh = ?";
        rs.executeQuery(sql, khx);
        if (rs.next()) {
            bankName = Util.null2String(rs.getString("YXMC"));
        }
        return bankName;
    }

    /**
     * 获取明细表数据
     *
     * @param requestInfo
     * @param num
     * @return
     */
    public static List getDetailInfo(RequestInfo requestInfo, int num) {
        num -= 1;
        DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(num);
        Row[] rows = detailTable.getRow();
        List subList = new ArrayList();
        for (int i = 0; i < rows.length; i++) {
            Row row = rows[i];
            Map oneRow = new HashMap();
            subList.add(oneRow);
            Cell[] cells = row.getCell();
            for (int j = 0; j < cells.length; j++) {
                Cell cell = cells[j];
                oneRow.put(cell.getName(), Util.null2String(cell.getValue()));
            }
        }
        return subList;
    }

    /**
     * 获取的银行卡号和开户行信息
     *
     * @param requestInfo
     * @return
     */
    private String[] getBankCardInfo(RequestInfo requestInfo) {
        List detail11Info = getDetailInfo(requestInfo, 11);
        String bankCardNum = "";
        String bankOfAccounts = "";
        if (detail11Info.size() != 0) {
            Map oneBankCardIndo = (Map) detail11Info.get(0);
            bankCardNum = Util.null2String(oneBankCardIndo.get("yxzh"));
            bankOfAccounts = "".equals(Util.null2String(oneBankCardIndo.get("khx"))) ? "" : getBankNameByCardNum(Util.null2String(oneBankCardIndo.get("khx")));
        }
        return new String[]{bankCardNum, bankOfAccounts};
    }

    /**
     * 获取主表名
     *
     * @param requestid
     * @return
     */
    public String getMainTableName(String requestid) {
        RecordSet rs = new RecordSet();
        String tableName = "";
        String sql = "select tablename from workflow_base a, workflow_bill b, workflow_requestbase c where a.formid = b.id and a.id = c.workflowid and c.requestid = ?";
        rs.executeQuery(sql, requestid);
        if (rs.next()) {
            tableName = Util.null2String(rs.getString("tablename"));
        }
        return tableName;
    }

    /**
     * 获取明细表数据
     *
     * @param requestid
     * @param num
     * @return
     */
    private List<Map<String, Object>> getDetailData(String requestid, Integer num) {
        List<Map<String, Object>> detailData = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String tableName = getMainTableName(requestid);
        if (!"".equals(tableName)) {
            String sql = "select * from " + tableName + "_dt" + num + " where mainid = (select id from " + tableName + " where requestid = '" + requestid + "')";
            rs.executeQuery(sql);
            while (rs.next()) {
                Map<String, Object> oneRow = new HashMap<>();
                String[] columnNames = rs.getColumnName();
                for (String columnName : columnNames) {
                    String rowName = columnName.toLowerCase();
                    oneRow.put(rowName, rs.getString(rowName));
                }
                detailData.add(oneRow);
            }
        } else {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "无法获取主表名");
            detailData.add(error);
        }
        return detailData;
    }

    /**
     * 格式化时间
     *
     * @param date
     * @return
     */
    private String fixDate(String date) {
        writeLog("格式化时间开始，接收到的时间是：" + date);
        String nyr = date.split(" ")[0];
        String[] split = nyr.split("-");
        String month = split[1];
        String day = split[2];
        if (Integer.parseInt(month) < 10 && !month.contains("0")) {
            month = "0".concat(month);
        }
        if (Integer.parseInt(day) < 10 && !day.contains("0")) {
            day = "0".concat(day);
        }
        writeLog("格式化时间结束，结果是：" + split[0] + "-" + month + "-" + day);
        return (split[0] + "-" + month + "-" + day);
    }

    /**
     * 获取发票信息
     *
     * @param requestid
     * @param num
     * @param requestInfo
     * @return
     */
    private List<Map<String, Object>> getInvoiceList(String requestid, Integer num, RequestInfo requestInfo) {
        String[] bankCardInfo = getBankCardInfo(requestInfo);
        writeLog("获取的银行卡号和开户行信息是：" + JSONObject.toJSONString(bankCardInfo));
        List<Map<String, Object>> invoiceList = new ArrayList<>();
        List<Map<String, Object>> detailData = getDetailData(requestid, num);
        for (Map<String, Object> everyRow : detailData) {
            Map<String, Object> standByAdd = new HashMap<>();
            standByAdd.put("invoiceNum", Util.null2String(everyRow.get("FPHM".toLowerCase())));
            standByAdd.put("invoceCode", Util.null2String(everyRow.get("FPDM".toLowerCase())));
            standByAdd.put("bankCard", bankCardInfo[0]);
            standByAdd.put("openingBank", bankCardInfo[1]);
            standByAdd.put("seller", Util.null2String(everyRow.get("XFMC".toLowerCase())));
            standByAdd.put("transactionAmount", Util.null2String(everyRow.get("JSHJ".toLowerCase())));
            standByAdd.put("invoiceCreateTime", fixDate(Util.null2String(everyRow.get("KPSJ".toLowerCase()))));
            invoiceList.add(standByAdd);
        }
        return invoiceList;
    }
}