package com.engine.jucailinkq.attendance.attendanceanalysis.wrapper;


import com.engine.jucailinkq.attendance.attendanceanalysis.dto.clockpoint.ClockPointDTO;
import com.engine.jucailinkq.attendance.attendanceanalysis.service.*;
import com.engine.jucailinkq.attendance.attendanceanalysis.service.impl.*;
import com.engine.jucailinkq.attendance.enums.*;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.jucailinkq.common.util.Utils;
import com.engine.core.impl.Service;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class UpdateAttendanceResultWrapper extends Service {
    private AbnormalAttendanceService beLateService = ServiceUtil.getService(AbnormalAttendanceServiceImpl.class);
    private ForgetClockInService forgetClockInService = ServiceUtil.getService(ForgetClockInServiceImpl.class);
    private AskForLeaveService askForLeaveService= ServiceUtil.getService(AskForLeaveServiceImpl.class);
    private EvectionService evectionService= ServiceUtil.getService(EvectionServiceImpl.class);
    private WorkOverTimeService workOverTimeService = ServiceUtil.getService(WorkOverTimeServiceImpl.class);
    private ComprehensiveWorkingHourService comprehensiveWorkingHourService = ServiceUtil.getService(ComprehensiveWorkingHourServiceImpl.class);
    private AllowanceService allowanceService = ServiceUtil.getService(AllowanceServiceImpl.class);
    private UtilService utilService = ServiceUtil.getService(UtilServiceImpl.class);

    /**
     * 记录异常打卡
     * */
    public List<Map<String,Object>> recordAbnormalClockIn(Map<String,Object> params){
        //卡点
        List<ClockPointDTO> clcokInTimeDataList = (List<ClockPointDTO>)params.get("clcokInTimeData");
        //考勤项目
        List<Map<String,Object>> attendanceItems = (List<Map<String,Object>>)params.get("attendanceItems");
        //排班
        List<Map<String, Object>> scheduleResult = (List<Map<String,Object>>)params.get("scheduleResult");
        //分析日期
        String analysisDate = Util.null2String(params.get("analysisDate"));
        //人员
        String userId = Util.null2String(params.get("userId"));
        //请假集合
        List<Map<String,Object>> askForLeaveList = (List<Map<String,Object>>)params.get("askForLeaveList");
        //请假项目
        Map<String,Map<String,Object>> askForLeaveItems = (Map<String,Map<String,Object>>)params.get("askForLeaveItems");
        //出差集合
        List<Map<String,Object>> evectionList = (List<Map<String,Object>>)params.get("evectionList");
        //出差项目
        Map<String,Map<String,Object>> evectionItems = (Map<String,Map<String,Object>>)params.get("evectionItems");

        //以开始时间分割班次
        Map<String,List<Map<String, Object>>> startScheduleResult = scheduleResult.stream().collect(Collectors.groupingBy(e->Utils.getkssjTime(e,analysisDate)));
        //以结束时间分割班次
        Map<String,List<Map<String, Object>>> endScheduleResult = scheduleResult.stream().collect(Collectors.groupingBy(e->Utils.getjssjTime(e,analysisDate)));
        List<Map<String,Object>> resultList = Lists.newArrayList();

        for (ClockPointDTO clcokInTimedto :clcokInTimeDataList){
            //当天打卡数据
            Map<String,Object> clcokInTimeData = clcokInTimedto.getClockTime();
            //需要计算的班次打卡时间点
            String pointTime = clcokInTimedto.getClassTime();
            //start：开始打卡时间点，end：结束打卡时间点
            ClockPointEnum pointType = clcokInTimedto.getPointType();
            //empty:漏卡，equal:打卡时间和班次时间相等，before：打卡时间在班次时间之前，after：打卡时间在班次时间之后
            ClockPointEnum timeType = clcokInTimedto.getTimeType();
            //是否是请假、外出打卡
            boolean ifevectionOrAskLeave = false;
            if (ClassSegmentTypeEnum.ASK_FOR_LEAVE.getKey().equals(clcokInTimedto.getClassSegmentType()) ||
                    ClassSegmentTypeEnum.EVECTION.getKey().equals(clcokInTimedto.getClassSegmentType())){
                ifevectionOrAskLeave = true;
            }

            //班次
            Map<String, Object> classInfo = Maps.newHashMap();
            if (ClockPointEnum.START.equals(pointType) && !ifevectionOrAskLeave){
                classInfo = startScheduleResult.get(pointTime).get(0);
            }else if (ClockPointEnum.END.equals(pointType) && !ifevectionOrAskLeave){
                classInfo = endScheduleResult.get(pointTime).get(0);
            }else if (ClockPointEnum.START.equals(pointType) && ifevectionOrAskLeave){
                classInfo = endScheduleResult.get(pointTime).get(0);
            }else if (ClockPointEnum.END.equals(pointType) && ifevectionOrAskLeave){
                classInfo = startScheduleResult.get(pointTime).get(0);
            }
            if (ClockPointEnum.EMPTY.equals(timeType) || clcokInTimeData == null){
                //漏卡
                Map<String,Object> missCardParams = Maps.newHashMap();
                missCardParams.put("classInfo",classInfo);
                missCardParams.put("clcokInTimeData",clcokInTimeData);
                missCardParams.put("attendanceItems",attendanceItems);
                missCardParams.put("analysisDate",analysisDate);
                missCardParams.put("userId",userId);
                missCardParams.put("point",clcokInTimedto);
                missCardParams.put("scheduleResult",scheduleResult);
                log.debug("missCardParams classInfo: [{}],clcokInTimeData:[{}]",classInfo,clcokInTimeData);
                List<Map<String,Object>> iforgetClockIn = forgetClockInService.forgetClockIn(missCardParams);
                if (iforgetClockIn.size() >0){
                    iforgetClockIn.get(0).put("pointTime",pointTime);
                    iforgetClockIn.get(0).put("pointType",clcokInTimedto.getPointType());
                    iforgetClockIn.get(0).put("bdlx",classInfo.get("bdlx"));
                    iforgetClockIn.get(0).put("record",clcokInTimedto.isRecord());
                    iforgetClockIn.get(0).put("clcokInTimeData",clcokInTimeData);
                    resultList.add(iforgetClockIn.get(0));
                }

            }else if (ClockPointEnum.START.equals(pointType) && ClockPointEnum.AFTER.equals(timeType)){
                //迟到
                Map<String,Object> beLateParams = Maps.newHashMap();
                beLateParams.put("classInfo",classInfo);
                beLateParams.put("clcokInTimeData",clcokInTimeData);
                beLateParams.put("attendanceItems",attendanceItems);
                beLateParams.put("analysisDate",analysisDate);
                beLateParams.put("userId",userId);
                beLateParams.put("point",clcokInTimedto);
                beLateParams.put("askForLeaveList",askForLeaveList);
                beLateParams.put("askForLeaveItems",askForLeaveItems);
                beLateParams.put("evectionList",evectionList);
                beLateParams.put("evectionItems",evectionItems);
                beLateParams.put("scheduleResult",scheduleResult);
                log.debug("beLateParams classInfo: [{}],clcokInTimeData:[{}]",classInfo,clcokInTimeData);
                List<Map<String,Object>> ifBeLate = beLateService.beLate(beLateParams);
                if (ifBeLate.size() > 0){
                    ifBeLate.get(0).put("pointTime",pointTime);
                    ifBeLate.get(0).put("pointType",clcokInTimedto.getPointType());
                    ifBeLate.get(0).put("bdlx",classInfo.get("bdlx"));
                    ifBeLate.get(0).put("record",clcokInTimedto.isRecord());
                    ifBeLate.get(0).put("clcokInTimeData",clcokInTimeData);
                    resultList.add(ifBeLate.get(0));
                }
            }else if (ClockPointEnum.END.equals(pointType) && ClockPointEnum.BEFORE.equals(timeType)){
                //早退
                Map<String,Object> leaveEarlyParams = Maps.newHashMap();
                leaveEarlyParams.put("classInfo",classInfo);
                leaveEarlyParams.put("clcokInTimeData",clcokInTimeData);
                leaveEarlyParams.put("attendanceItems",attendanceItems);
                leaveEarlyParams.put("analysisDate",analysisDate);
                leaveEarlyParams.put("userId",userId);
                leaveEarlyParams.put("point",clcokInTimedto);
                leaveEarlyParams.put("askForLeaveList",askForLeaveList);
                leaveEarlyParams.put("askForLeaveItems",askForLeaveItems);
                leaveEarlyParams.put("evectionList",evectionList);
                leaveEarlyParams.put("evectionItems",evectionItems);
                leaveEarlyParams.put("scheduleResult",scheduleResult);
                log.debug("leaveEarlyParams classInfo: [{}],clcokInTimeData:[{}]",classInfo,clcokInTimeData);
                List<Map<String,Object>> ifLeaveEarly = beLateService.leaveEarly(leaveEarlyParams);
                if (ifLeaveEarly.size() > 0){
                    ifLeaveEarly.get(0).put("pointTime",pointTime);
                    ifLeaveEarly.get(0).put("pointType",clcokInTimedto.getPointType());
                    ifLeaveEarly.get(0).put("bdlx",classInfo.get("bdlx"));
                    ifLeaveEarly.get(0).put("record",clcokInTimedto.isRecord());
                    ifLeaveEarly.get(0).put("clcokInTimeData",clcokInTimeData);
                    resultList.add(ifLeaveEarly.get(0));
                }
            }

        }
        if (resultList.size() > 0){
            //漏打卡转旷工
            Map<String,Object> forgetParam = Maps.newHashMap();
            forgetParam.put("abnormalList",resultList);
            forgetParam.put("scheduleResult",scheduleResult);
            forgetParam.put("attendanceItems",attendanceItems);
            forgetParam.put("analysisDate",analysisDate);
            resultList = forgetClockInService.forgetConvertAbsenteeism(forgetParam);
        }
        log.debug("abnormalClockInList : [{}]",resultList);
        return resultList;
    }

    /**
     * 记录加班
     * @param params
     * @return
     */
    public Map<String, Object> recordWorkOverTime(Map<String,Object> params){
       return workOverTimeService.recordWorkOverTime(params);
    }


    /**
     * 请假
     * @param params
     * @return
     */
    public Map<String, Object> recordAskForLeave(Map<String,Object> params){
        //请假项目
        Map<String,Map<String,Object>> askForLeaveItems = (Map<String,Map<String,Object>>)params.get("askForLeaveItems");
        //分析日期
        String analysisDate = Util.null2String(params.get("analysisDate"));
        //排班
        List<Map<String, Object>> scheduleResult = (List<Map<String,Object>>)params.get("scheduleResult");
        //请假记录
        List<Map<String, Object>> askForLeaveList = (List<Map<String,Object>>)params.get("askForLeaveList");
        //异常记录
        List<Map<String,Object>> abnormalClockInList = (List<Map<String,Object>>)params.get("abnormalClockInList");
        //请假抵消异常
        List<Map<String,Object>> offsetAskForLeaveAnomaly = Lists.newArrayList();
        //请假-抵消异常
        Map<Map<String, Object>,List<Map<String, Object>>> askForLeaveToOffsetAbnomaly = Maps.newHashMap();

        Map<String, Object> map = Maps.newHashMap();
        List<Map<String, Object>> resultList = Lists.newArrayList();

        for (int i=0;i<askForLeaveList.size();i++){
            Map<String, Object> resultMap = Maps.newHashMap();
            String kssj = askForLeaveList.get(i).get("ksrq") + " "+askForLeaveList.get(i).get("kssj");
            String jssj = askForLeaveList.get(i).get("jsrq")+ " "+askForLeaveList.get(i).get("jssj");
            //半天请假
            String btj = Util.null2String(askForLeaveList.get(i).get("btj"));
            //请假时长
            String qjsc = Util.null2String(askForLeaveList.get(i).get("qjsc"));
            //请假时长分钟数
            int qjscMinute = "".equals(qjsc)?0:Double.valueOf(Math.ceil(Double.valueOf(qjsc)*60)).intValue();
            //请假项目
            Map<String,Object> askForLeaveItem = askForLeaveItems.get(askForLeaveList.get(i).get("jqlx"));
            //自动移除时间区间内的非工作时长
            String zdycbcndfgzsd = Util.null2String(askForLeaveItem.get("zdycbcndfgzsd"));
            //半天规则
            String btgz = Util.null2String(scheduleResult.get(0).get("btgz"));
            //同一天可抵消多个异常
            String tybcndbjlhbjs = Util.null2String(askForLeaveItem.get("tybcndbjlhbjs"));
            //作用时段
            String zysd = Util.null2String(askForLeaveItem.get("zysd"));
            //核算量
            double hsl = Double.valueOf(Util.null2String(askForLeaveItem.get("hsl")));
            //核算单位
            String hsdw = Util.null2String(askForLeaveItem.get("hsdw"));
            //是否分组呈现
            String sffzcx = Util.null2String(askForLeaveItem.get("sffzcx"));

            if (!sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                resultMap.put("item",askForLeaveList.get(i).get("jqlx"));
                resultList.add(resultMap);
            }

            Map<String,Object> param = Maps.newHashMap();
            param.put("abnormalClockInList",abnormalClockInList);
            param.put("zysd",zysd);
            param.put("scheduleResult",scheduleResult);
            param.put("analysisDate",analysisDate);
            param.put("askForLeaveItem",askForLeaveItem);
            double itemduration = 0;
            if ("".equals(Util.null2String(askForLeaveList.get(i).get("kssj"))) || "".equals(Util.null2String(askForLeaveList.get(i).get("jssj")))){
                //弹性请假,半天请假
                if (CheckBoxEnum.CHECKED.getKey().equals(btj) && (btgz.equals(HalfDayRuleREnum.BY_CLASS_SET.getKey()) || btgz.equals(HalfDayRuleREnum.FIXED_DURATION.getKey()))){
                    //半天请假
                    Map<String,Object> handleMap = askForLeaveService.askForLeaveByHalfDay(param);
                    itemduration = Double.valueOf(handleMap.get("itemduration").toString());
                    abnormalClockInList = (List<Map<String,Object>>)handleMap.get("abnormalClockInList");
                    offsetAskForLeaveAnomaly.addAll((List<Map<String,Object>>)handleMap.get("offsetAskForLeaveAnomaly"));
                    resultMap.put("itemduration",itemduration);
                    askForLeaveToOffsetAbnomaly.put(askForLeaveList.get(i),(List<Map<String,Object>>)handleMap.get("offsetAskForLeaveAnomaly"));
                    resultMap.put("item",askForLeaveList.get(i).get("jqlx"));
                    resultList.add(resultMap);
                }else if (!"".equals(qjsc) || (CheckBoxEnum.CHECKED.getKey().equals(btj) && (btgz.equals(HalfDayRuleREnum.HALF_TOTAL_DURATION.getKey()) || btgz.equals(HalfDayRuleREnum.HALF_RATED_DURATION.getKey())))){
                    if (CheckBoxEnum.CHECKED.getKey().equals(btj)){
                        if (btgz.equals(HalfDayRuleREnum.HALF_TOTAL_DURATION.getKey())){
                            qjsc = new BigDecimal(scheduleResult.get(0).get("zgzsc").toString()).divide(new BigDecimal(2),new MathContext(2, RoundingMode.HALF_UP)).toString();
                        }else{
                            qjsc = new BigDecimal(scheduleResult.get(0).get("edsc").toString()).divide(new BigDecimal(2),new MathContext(2, RoundingMode.HALF_UP)).toString();
                        }
                    }
                    qjscMinute = "".equals(qjsc)?0:Double.valueOf(Math.ceil(Double.valueOf(qjsc)*60)).intValue();
                    //时长请假
                    itemduration = Utils.getItemduration(hsl,hsdw,qjscMinute,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));

                    if (!sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                        resultMap.put("itemduration",itemduration);
                    }

                    param.put("qjsc",qjsc);
                    param.put("tybcndbjlhbjs",tybcndbjlhbjs);
                    if (abnormalClockInList.size()>0){
                        Map<String,Object> map1 = askForLeaveService.askForLeaveByDurationTime(param);
                        abnormalClockInList =(List<Map<String,Object>>)map1.get("abnormalClockInList");
                        List<Map<String,Object>> offsetAskForLeaveAnomalyList = (List<Map<String,Object>>)map1.get("offsetAskForLeaveAnomaly");
                        offsetAskForLeaveAnomaly.addAll(offsetAskForLeaveAnomalyList);
                        askForLeaveToOffsetAbnomaly.put(askForLeaveList.get(i),offsetAskForLeaveAnomalyList);


                        //按时长请假，将标记请假作用的时段上的异常 按标准逻辑进行冲销，如果冲销后还有多余时长，如请假时长为1.5小时，但员工当天有两个时段上各有不到30分钟的异常，此时每个时段0.5小时需要冲销，多出来的0.5小时放哪里，放到异常多的那个时段上
                        //有几个抵消异常计入几个请假考勤项目
                        if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                            int total = offsetAskForLeaveAnomalyList.stream().mapToInt(e->Integer.valueOf(e.get("betweenMinutes").toString())).sum();
                            int more = 0;
                            if (total < qjscMinute){
                                more = qjscMinute-total;
                            }
                            List<Map<String,Object>> sortOffsetAskForLeaveAnomalyList = offsetAskForLeaveAnomalyList.stream().sorted(Comparator.comparing(e->Integer.valueOf(e.get("betweenMinutes").toString()))).collect(Collectors.toList());
                            for (int j=0;j<sortOffsetAskForLeaveAnomalyList.size();j++){
                                //异常班段类型
                                String bdlx = sortOffsetAskForLeaveAnomalyList.get(i).get("bdlx").toString();
                                //异常时间
                                int time = Integer.valueOf(sortOffsetAskForLeaveAnomalyList.get(i).get("betweenMinutes").toString());
                                if (j == sortOffsetAskForLeaveAnomalyList.size()-1){
                                    time = time+more;
                                }
                                Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(askForLeaveItem,bdlx);
                                if (item != null){
                                    itemduration = Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),time,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                                    Map<String, Object> itemMap = Maps.newHashMap();
                                    itemMap.put("itemduration",itemduration);
                                    itemMap.put("item",item.get("keyid"));
                                    resultList.add(itemMap);
                                }
                            }
                        }
                    }else {
                        if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                            Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(askForLeaveItem,ClassSegmentTypeEnum.WORK_TIME.getKey());
                            if (item != null){
                                Map<String, Object> itemMap = Maps.newHashMap();
                                itemduration = Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),qjscMinute,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                                itemMap.put("itemduration",itemduration);
                                itemMap.put("item",item.get("keyid"));
                                resultList.add(itemMap);
                            }
                        }
                    }
                }
            }else {
                //按照开始时间，结束时间请假
                int timeMinutes = getTimeByWorkFor(zysd,zdycbcndfgzsd,scheduleResult,kssj,jssj,analysisDate);
                if (timeMinutes > qjscMinute){
                    timeMinutes = qjscMinute;
                }
                log.debug("recordAskForLeave timeMinutes ：[{}] ,hsl:{},hsdw",timeMinutes,hsl,hsdw);
                itemduration = Utils.getItemduration(hsl,hsdw,timeMinutes,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                param.put("kssj",kssj);
                param.put("jssj",jssj);
                if (abnormalClockInList.size()>0){
                    Map<String,Object> map1 = askForLeaveService.askForLeaveByTime(param);
                    abnormalClockInList = (List<Map<String,Object>>)map1.get("abnormalClockInList");
                    offsetAskForLeaveAnomaly.addAll((List<Map<String,Object>>)map1.get("offsetAskForLeaveAnomaly"));
                    askForLeaveToOffsetAbnomaly.put(askForLeaveList.get(i),(List<Map<String,Object>>)map1.get("offsetAskForLeaveAnomaly"));
                }
                if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                    //按时间区间请假时 将连接的同一类型时段设置一种假别 计算出分钟时长后按核算量算出核算时长及单位即可
                    Map<String,Object> proportionMap = Utils.getAskLeaveAndEvctionProportion(kssj,jssj,scheduleResult,analysisDate);
                    for (Map.Entry<String,Object> entry: proportionMap.entrySet()){
                        String bdlx = entry.getKey();
                        int betweenTimes = Integer.valueOf(entry.getValue().toString());
                        Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(askForLeaveItem,bdlx);
                        if (item != null){
                            Map<String, Object> itemMap = Maps.newHashMap();
                            itemMap.put("itemduration",Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),betweenTimes,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString())));
                            itemMap.put("item",item.get("keyid"));
                            resultList.add(itemMap);
                        }
                    }
                }else {
                    resultMap.put("itemduration",itemduration);
                }
            }
        }
        map.put("resultList",resultList);
        map.put("abnormalClockInList",abnormalClockInList);
        map.put("offsetAskForLeaveAnomaly",offsetAskForLeaveAnomaly);
        map.put("askForLeaveToOffsetAbnomaly",askForLeaveToOffsetAbnomaly);
        return map;
    }

    /**
     * 外出
     * @param params
     * @return
     */
    public Map<String, Object> recordEvection(Map<String,Object> params){

        //外出项目
        Map<String,Map<String,Object>> evectionItems = (Map<String,Map<String,Object>>)params.get("evectionItems");
        //排班
        List<Map<String, Object>> scheduleResult = (List<Map<String,Object>>)params.get("scheduleResult");
        //分析日期
        String analysisDate = Util.null2String(params.get("analysisDate"));
        //出差记录
        List<Map<String, Object>> evectionList = (List<Map<String,Object>>)params.get("evectionList");
        //异常记录
        List<Map<String,Object>> abnormalClockInList = (List<Map<String,Object>>)params.get("abnormalClockInList");
        //外出抵消异常
        List<Map<String,Object>> offsetEvectionAnomaly = Lists.newArrayList();
        //外出-抵消异常
        Map<Map<String, Object>,List<Map<String,Object>>> evectionToOffsetAbnomaly = Maps.newHashMap();

        Map<String, Object> map = Maps.newHashMap();
        List<Map<String, Object>> resultList = Lists.newArrayList();

        for (int i=0;i<evectionList.size();i++){
            Map<String, Object> resultMap = Maps.newHashMap();
            String kssj = evectionList.get(i).get("ksrq") + " "+evectionList.get(i).get("kssj");
            String jssj = evectionList.get(i).get("jsrq")+ " "+evectionList.get(i).get("jssj");
            //半天请假
            String btj = Util.null2String(evectionList.get(i).get("btcc"));
            //出差时长
            String ccsc = Util.null2String(evectionList.get(i).get("ccsc"));
            //出差时长分钟数
            int ccscMinute = "".equals(ccsc)?0:Double.valueOf(Math.ceil(Double.valueOf(ccsc)*60)).intValue();
            //请假项目
            Map<String,Object> evectionItem = evectionItems.get(evectionList.get(i).get("cclx"));
            //自动移除时间区间内的非工作时长
            String zdycbcndfgzsd = Util.null2String(evectionItem.get("zdycbcndfgzsd"));
            //半天规则
            String btgz = Util.null2String(scheduleResult.get(0).get("btgz"));
            //同一天可抵消多个异常
            String tybcndbjlhbjs = Util.null2String(evectionItem.get("tybcndbjlhbjs"));
            //核算量
            double hsl = Double.valueOf(Util.null2String(evectionItem.get("hsl")));
            //核算单位
            String hsdw = Util.null2String(evectionItem.get("hsdw"));
            //作用时间段
            String zysd = Util.null2String(evectionItem.get("zysd"));
            //是否分组呈现
            String sffzcx = Util.null2String(evectionItem.get("sffzcx"));

            if (!sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                resultList.add(resultMap);
                resultMap.put("item",evectionList.get(i).get("cclx"));
            }

            Map<String,Object> param = Maps.newHashMap();
            param.put("abnormalClockInList",abnormalClockInList);
            param.put("zysd",zysd);
            param.put("scheduleResult",scheduleResult);
            param.put("analysisDate",analysisDate);
            param.put("evectionItem",evectionItem);
            double itemduration = 0;
            if ("".equals(Util.null2String(evectionList.get(i).get("kssj"))) || "".equals(Util.null2String(evectionList.get(i).get("jssj")))){
                //弹性请假,半天出差
                if (CheckBoxEnum.CHECKED.getKey().equals(btj) && (btgz.equals(HalfDayRuleREnum.BY_CLASS_SET.getKey()) || btgz.equals(HalfDayRuleREnum.FIXED_DURATION.getKey()))){
                    //半天出差
                    Map<String,Object> handleMap = evectionService.evectionByHalfDay(param);
                    itemduration = Double.valueOf(handleMap.get("itemduration").toString());
                    abnormalClockInList = (List<Map<String,Object>>)handleMap.get("abnormalClockInList");
                    offsetEvectionAnomaly.addAll((List<Map<String,Object>>)handleMap.get("offsetEvectionAnomaly"));
                    resultMap.put("itemduration",itemduration);
                    evectionToOffsetAbnomaly.put(evectionList.get(i),(List<Map<String,Object>>)handleMap.get("offsetEvectionAnomaly"));
                    resultMap.put("item",evectionList.get(i).get("cclx"));
                    resultList.add(resultMap);
                }else if (!"".equals(ccsc) || (CheckBoxEnum.CHECKED.getKey().equals(btj) && (btgz.equals(HalfDayRuleREnum.HALF_TOTAL_DURATION.getKey()) || btgz.equals(HalfDayRuleREnum.HALF_RATED_DURATION.getKey())))){
                    //时长出差
                    itemduration = Utils.getItemduration(hsl,hsdw,ccscMinute,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                    if (!sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                        resultMap.put("itemduration",itemduration);
                    }

                    param.put("ccsc",ccsc);
                    param.put("tybcndbjlhbjs",tybcndbjlhbjs);
                    if (abnormalClockInList.size()>0){
                        Map<String,Object> map1 =evectionService.evectionByDurationTime(param);
                        abnormalClockInList = (List<Map<String,Object>>)map1.get("abnormalClockInList");
                        List<Map<String,Object>> offsetEvectionAnomalyList = (List<Map<String,Object>>)map1.get("offsetEvectionAnomaly");
                        offsetEvectionAnomaly.addAll(offsetEvectionAnomalyList);
                        evectionToOffsetAbnomaly.put(evectionList.get(i),offsetEvectionAnomalyList);

                        //按时长请假，将标记请假作用的时段上的异常 按标准逻辑进行冲销，如果冲销后还有多余时长，如请假时长为1.5小时，但员工当天有两个时段上各有不到30分钟的异常，此时每个时段0.5小时需要冲销，多出来的0.5小时放哪里，放到异常多的那个时段上
                        //有几个抵消异常计入几个请假考勤项目
                        if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                            int total = offsetEvectionAnomalyList.stream().mapToInt(e->Integer.valueOf(e.get("betweenMinutes").toString())).sum();
                            int more = 0;
                            if (total < ccscMinute){
                                more = ccscMinute-total;
                            }
                            List<Map<String,Object>> sortOffsetEvectionAnomalyList = offsetEvectionAnomalyList.stream().sorted(Comparator.comparing(e->Integer.valueOf(e.get("betweenMinutes").toString()))).collect(Collectors.toList());
                            for (int j=0;j<sortOffsetEvectionAnomalyList.size();j++){
                                //异常班段类型
                                String bdlx = sortOffsetEvectionAnomalyList.get(i).get("bdlx").toString();
                                //异常时间
                                int time = Integer.valueOf(sortOffsetEvectionAnomalyList.get(i).get("betweenMinutes").toString());
                                if (j == sortOffsetEvectionAnomalyList.size()-1){
                                    time = time+more;
                                }
                                Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(evectionItem,bdlx);
                                if (item != null){
                                    itemduration = Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),time,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                                    Map<String, Object> itemMap = Maps.newHashMap();
                                    itemMap.put("itemduration",itemduration);
                                    itemMap.put("item",item.get("keyid"));
                                    resultList.add(itemMap);
                                }
                            }
                        }

                    }else {
                        if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                            Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(evectionItem,ClassSegmentTypeEnum.WORK_TIME.getKey());
                            if (item != null){
                                Map<String, Object> itemMap = Maps.newHashMap();
                                itemduration = Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),ccscMinute,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                                itemMap.put("itemduration",itemduration);
                                itemMap.put("item",item.get("keyid"));
                                resultList.add(itemMap);
                            }
                        }
                    }
                }
            }else {
                //按照开始时间，结束时间出差


                int timeMinutes = getTimeByWorkFor(zysd,zdycbcndfgzsd,scheduleResult,kssj,jssj,analysisDate);
                if (timeMinutes > ccscMinute){
                    timeMinutes = ccscMinute;
                }
                log.debug("recordEvection timeMinutes ：[{}] ,hsl:{},hsdw",timeMinutes,hsl,hsdw);
                itemduration = Utils.getItemduration(hsl,hsdw,timeMinutes,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString()));
                param.put("kssj",kssj);
                param.put("jssj",jssj);
                if (abnormalClockInList.size()>0){
                    Map<String,Object> map1 = evectionService.evectionByTime(param);
                    abnormalClockInList = (List<Map<String,Object>>)map1.get("abnormalClockInList");
                    offsetEvectionAnomaly.addAll((List<Map<String,Object>>)map1.get("offsetEvectionAnomaly"));
                    evectionToOffsetAbnomaly.put(evectionList.get(i),(List<Map<String,Object>>)map1.get("offsetEvectionAnomaly"));
                }

                if (sffzcx.equals(CheckBoxEnum.CHECKED.getKey())){
                    //按时间区间请假时 将连接的同一类型时段设置一种假别 计算出分钟时长后按核算量算出核算时长及单位即可
                    Map<String,Object> proportionMap = Utils.getAskLeaveAndEvctionProportion(kssj,jssj,scheduleResult,analysisDate);
                    for (Map.Entry<String,Object> entry: proportionMap.entrySet()){
                        String bdlx = entry.getKey();
                        int betweenTimes = Integer.valueOf(entry.getValue().toString());
                        Map<String,Object> item = CommonUtil.assembleAskForOrEvectionItem(evectionItem,bdlx);
                        if (item != null){
                            Map<String, Object> itemMap = Maps.newHashMap();
                            itemMap.put("itemduration",Utils.getItemduration(Double.valueOf(Util.null2String(item.get("hsl"))),Util.null2String(item.get("hsdw")),betweenTimes,AccountingUnitEnum.MINUTES,Double.valueOf(scheduleResult.get(0).get("edsc").toString())));
                            itemMap.put("item",item.get("keyid"));
                            resultList.add(itemMap);
                        }
                    }
                }else {
                    resultMap.put("itemduration",itemduration);
                }
            }
        }
        map.put("resultList",resultList);
        map.put("abnormalClockInList",abnormalClockInList);
        map.put("offsetEvectionAnomaly",offsetEvectionAnomaly);
        map.put("evectionToOffsetAbnomaly",evectionToOffsetAbnomaly);
        return map;
    }

    /**
     * 没有排班
     * @param params
     * @return
     */
    public Map<String,Object> recordNoClass(Map<String,Object> params){
        //分析日期
        String analysisDate = Util.null2String(params.get("analysisDate"));
        //人员
        String userId = Util.null2String(params.get("userId"));
        //综合工时
        List<Map<String,Object>> workHourItems = (List<Map<String,Object>>)params.get("workHourItems");
        //津贴
        Map<String,Object> allowanceMap = (Map<String,Object>)params.get("allowanceMap");

        log.debug("userId : {} ,analysisDate: {} have no class",userId,analysisDate);

        Map<String,Object> recordParam = Maps.newHashMap();
        recordParam.put("userId",userId);
        recordParam.put("analysisDate",analysisDate);
        recordParam.put("recordData",Lists.newArrayList());
        String rqlx = CommonUtil.getRqlx(userId,analysisDate);
        recordParam.put("rqlx",rqlx);

        recordParam.put("classInfo",Lists.newArrayList());
        recordParam.put("recordDataTime",Maps.newHashMap());
        recordParam.put("attendanceDuration",0);
        recordParam.put("formmodeIdMap",Utils.getFormmodeIdMap());
        List<Map<String, Object>> recordDataList = Lists.newArrayList();;
        if (allowanceMap.get("ifnotWork") != null){
            //次日免班
            recordParam.put("cqzt",CheckBoxEnum.UNCHECKED.getKey());
            utilService.recordItem(recordParam);
            return recordParam;
        }
        if (rqlx.equals(DateTypeEnum.WORK_DAY.getKey()) || rqlx.equals(DateTypeEnum.CHANGECLASS.getKey())){
            recordParam.put("cqzt",CheckBoxEnum.CHECKED.getKey());
            recordDataList.add(new HashMap(){{
                put("item",SystemItemEnum.NO_SCHEDULING.getKey());
                put("itemduration","NULL");
            }});
        }else {
            recordParam.put("cqzt",CheckBoxEnum.UNCHECKED.getKey());
            recordParam.put("sfxx",CheckBoxEnum.CHECKED.getKey());

        }


        if (workHourItems != null && workHourItems.size() >0 ){
            //核算工时的日期类型
            String hsgsdrqlx = Util.null2String(workHourItems.get(0).get("hsgsdrqlx"));

            rqlx = Utils.getDateType(analysisDate,Util.null2String(workHourItems.get(0).get("qyrl")));
            params.put("workHourItem",workHourItems.get(0));
            if (CommonUtil.ifContainStr(hsgsdrqlx,rqlx,",")){
                //走综合工时
                return comprehensiveWorkingHourService.excuteByWorkHour(params);
            }else {
                //没有排班
                recordParam.put("recordData",recordDataList);
                utilService.recordItem(recordParam);
            }
        }else {
            //没有排班
            recordParam.put("recordData",recordDataList);
             utilService.recordItem(recordParam);
        }


        return recordParam;
    }


    /**
     * 津贴处理
     * @param params
     * @return
     */
    public Map<String,Object> allowanceHandle(Map<String,Object> params){
        return allowanceService.allowanceHandle(params);
    }

    /**
     * 津贴处理
     * @param params
     * @return
     */
    public Map<String,Object> removeAbnormal(Map<String,Object> params){
        return allowanceService.removeAbnormal(params);
    }

    /**
     * 根据班次获得请假记录以及请假排班
     * @param params
     * @return
     */
    public Map<String,Object> getAskForLeave(Map<String,Object> params){
        return askForLeaveService.getAskForLeave(params);
    }
    /**
     * 根据班次获得出差记录以及出差排班
     * @param params
     * @return
     */
    public Map<String,Object> getEvection(Map<String,Object> params){
        return evectionService.getEvection(params);
    }


    /**
     * 休息班次，直接算成成休息
     */
    public void recordRest(Map<String,Object> recordParam){
        recordParam.put("recordData",Lists.newArrayList());
        recordParam.put("recordDataTime",Maps.newHashMap());
        recordParam.put("attendanceDuration",0);
        recordParam.put("cqzt",CheckBoxEnum.UNCHECKED.getKey());
        recordParam.put("sfxx",CheckBoxEnum.CHECKED.getKey());
        utilService.recordItem(recordParam);
    }

    public int getTimeByWorkFor(String zysd,String zdycbcndfgzsd,List<Map<String, Object>> scheduleResult,String kssj,String jssj,String analysisDate){
        List<Map<String, Object>> reusltList = scheduleResult.stream().filter(e->(zysd.contains(Utils.getWorkFor(e.get("bdlx").toString())) && !Utils.ifRestClassSegment(e.get("bdlx").toString())) ||
                (!CheckBoxEnum.CHECKED.getKey().equals(zdycbcndfgzsd) && Utils.ifRestClassSegment(e.get("bdlx").toString()))).collect(Collectors.toList());

        return Utils.removeTime(kssj,jssj,reusltList,analysisDate);
    }


}
