package com.engine.attendance.workflow.action.askforleave;

import com.engine.attendance.enums.AccountingUnitEnum;
import com.engine.attendance.enums.CheckBoxEnum;
import com.engine.attendance.workflow.enums.AskAndEvctionWayEnum;
import com.engine.attendance.workflow.service.MakeUpClockInService;
import com.engine.attendance.workflow.service.impl.MakeUpClockInServiceImpl;
import com.engine.common.util.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class AskForLeaveWorkFlowSubmitAction implements Action {
    private MakeUpClockInService makeUpClockInService = ServiceUtil.getService(MakeUpClockInServiceImpl.class);

    @Override
    public String execute(RequestInfo requestInfo) {
        String requestid = requestInfo.getRequestid();

        try {

            // 流程表单主表数据
            HashMap<String, String> mainTableData = CommonUtil.getMainTableInfo(requestInfo);
            log.info("mainTableData : [{}]", mainTableData);
            // 流程表单明细表1数据
            List<Map<String, String>> detailTableData = CommonUtil.getDetailTableInfo(requestInfo, 0);
            log.info("detailTableData : [{}]", detailTableData);

            String detail2TableName = requestInfo.getDetailTableInfo().getDetailTable()[1].getTableDBName();
            log.info("detail2TableName : [{}]", detail2TableName);
            //请假人员
            String qjry = mainTableData.get("qjry");
            //实际假期类型
            String jqlx = mainTableData.get("sjqjlx");
            //需要校验假期额度的假期类型
            List<String> checkAmountJqIdList = CommonUtil.getJqInfoWithAmount();
            //第一笔开始时间
            String firstStartDate = detailTableData.get(0).get("ksrq");

            List<Map<String, Object>> detailTable2 = Lists.newArrayList();


            /**
             * 补打卡日期是否关账
             */
            Map<String, Object> params = Maps.newHashMap();
            params.put("userId",qjry);
            params.put("submitDate",DateUtil.getCurrentDate());
            params.put("submitStr","ksrq");
            params.put("submitDataList",detailTableData);
            if (detailTableData == null || detailTableData.size() == 0){
                log.error("明细表没有数据！");
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent("明细表没有数据！");
                return Action.FAILURE_AND_CONTINUE;
            }
            Map<String,Object> dataMap = makeUpClockInService.getKqCycleTimeIntervalCmd(params);
            List<Map<String,Object>> closeList = (List<Map<String,Object>>)dataMap.get("closeList");
            List<String> nocycleList = (List<String>)dataMap.get("nocycleList");
            List<Map<String,Object>> dateList = (List<Map<String,Object>>)dataMap.get("dataList");

            boolean status = (boolean)dataMap.get("status");
            if (!status){
                log.error("该人员没有考勤周期");
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent("该人员没有考勤周期！");
                return Action.FAILURE_AND_CONTINUE;
            }
            if (closeList.size() > 0 || nocycleList.size() > 0){
                String message = "";
                if (nocycleList.size() > 0){
                    message = message +String.join(",",nocycleList)+"未找对对应的考勤周期；";
                }
                if (closeList.size() > 0){
                    List<String> list = closeList.stream().map(e->e.get("rq").toString()).collect(Collectors.toList());
                    message = message +String.join(",",list)+"对应的考勤周期的考勤周期已关账";
                }
                requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                requestInfo.getRequestManager().setMessagecontent(message);
                return Action.FAILURE_AND_CONTINUE;
            }
            /**
             * 假期校验及入库
             */
            String sql = "select id,jqid,sxrq,ktsc,yxsc,wxsc,yqsxrq,ztsc from uf_jcl_kq_jqye where ygid=? and jqid=? and sxrq<=? and yqsxrq>=? order by sxrq";
            List<Map<String, Object>> holidayBalanceList = DbTools.getSqlToList(sql, qjry, jqlx, firstStartDate, firstStartDate);
            Map<String, Object> holidayBalanceMap = holidayBalanceList.stream().collect(Collectors.toMap(e -> e.get("id").toString(), e -> e));
            sql = "select id,mc,hsdw,hsl,jcbyxsyqjb,yxsydjb,qzsyyxjb  from uf_jcl_kq_kqxm  where id=?";
            Map<String, Object> holidayItem = DbTools.getSqlToMap(sql, jqlx);
            //当前假期类型需要校验剩余额度时则校验假期剩余额度，否则跳过校验
            if (checkAmountJqIdList.contains(jqlx)) {
                //假期核算单位
                String hsdw = Util.null2String(holidayItem.get("hsdw"));
                //请假方式
                String cxjqj = mainTableData.get("cxjqj");

                for (Map<String, String> detailData : detailTableData) {
                    String ksrq = detailData.get("ksrq");
                    //请假时间
                    double leaveDuration = 0;
                    if (cxjqj.equals(AskAndEvctionWayEnum.ALLDAY.getKey())) {
                        leaveDuration = 1;
                    } else if (cxjqj.equals(AskAndEvctionWayEnum.HALFDAY.getKey())) {
                        leaveDuration = 0.5;
                    } else if (cxjqj.equals(AskAndEvctionWayEnum.TIME_INTERVAL.getKey()) || cxjqj.equals(AskAndEvctionWayEnum.HOUR.getKey())) {
                        leaveDuration = Double.valueOf(Util.null2String(detailData.get("qjsc")));
                    }
                    if (hsdw.equals(AccountingUnitEnum.HOUR.getKey()) && (cxjqj.equals(AskAndEvctionWayEnum.ALLDAY.getKey()) || cxjqj.equals(AskAndEvctionWayEnum.HALFDAY.getKey()))) {
                        leaveDuration = leaveDuration * 8;
                    }
                    log.info("leaveDuration : [{}]", leaveDuration);
//                    List<Map<String, Object>> holidayBalancefilterList = holidayBalanceList.stream().filter(e -> DateUtil.getTime(e.get("yqsxrq").toString()).compareTo(DateUtil.getTime(ksrq)) >= 0).collect(Collectors.toList());
                    for (Map<String, Object> holidayBalance : holidayBalanceList) {
                        //额定未休时长
                        double wxsc = Util.null2String(holidayBalance.get("wxsc")).equals("") ? 0 : Double.valueOf(holidayBalance.get("wxsc").toString());
                        if (leaveDuration > 0) {
                            Map<String, Object> detail2Map = Maps.newHashMap();
                            detail2Map.put("glmxid", detailData.get("id"));
                            detail2Map.put("jqye", holidayBalance.get("id"));
                            detail2Map.put("mainid", mainTableData.get("id"));
                            detail2Map.put("glrq", detailData.get("ksrq"));
                            if (leaveDuration > wxsc) {
                                detail2Map.put("sysc", wxsc);
                                leaveDuration = Utils.subtract(leaveDuration, wxsc);
                                wxsc = 0;
                            } else {
                                detail2Map.put("sysc", leaveDuration);
                                leaveDuration = 0;
                                wxsc = Utils.subtract(wxsc, leaveDuration);
                            }
                            detailTable2.add(detail2Map);
                            holidayBalance.put("wxsc", wxsc);
                        }
                    }
                    if (leaveDuration > 0) {
                        //假期余额不足
//                        String message = ksrq + "对应的" + holidayItem.get("mc") + "假期余额不足！";
                        String message = holidayItem.get("mc") + "假期余额不足！";
                        log.error(message);
                        requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                        requestInfo.getRequestManager().setMessagecontent(message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }
                log.info("detailTable2 : [{}]", detailTable2);

                /**
                 * 请假时长是否满足“请假类型”中单次最小休时长，由假期额度表和流程主表获取对比数据
                 */
                String jqedSql = "select eddw, dczskxsc from uf_jcl_kq_jqed where jb = ?";
                Map<String, Object> jqedInfo = DbTools.getSqlToMap(jqedSql, jqlx);
                //假期额度的额度单位，0-天、1-小时
                String eddw = Util.null2String(jqedInfo.get("eddw"));
                String eddwValue = "";
                //单次最小休时长
                String minDuration = Util.null2String(jqedInfo.get("dczskxsc"));
                //请假时长qjsc
                String qjsc = Util.null2String(mainTableData.get("qjsc"));
                //请假时长单位scdw，0-天、1-小时
                String scdw = Util.null2String(mainTableData.get("scdw"));
                String scdwValue = "";
                if (!"".equals(eddw) && !"".equals(minDuration)) {
                    double minDurationValue = Double.parseDouble(minDuration);
                    if (eddw.equals(AccountingUnitEnum.DAY.getKey())) {
                        minDurationValue = minDurationValue * 8;
                        eddwValue = AccountingUnitEnum.DAY.getValue();
                    } else {
                        eddwValue = AccountingUnitEnum.HOUR.getValue();
                    }
                    double qjscValue = "".equals(qjsc) ? 0 : Double.parseDouble(qjsc);
                    if (scdw.equals(AccountingUnitEnum.DAY.getKey())) {
                        qjscValue = qjscValue * 8;
                        scdwValue = AccountingUnitEnum.DAY.getValue();
                    } else {
                        scdwValue = AccountingUnitEnum.HOUR.getValue();
                    }

                    if (Double.compare(minDurationValue, qjscValue) > 0) {
                        String message = "请假时长" + qjsc + eddwValue + "，不能小于单次最小休时长" + minDuration + scdwValue;
                        log.error(message);
                        requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                        requestInfo.getRequestManager().setMessagecontent(message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }
                //更新流程明细表2
                String delteSql = "delete from " + detail2TableName + " where mainid=?";
                DbTools.update(delteSql, requestid);
                if (detailTable2.size() > 0 && !CommonUtil.insertBatch(detailTable2, detail2TableName)) {
                    //更新流程明细表2失败
                    String message = "更新流程明细表2失败";
                    log.error(message);
                    requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                    requestInfo.getRequestManager().setMessagecontent(message);
                    return Action.FAILURE_AND_CONTINUE;
                }

                //更新假期余额在途时长
                Map<String, Object> balanceMap = Maps.newHashMap();
                for (Map<String, Object> data : detailTable2) {
                    String jqye = Util.null2String(data.get("jqye"));
                    double sysc = Double.valueOf(data.get("sysc").toString());
                    double havedSysc = balanceMap.get(jqye) == null ? 0 : Double.valueOf(balanceMap.get(jqye).toString());
                    sysc = Utils.add(sysc, havedSysc);
                    balanceMap.put(jqye, sysc);
                }
                for (Map.Entry<String, Object> entry : balanceMap.entrySet()) {
                    String id = entry.getKey();
                    double ztsc = Double.valueOf(entry.getValue().toString());
                    Map<String, Object> map = (Map<String, Object>) holidayBalanceMap.get(id);

                    double havedztsc = Util.null2String(map.get("ztsc")).equals("") ? 0 : Double.valueOf(map.get("ztsc").toString());
                    double havedwxsc = Util.null2String(map.get("wxsc")).equals("") ? 0 : Double.valueOf(map.get("wxsc").toString());

                    double updatedztsc = Utils.add(havedztsc, ztsc);
                    double updatedwxsc = Utils.subtract(havedwxsc, ztsc);

                    String updateSql = "update uf_jcl_kq_jqye set wxsc=?,ztsc=? where id=?";
                    if (!DbTools.update(updateSql, updatedwxsc, updatedztsc, id)) {
                        //更新假期余额失败
                        String message = "更新假期余额失败";
                        log.error(message);
                        requestInfo.getRequestManager().setMessageid("11111" + requestid + "22222");
                        requestInfo.getRequestManager().setMessagecontent(message);
                        return Action.FAILURE_AND_CONTINUE;
                    }
                }
            }

        }catch (Exception e){
            log.error("AskForLeaveWorkFlowSubmitAction error : [{}]",e);
            return Action.FAILURE_AND_CONTINUE;
        }

        return Action.SUCCESS;
    }
}
