package weaver.interfaces.htsc.payment;

import com.alibaba.fastjson.JSON;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class LeaderViewAction extends BaseBean implements Action {

    Pattern patternDigit = Pattern.compile("^-?\\d+(\\.\\d+)?$");

    private String FlowType;
    @Override
    public String execute(RequestInfo requestInfo) {
        //1、获取该流程所有的明细，汇总出部门及预算科目的list
        //2、便利，获取该部门及所有上级预算科目的预算信息，配置groupid
        //3、存入表中
        String requestId = Util.null2String(requestInfo.getRequestid());
        //主表
        String mainTable = Util.null2String(requestInfo.getRequestManager().getBillTableName());
        //本币付款明细表
        String dt8Table = mainTable + "_dt8";
        //外币付款明细表
        String dt9Table = mainTable + "_dt9";
        JAVATools.writelog("begin save leaverView: " + requestId + "--" + FlowType);
        List<Map<String, Object>> budgetList = new ArrayList<>();
        List<Map<String, String>> budgetDeptList = new ArrayList<>();
        if("clbx".equals(FlowType)){
//            String querySql9 = "select t.fycdbm,t. from " + dt9Table + "t " +
//                    " left join " + mainTable + " y on t.mainid=y.id where y.requestid=" + requestId;
//            RecordSet re = new RecordSet();
//            re.executeQuery(querySql9);
//            while (re.next()){
//
//            }

        } else {
            JAVATools.writelog("begin dt8,dt9");
            String querySql8 = "select distinct y.requestid,y.lcbh,t.fysjcdbm,m.departmentcode,m.departmentname,t.yskm,p.yskmmc from " + dt8Table + " t " +
                    " left join " + mainTable + " y on t.mainid=y.id " +
                    " left join hrmdepartment m on t.fysjcdbm = m.id" +
                    " left join uf_kmpz p on t.yskm=p.yskmbm " +
                    " where y.requestid=" + requestId;
            String querySql9 = "select distinct y.requestid,y.lcbh,t.fysjcdbm,m.departmentcode,m.departmentname,t.yskm,p.yskmmc from " + dt9Table + " t " +
                    " left join " + mainTable + " y on t.mainid=y.id " +
                    " left join hrmdepartment m on t.fysjcdbm = m.id " +
                    " left join uf_kmpz p on t.yskm=p.yskmbm " +
                    " where y.requestid=" + requestId;
            List<Map<String, Object>> budgetList8 = this.getBudgetList(querySql8);
            List<Map<String, Object>> budgetList9 = this.getBudgetList(querySql9);
            if(CollectionUtils.isNotEmpty(budgetList8)){
                budgetList.addAll(budgetList8);
            }
            if(CollectionUtils.isNotEmpty(budgetList9)){
                budgetList.addAll(budgetList9);
            }
        }
        JAVATools.writelog("begin budgetList" + JSON.toJSONString(budgetList));
        budgetList.forEach(t -> {
            t.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> t.put(e.getKey(), e.getValue()));
        });
        JAVATools.writelog("begin budgetList" + JSON.toJSONString(budgetList));
        this.doDelete(requestId);
        this.doSave(budgetList);

        return SUCCESS;
    }

    private void doDelete(String requestId){
        String strSql = " delete from uf_leaderViewBase t where t.groupid in (" +
                " select w.groupid from uf_leaderViewBase w where w.requestid=" + requestId +
                ")";
        RecordSet re = new RecordSet();
        re.execute(strSql);
    }


    private void doSave(List<Map<String, Object>> budgetDeptList){
        if(CollectionUtils.isEmpty(budgetDeptList)){
            return;
        }
        List<String> keyList = new ArrayList<>();
        List<String> valueList = new ArrayList<>();
        Map<String, Object> objectMap = budgetDeptList.get(0);
        for(Map.Entry<String, Object> entry : objectMap.entrySet()){
            keyList.add(entry.getKey());
            valueList.add("?");
        }

        String keyStr = StringUtils.join(keyList, ",");
        String valueStr = StringUtils.join(valueList, ",");
//        List<List> values = budgetDeptList.stream().map(t -> (List<Object>)new ArrayList(t.values())).collect(Collectors.toList());
        List<List<Object>> values = new ArrayList<>();
        for(Map<String, Object> budgetDept : budgetDeptList){
//            int count = 0;
            List<Object> valueEle = new ArrayList<>();
            for(String key : keyList){
                valueEle.add(budgetDept.get(key));
            }
            values.add(valueEle);
        }
        String sql = " insert into uf_leaderViewBase ( " + keyStr + " ) values ( " + valueStr + " )";
        JAVATools.writelog("insert sql : " + sql);
        JAVATools.writelog("insert values : " + JSON.toJSONString(values));
        try {
            RecordSetTrans rs = new RecordSetTrans();
            rs.executeBatchSql(sql, values);
            rs.setAutoCommit(false);
            rs.commit();
        }catch (Exception e){
            JAVATools.writelog("batch insert error: " + e);
        }
    }

    private List<Map<String, Object>> getBudgetList(String sql){
        List<Map<String, Object>> leaderViewModelMaps = new ArrayList<>();
        RecordSet re = new RecordSet();
        JAVATools.writelog("begin sql:" + sql);
        re.executeQuery(sql);
        String year = new SimpleDateFormat("yyyy").format(new Date());
        while (re.next()){

            String deptId=  Util.null2String(re.getString("fysjcdbm"));
            String deptCode=  Util.null2String(re.getString("departmentcode"));
            String deptName=  Util.null2String(re.getString("departmentname"));
            String yskmbm=  Util.null2String(re.getString("yskm"));
            String yskmmc=  Util.null2String(re.getString("yskmmc"));
            String lcbh=  Util.null2String(re.getString("lcbh"));
            String requestid=  Util.null2String(re.getString("requestid"));
            JAVATools.writelog("end requestid:" + requestid);
            List<Map<String, Object>> deptBudgetMapList = this.getDeptBudgetList(deptId, deptCode, lcbh, requestid, deptName, yskmbm, yskmmc, year);
            if(CollectionUtils.isNotEmpty(deptBudgetMapList)){
                leaderViewModelMaps.addAll(deptBudgetMapList);
            }
        }
        JAVATools.writelog("end leaderViewModelMaps:" + JSON.toJSONString(leaderViewModelMaps));
        return leaderViewModelMaps;
    }


    //获取该部门，该预算科目所有数据
    private List<Map<String, Object>> getDeptBudgetList(String deptId, String deptCode, String lcbh, String requestid,String deptName, String yskmbm, String yskmmc, String year){
        List<Map<String, Object>> leaderViewMapList =  new ArrayList<>();
        List<String> yskmList = new ArrayList<>();
        String sjyskmbm = yskmbm;
        String originbm = yskmbm;
        do{
            String yskmSql = " select t.sjyskm,t.yskmmc from uf_kmpz t where t.yskmbm = ? ";
            JAVATools.writelog("end yskmSql:" + yskmSql);
            RecordSet re1 = new RecordSet();
            re1.executeQuery(yskmSql, yskmbm);
            if(re1.next()){
                sjyskmbm = Util.null2String(re1.getString("sjyskm"));
                yskmmc = Util.null2String(re1.getString("yskmmc"));
            }
            if(StringUtils.isEmpty(sjyskmbm)) break;
            yskmList.add(yskmbm);
                Map<String, Object> budgetMap = new HashMap<>();
                budgetMap.put("lcbh", lcbh);//流程编号
                budgetMap.put("yskmbm", yskmbm);//预算编码
                budgetMap.put("yskmmc", yskmmc);//预算名称
                budgetMap.put("bmid", deptId);
                budgetMap.put("bmmc", deptName);
                budgetMap.put("bmbm", deptCode);
                leaderViewMapList.add(budgetMap);
                JAVATools.writelog("end leaderViewMapList:" + JSON.toJSONString(leaderViewMapList));
//            }
            yskmbm = sjyskmbm;
            JAVATools.writelog("end yskmbm:" + yskmbm);
        }while(StringUtils.isNotEmpty(yskmbm));
        String groupId = UUID.randomUUID().toString();
        List<String> collect = yskmList.stream().filter(t -> !t.equals(originbm)).sorted(Comparator.comparing(String::length)).collect(Collectors.toList());
        collect.forEach(String::trim);
        String join = StringUtils.join(collect, "-");
        leaderViewMapList.forEach(t -> {
            t.put("yskmbmlj", join);
            t.put("groupid", groupId);
        });
        if(CollectionUtils.isNotEmpty(leaderViewMapList)){
            leaderViewMapList.get(0).put("requestid", requestid);
        }
        JAVATools.writelog("end leaderViewMapList:" + JSON.toJSONString(leaderViewMapList));

        return leaderViewMapList;
    }

    private boolean isDigit(String str){

        return patternDigit.matcher(str).matches();
    }



}
