package weaver.interfaces.htsc.ksbx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.htsc.payment.util.HttpUtil;
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;

public class ClearFykjAction extends BaseBean implements Action {
    @Override
    public String execute(RequestInfo requestInfo) {
        String back = "";
        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();
        String tablename = requestInfo.getRequestManager().getBillTableName();
        writeLog("==========================ClearFykjAction==========================");
        try {
//            获取表单数据
            Map map = mainData(requestInfo);
            String bsw = Util.null2String(map.get("bsw"));
            String ngr = Util.null2String(map.get("ngr"));//非空判断
            String szbm = Util.null2String(map.get("szbm"));//所在部门

            writeLog("获取的bsw是：" + bsw + "----------------------");

            if ("ksbx".equals(bsw)&&getKsbx(szbm)) {
                String sql = "";
                String requestid = requestInfo.getRequestid();
// ==========================访问接口代码开始=======================================
//                获取相关URL以及相关参数
                PropBean pp = new PropBean();
                String url = pp.getPropName("startAccountHelper");
                writeLog(url + " ----------");
                //接口参数组装
                Map<String, Object> paramsMap = new HashMap<>();
                paramsMap.put("taskType", "accountingAssistant");
                paramsMap.put("sysCode", "OA");

                Map<String, Object> concreteData = new HashMap<>();
                concreteData.put("claimer", getBxrName(ngr));//判断非空
                concreteData.put("claimerId", getBxrWorkCode(ngr));//判断非空
                concreteData.put("invoiceList", getinvoiceList(requestInfo.getRequestid(), 5,requestInfo));
                paramsMap.put("paramsMap", concreteData);
                writeLog(JSON.toJSONString(paramsMap));
                //访问接口
                String backData = HttpUtil.postApplicationJson(url, JSON.toJSONString(paramsMap));
                writeLog("接口返回的参数是：" + backData);
                JSONObject object = JSON.parseObject(backData);
                String retCode = object.getString("retCode");
                String message = object.getString("message");
                writeLog("接口的返回数据是：" + object);

                //将意见插入主表字段szygyj
                rst.setAutoCommit(false);
                String szygyjSql = String.format("update %s set szygyj = ?, szygshjg = ? where requestid = ?", tablename);
                rst.executeUpdate(szygyjSql, message, retCode, requestid);
                rst.commit();
                writeLog("isShowKSBXComment为false，更新主表数据成功");

                if ("0".equals(retCode)) {
                    //更新表单数据
                    writeLog("执行update表单语句");
                    sql = "UPDATE " + tablename + " SET fykj = '' where requestid = '" + requestid + "'";
                    writeLog("即将执行的update语句是：" + sql);
                    rs.executeUpdate(sql);
                    back = SUCCESS;
                }else {
                    writeLog("第三方接口返回值为不成功");
                    changeFhr(requestid);
                    back = SUCCESS;
                }
// ==========================访问接口代码结束=======================================
            } else {
                writeLog("流程不满足快速报销");
                changeFhr(requestInfo.getRequestid());
                back = SUCCESS;
            }
        } catch (Exception e) {
            writeLog(e.getMessage());
            back = SUCCESS;
        }
        writeLog("执行结果是：" + back);
        return back;
    }

    private Boolean getKsbx(String szbm){
        RecordSet rs = new RecordSet();
        String sfksbx = "";
        String sql = "select bm,sfksbx from uf_ksbxbm where bm = '"+szbm+"'";
        rs.execute(sql);
        if (rs.next()) {
            sfksbx = Util.null2String(rs.getString("sfksbx"));
        }
        if ("1".equals(sfksbx)) {
            return true;
        }else {
            return false;
        }
    }

    private List<Map<String, Object>> getinvoiceList(String requestid, Integer num, RequestInfo requestInfo) {
//        获取银行卡号和开户行信息 {bankCardNum, bankOfAccounts};
        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;

    }

    private String getBxrWorkCode(String ngr) {
        String workCode = "";
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        String sql = "select workcode from hrmresource where id = '" + ngr + "'";
        writeLog("=========即将执行获取报销人工号的sql是:" + sql);
        rs.executeQuery(sql);
        if (rs.next()) {
            workCode = rs.getString("workcode");
        }
        writeLog("=========获取的workcode是：" + workCode);
        return workCode;
    }

    private String getBxrName(String ngr) {
        String lastname = "";
        BaseBean bb = new BaseBean();
        RecordSet rs = new RecordSet();
        String sql = "select lastname from hrmresource where id = '" + ngr + "'";
        writeLog("=========即将执行获取报销人姓名的sql是:" + sql);
        rs.executeQuery(sql);
        if (rs.next()) {
            lastname = rs.getString("lastname");
        }
        writeLog("获取的报销人姓名是：" + lastname);
        return lastname;
    }

    /**
     * 主表数据
     */
    private static Map mainData(RequestInfo requestInfo) {
        Map mainTableDataMap = new HashMap();
        Property[] property = requestInfo.getMainTableInfo().getProperty();
        for (int i = 0; i < property.length; i++) {
            mainTableDataMap.put(property[i].getName().toLowerCase(), Util.null2String(property[i].getValue()));
        }
        return mainTableDataMap;
    }

    /**
     * 获取明细表数据
     */
    private List<Map<String, Object>> getDetailData(String requestid, Integer num) {
        List<Map<String, Object>> detailData = new ArrayList<>();
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        String sql = "";
        String tableName = getMainTableName(requestid);
        if (!"".equals(tableName)) {
            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;
    }

    public String getMainTableName(String requestid) {
        RecordSet rs = new RecordSet();
        String tableName = "";
        String sql = "";
        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='" + requestid + "'";
        rs.executeQuery(sql);
        if (rs.next()) {
            tableName = rs.getString("tablename");
        }
        return tableName;
    }

    /**
     * @param date
     * @return
     */
    private String fixDate(String date) {
        BaseBean bb = new BaseBean();
        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);
    }

    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};
    }

    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 = num - 1;
        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;
    }

    private void changeFhr(String requestid){
        writeLog("进入置空复核人的方法=-=-=-=-=-=-=-=-=-=-=-=");
        RecordSet rs = new RecordSet();
        String sql = "UPDATE " + getMainTableName(requestid) + " SET fhr = '' where requestid = '" + requestid + "'";
        writeLog("即将执行的sql是："+sql);
        rs.executeUpdate(sql);
    }
}
