package weaver.interfaces.htsc.lhccsq;

import com.alibaba.fastjson.JSONObject;
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.SimpleDateFormat;
import java.util.*;

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

    /**
     * 特殊地区
     */
    private static String[] area = {"34", "112", "248", "246"};

    @Override
    public String execute(RequestInfo requestInfo) {
        logger.info("进入重新计算差补接口");
        String back = SUCCESS;
        try{
            RecordSet rs = new RecordSet();
            String mainTableName = requestInfo.getRequestManager().getBillTableName();
            logger.info("主表名是：" + mainTableName);
            String requestid = requestInfo.getRequestid();
            logger.info("requestid：" + requestid);
            int i = generateBtVal(isSpecialPeople(requestInfo), requestInfo);
            logger.info("计算的补贴值是:" + i);
            // 将补贴值添加到数据库中
            String sql = "update " + mainTableName + " set cb = ? where requestid = ?";
            boolean isSuccess = rs.executeUpdate(sql, i, requestid);
            if (isSuccess) {
                back = SUCCESS;
            } else {
                back = FAILURE_AND_CONTINUE;
                requestInfo.getRequestManager().setMessagecontent("流程流转异常：补贴更新失败，请联系管理员处理");
            }
        }catch (Exception e){
            back = FAILURE_AND_CONTINUE;
            requestInfo.getRequestManager().setMessagecontent("流程流转异常：补贴更新失败，请联系管理员处理");
            logger.info("重新计算差补接口发生错误："+e.getMessage());
        }
        return back;
    }

    private int generateBtVal(boolean isSpecial, RequestInfo requestInfo) {
        logger.info("进入具体计算补贴的方法==================================");
        int bt = 0;
        // 1、如果是实习生，则没有补贴
        String ccrgh = getDataStringByRequestInfo("ccrgh", 2, requestInfo, ",").split(",")[0];
        logger.info("获取的出差人工号是：" + ccrgh);
        if (ccrgh.contains("sx")) {
            bt = 0;
        } else if (!isSpecial) {
            // 不是特殊人员
            int ts = 0;
            // 获取出差信息，对应G1216
            String mainTable = requestInfo.getRequestManager().getBillTableName();
            logger.info("获取的主表名是：" + mainTable);
            String requestid = requestInfo.getRequestid();
            logger.info("获取的requestid是：" + requestid);

            List<TravelInfo> travelInfos = getTravelInfo(mainTable, requestid);
            logger.info("需要进行补贴计算金额的差旅信息是：" + JSONObject.toJSONString(travelInfos));
            for (int i = 0; i < travelInfos.size(); i++) {
                TravelInfo travelInfo = travelInfos.get(i);
                String cfsj = travelInfo.getCfsj();
                String fhsj = travelInfo.getFhsj();
                String mddgn = travelInfo.getMddgn();
                String sfbc = travelInfo.getSfbc();
                // 首条数据天数+1
                if (i == 0) {
                    ts = (int) (1 + getDaysBetween(cfsj, fhsj));
                } else {
                    if ("0".equals(sfbc)) {
                        ts = (int) getDaysBetween(cfsj, fhsj);
                    } else {
                        ts = (int) (1 + getDaysBetween(cfsj, fhsj));
                    }
                }
                // 出差类型  业务
                Map mainInfo = getMainInfo(requestInfo);
                String cclxzxx = Util.null2String(mainInfo.get("cclxzxx"));
                if ("3".equals(cclxzxx)) {
                    bt += ts * 50;
                } else {
                    String city = mddgn.split(",")[1];
                    String procince = mddgn.split(",")[0];
                    List<String> areas = Arrays.asList(area);
                    logger.info("数组转成集合之后的值是：" + JSONObject.toJSONString(areas));
                    if (areas.contains(city) || "282".equals(procince)) {
                        bt += ts * 100;
                    } else {
                        bt += ts * 80;
                    }
                }
            }
        }
        return bt;
    }


    /**
     * 判断是否是特殊人员
     *
     * @return 是否是特殊人员
     */
    private boolean isSpecialPeople(RequestInfo requestInfo) {
        String field_sfsbsx_value = getDataStringByRequestInfo("sfsbsx", 2, requestInfo, ",").split(",")[0];
        logger.info("获取的是否实报实销值是：" + field_sfsbsx_value);
        return "0".equals(field_sfsbsx_value);
    }

    /**
     * @param fieldName   获取的字段名
     * @param tableNum    明细表Num
     * @param requestInfo 参数
     * @param interval    间隔符
     * @Describe 通过RequestInfo获取明细表指定字段
     */
    private 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;
    }

    /**
     * 获取主表数据
     *
     * @param requestInfo
     * @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;
    }

    /**
     * 获取明细表数据
     * 明细表4则传3
     *
     * @param requestInfo
     * @param num
     * @return
     */
    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;
    }

    /**
     * 获取该流程出差信息
     *
     * @param mainTable
     * @param requestid
     * @return
     */
    private List<TravelInfo> getTravelInfo(String mainTable, String requestid) {
        List<TravelInfo> travelinfos = new ArrayList<>();
        RecordSet rs = new RecordSet();
        String sql = "select id,sfbc,cfsj,fhsj,mddgn from " + mainTable + "_dt4 where mainid =  " +
                "(select id from " + mainTable + "  where requestid = " + requestid + ") order by id";
        logger.info("即将执行的sql是：" + sql);
        rs.executeQuery(sql);
        while (rs.next()) {
            TravelInfo travelInfo = new TravelInfo();
            travelInfo.setSfbc(Util.null2String(rs.getString("sfbc")));
            travelInfo.setCfsj(Util.null2String(rs.getString("cfsj")));
            travelInfo.setFhsj(Util.null2String(rs.getString("fhsj")));
            travelInfo.setMddgn(Util.null2String(rs.getString("mddgn")));
            travelinfos.add(travelInfo);
        }
        logger.info("获取的出差信息是：" + JSONObject.toJSONString(travelinfos));
        return travelinfos;
    }

    /**
     * 获取两个时间点之间的天数
     *
     * @param var0
     * @param var1
     * @return
     */
    private static long getDaysBetween(String var0, String var1) {
        SimpleDateFormat var2 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date var3 = var2.parse(var1);
            Date var4 = var2.parse(var0);
            return (var3.getTime() - var4.getTime()) / 86400000L;
        } catch (Exception var5) {
            return 0L;
        }
    }
}
