package com.engine.htsc.yfkfyqr.dao;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.htsc.yfkfyqr.pojo.ReceivingUnitDetail;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.comInfo.PropBean;
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 ViewDetailCMD extends AbstractCommonCommand<Map<String, Object>> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private String requestid;

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

    public ViewDetailCMD(String requestid) {
        this.requestid = requestid;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        logger.info("接收到的requestid参数是：" + requestid);
        Map<String, Object> result = new HashMap<>();
        try {
//        1、取原付款流程的支付模块信息
            List<ReceivingUnitDetail> receivingUnitDetails = getPaymentWorkFlowReceiveDetail(requestid);
//            [{"skdw":"上海携程宏睿国际旅行社有限公司","yfkje":"1060201.06"},{"skdw":"华泰giaogiaogiao","yfkje":"250"}]
            logger.info("原付款流程的支付模块信息:" + JSONObject.toJSONString(receivingUnitDetails));
//        2、取关联此付款流程并且已经办结的预付款费用确认流程票据信息
            Map<String, Double> prepaymentUnitDetail = getPrepaymentWfReceiveDetail(requestid);
//            {"空":102.0}
            logger.info("关联此付款流程并且已经办结的预付款费用确认流程票据信息:" + prepaymentUnitDetail);
//        3、数据合并返回
//            3.1、匹配的数据整理
            for (ReceivingUnitDetail receivingUnitDetail : receivingUnitDetails) {
                String skdw = receivingUnitDetail.getSkdw();
                if (prepaymentUnitDetail.containsKey(skdw)) {
                    receivingUnitDetail.setYhxje(prepaymentUnitDetail.get(skdw).toString());
                    receivingUnitDetail.setDhxje(String.valueOf(str2double(receivingUnitDetail.getYfkje()) - prepaymentUnitDetail.get(skdw)));
                } else {
                    receivingUnitDetail.setYhxje("0.00");
                    receivingUnitDetail.setDhxje(receivingUnitDetail.getYfkje());
                }
            }
//            3.2、未匹配数据整理
            List<ReceivingUnitDetail> unCheckedList = new ArrayList<>();
            for (String skdw : prepaymentUnitDetail.keySet()) {
                boolean isHas = true;
                for (ReceivingUnitDetail receivingUnitDetail : receivingUnitDetails) {
                    if (!receivingUnitDetail.getSkdw().equals(skdw)){
                        isHas = false;
                    }
                }
                if (!isHas){
                    ReceivingUnitDetail unChecked = new ReceivingUnitDetail();
                    unChecked.setSkdw(skdw);
                    unChecked.setYfkje("0.00");
                    unChecked.setYhxje(Util.null2String(prepaymentUnitDetail.get(skdw)));
                    unChecked.setDhxje("0.00");
                    unCheckedList.add(unChecked);
                }
            }
            if (unCheckedList.size()!=0){
//                将没有校验上的数据添加到前端返回数组中
                receivingUnitDetails.addAll(unCheckedList);
            }
            logger.info("即将返回给前端的数据过滤操作结果：" + JSONObject.toJSONString(receivingUnitDetails));
            result.put("isSuccess", "true");
            result.put("data", receivingUnitDetails);
            result.put("message", "");
        } catch (Exception e) {
            logger.info("预付款管理台账对比详情接口出错：");
            logger.info(e.getMessage());
            result.put("isSuccess", "false");
            result.put("data", "");
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 获取所有关联此付款流程并且已办结的预付款费用确认流程，并且取发票中的销方名称以及对应的加税合计金额
     * 1、考虑预付款费用确认流程中发票明细表为5、6两张表
     * 2、考虑可能存在销方名称一样的发票
     *
     * @param requestid 原付款流程
     * @return
     */
    private Map<String, Double> getPrepaymentWfReceiveDetail(String requestid) {
        logger.info("=-=-=-=-=-=-=-=-=-=-=进入获取所有关联此付款流程并且已办结的预付款收据收集方法=-=-=-=-=-=-=-=-=-=-=");
        PropBean pp = new PropBean();
        String yfkMainTable = pp.getPropName("yfkTableName");
        logger.info("获取的预付款流程主表名是：" + yfkMainTable);
        return getInvoiceDetail(yfkMainTable, "5,6", requestid);
    }

    /**
     * 获取指定原付款流程并且已办结的预付款流程发票销方名称以及对应的价税合计金额
     *
     * @param yfkMainTable 预付款流程主表名
     * @param dtNums       对应明细表,多个时以英文逗号分隔
     * @param requestid    原付款流程的requestid
     * @return Map<String, Object>
     */
    private Map<String, Double> getInvoiceDetail(String yfkMainTable, String dtNums, String requestid) {
        logger.info("-=-=-=-=-=-=-=-=-=-=获取预付款流程发票销方名称以及对应的价税合计金额方法，原付款流程requestid为：" + requestid);
        Map<String, Double> invoiceDetail = new HashMap<>();
        RecordSet rs = new RecordSet();
        String sql = "";
        for (String dtNum : dtNums.split(",")) {
            if ("5".equals(dtNum)) {
                sql = "select currentnodetype,isstopped,XFMC,JSHJ from " + yfkMainTable + " a," +
                        "workflow_requestbase b," + yfkMainTable + "_dt5 c where a.requestid = b.requestid and a.id = c.mainid and a.GLYFKLC = '" + requestid + "'";
                logger.info("即将执行的sql是：" + sql);
                rs.executeQuery(sql);
                while (rs.next()) {
                    String currentnodetype = Util.null2String(rs.getString("currentnodetype"));
                    String isstopped = Util.null2String(rs.getString("isstopped"));
                    if ((!"1".equals(isstopped)) && ("3".equals(currentnodetype))) {
                        String xfmc = "".equals(Util.null2String(rs.getString("XFMC"))) ? "空" : Util.null2String(rs.getString("XFMC"));
                        String jshj = Util.null2String(rs.getString("JSHJ"));
                        if (invoiceDetail.containsKey(xfmc)) {
                            Double oldJshj = invoiceDetail.get(xfmc);
                            invoiceDetail.put(xfmc, oldJshj + str2double(jshj));
                        } else {
                            invoiceDetail.put(xfmc, str2double(jshj));
                        }
                    }
                }
            }
            if ("6".equals(dtNum)) {
                sql = "select currentnodetype,isstopped,kpf,kpje from " + yfkMainTable + " a," +
                        "workflow_requestbase b," + yfkMainTable + "_dt6 c where a.requestid = b.requestid and a.id = c.mainid and a.GLYFKLC = '" + requestid + "'";
                logger.info("即将执行的sql是：" + sql);
                rs.executeQuery(sql);
                while (rs.next()) {
                    String currentnodetype = Util.null2String(rs.getString("currentnodetype"));
                    String isstopped = Util.null2String(rs.getString("isstopped"));
                    if ((!"1".equals(isstopped)) && ("3".equals(currentnodetype))) {
                        String xfmc = "".equals(Util.null2String(rs.getString("kpf"))) ? "空" : Util.null2String(rs.getString("kpf"));
                        String jshj = Util.null2String(rs.getString("kpje"));
                        if (invoiceDetail.containsKey(xfmc)) {
                            Double oldJshj = invoiceDetail.get(xfmc);
                            invoiceDetail.put(xfmc, oldJshj + str2double(jshj));
                        } else {
                            invoiceDetail.put(xfmc, str2double(jshj));
                        }
                    }
                }
            }
        }
        return invoiceDetail;
    }

    /**
     * 根据requestid获取原付款流程的支付明细信息
     *
     * @param requestid 原付款流程reqquestid
     * @return
     */
    private List<ReceivingUnitDetail> getPaymentWorkFlowReceiveDetail(String requestid) {
        logger.info("开始获取原付款流程支付明细信息，接收到的requestid是：" + requestid);
        List<ReceivingUnitDetail> receivingPayUnitDetails = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql;
        String mainTable = "";
        sql = "select t2.tablename from workflow_requestbase t0,workflow_base t1,workflow_bill t2 where t0.workflowid = t1.id and t1.formid = t2.id and  t0.requestid = ?";
        logger.info("即将执行的sql是：" + sql);
        rs.executeQuery(sql, requestid);
        if (rs.next()) {
            mainTable = Util.null2String(rs.getString("tablename"));
        }
        if (!"".equals(mainTable)) {
            sql = "select SKDW,DFKJE from " + mainTable + "_dt11 where mainid = (select id from " + mainTable + " where requestid = '" + requestid + "')";
            logger.info("即将执行的sql语句是：" + sql);
            rs.executeQuery(sql);
            while (rs.next()) {
                boolean isNew = true;
                String skdw = Util.null2String(rs.getString("SKDW"));
                logger.info("开始操作的收款单位是：" + skdw);
                String dfkje = Util.null2String(rs.getString("DFKJE"));
                logger.info("开始操作的待付款金额是：" + dfkje);
                logger.info("目前收集到的原付款支付信息是：" + JSONObject.toJSONString(receivingPayUnitDetails));
                for (ReceivingUnitDetail receivingPayUnitDetail : receivingPayUnitDetails) {
                    if (receivingPayUnitDetail.getSkdw().equals(skdw)) {
                        isNew = false;
                        receivingPayUnitDetail.setYfkje(String.valueOf(str2double(dfkje) + str2double(receivingPayUnitDetail.getYfkje())));
                    }
                }
                if (isNew) {
                    ReceivingUnitDetail unitDetail = new ReceivingUnitDetail();
                    unitDetail.setSkdw(skdw);
                    unitDetail.setYfkje(dfkje);
                    receivingPayUnitDetails.add(unitDetail);
                }
            }
        }
        return receivingPayUnitDetails;
    }

    /**
     * 数字的字符串转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;
    }

    private String computeDhxje(String yfkje, String yhxje) {
        double dhxje = str2double(yfkje) - str2double(yhxje);
        return String.valueOf(dhxje);
    }
}
