package weaver.interfaces.htsc.yfkqrlc;

import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.*;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

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

public class ChangeMoneyPara implements Action {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 预付款费用确认流程办结前将金额对应调整到预付款台账中间表中
     *
     * @param requestInfo
     * @return
     * @tableName uf_PrepayMageAccRep
     */
    @Override
    public String execute(RequestInfo requestInfo) {
        logger.info("=============进入金额调整到预付款台账中间表接口===================");
        String back;
        String sql = "";
        RecordSet rs = new RecordSet();
        Map mainInfo = getMainInfo(requestInfo);
        // 关联的付款流程requestId
        String glyfklc = Util.null2String(mainInfo.get("glyfklc"));
        String lcbh = getLcbhFromDate(requestInfo.getRequestid(), requestInfo.getRequestManager().getBillTableName());
        logger.info("需要变动的requestid是：" + glyfklc);
        // 金额
        double xjhjmx = getAllInvoiceMoney(requestInfo.getRequestid(), requestInfo.getRequestManager().getBillTableName());
        logger.info("需要变动的金额是：" + xjhjmx);
        // 获取该流程在在预付款中间表中已经产生的已核销金额和待报销金额
        String newKpf = getDataStringByRequestInfo("xfmc", 5, requestInfo, ";");
        newKpf +=  "".equals(newKpf) ?
                getDataStringByRequestInfo("kpf", 6, requestInfo, ";")
                : ";"+getDataStringByRequestInfo("kpf", 6, requestInfo, ";");
        logger.info("需要更新的开票方为："+newKpf);
        sql = "update uf_PrepayMageAccRep set " +
                "YHXJE = (select to_number(YHXJE) from uf_PrepayMageAccRep where REQUTID = " + glyfklc + ") + " + xjhjmx + "," +
                "DHXJE = (select to_number(DHXJE) from uf_PrepayMageAccRep where REQUTID = " + glyfklc + ") - " + xjhjmx + "," +
                "fyqrlcbh = (select decode(" +
                "       Dbms_Lob.getlength(a.fyqrlcbh)," +
                "       '','" + lcbh + "'," +
                "       a.fyqrlcbh||'；'|| '" + lcbh + "') " +
                "from uf_PrepayMageAccRep a where REQUTID = " + glyfklc + ") " + "," +
                "KPF = (select decode(Dbms_Lob.getlength(a.KPF),'','" + newKpf + "',a.KPF||'；'|| '" + newKpf + "') from uf_PrepayMageAccRep a where REQUTID = " + glyfklc + ")" +
                "where REQUTID = " + glyfklc + "";
        logger.info("即将执行的sql是：" + sql);
        boolean b = rs.executeUpdate(sql);
        if (b) {
            back = SUCCESS;
        } else {
            back = FAILURE_AND_CONTINUE;
            requestInfo.getRequestManager().setMessagecontent("流程流转异常：金额写入中间表异常，请联系管理员");
        }
        return back;
    }

    /**
     * 获取流程编号
     *
     * @param requestid
     * @param tableName
     * @return
     */
    private String getLcbhFromDate(String requestid, String tableName) {
        logger.info("进入获取流程编号方法：requestid：" + requestid + ",maintablename:" + tableName);
        RecordSet rs = new RecordSet();
        rs.executeQuery("select LCBH from " + tableName + " where requestid = " + requestid + "");
        if (rs.next()) {
            return Util.null2String(rs.getString("LCBH"));
        } else {
            return "";
        }
    }

    /**
     * 获取主表数据
     */
    private static Map getMainInfo(RequestInfo requestInfo) {
        Map 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;
    }

    /**
     * 数字的字符串转double类型
     *
     * @param str
     * @return
     */
    private static double str2double(String str) {
        str = "".equals(str) ? "0" : str;
        double num;
        DecimalFormat myformat = new DecimalFormat("#0.00");
        //装换为double类型
        num = Double.parseDouble(str);
        //保留2为小数
        num = Double.parseDouble(myformat.format(num));
        return num;
    }

    /**
     * 获取当前流程的发票加税合计金额
     *
     * @param requestid
     * @param tableName
     * @return
     */
    private double getAllInvoiceMoney(String requestid, String tableName) {
        logger.info("获取当前流程的发票汇总价税合计金额" + ",requestid：" + requestid + ",maintablename:" + tableName);
        RecordSet rs = new RecordSet();
        String sql = "select SUM(JSHJZE) as JSHJZES from " + tableName + "_dt7 where mainid = (select id from " + tableName + " where requestid = '" + requestid + "')";
        rs.executeQuery(sql);
        if (rs.next()) {
            return str2double(Util.null2String(rs.getString("JSHJZES")));
        } else {
            return 0.00;
        }
    }

    /**
     * @param fieldName   获取的字段名
     * @param tableNum    明细表Num
     * @param requestInfo 参数
     * @param interval    间隔符
     * @Describe 通过RequestInfo获取明细表指定字段
     */
    public static String getDataStringByRequestInfo(String fieldName, int tableNum, RequestInfo requestInfo, String interval) {
        String returnResult = "";
        List dtData = getDetailInfo(requestInfo, tableNum - 1);
        if (dtData.size() != 0) {
            List<String> htbhList = new ArrayList<>(dtData.size());
            for (Object dtOne : dtData) {
                Map oneRow = (Map) dtOne;
                String aFieldVal = Util.null2String(oneRow.get(fieldName));
                // 去重去空处理
                if ((!"".equals(aFieldVal)) && (!" ".equals(aFieldVal)) && (!htbhList.contains(aFieldVal))) {
                    htbhList.add(aFieldVal);
                }
            }
            htbhList.remove(null);
            returnResult = StringUtils.join(htbhList, interval);
        }
        return returnResult;
    }

    private static List getDetailInfo(RequestInfo requestInfo, int num) {
        DetailTable detailTable = requestInfo.getDetailTableInfo().getDetailTable(num);
        //dtltable数组中的行数据集合
        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;
    }
}
