package com.engine.attendance.attendanceanalysis.cmd;

import com.engine.attendance.enums.CheckBoxEnum;
import com.engine.attendance.enums.ClassSegmentTypeEnum;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.common.util.DateUtil;
import com.engine.common.util.DbTools;
import com.engine.common.util.Utils;
import com.engine.core.interceptor.CommandContext;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;

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

/**
 * 计算获取归属于分析日期的打卡数据
 */
@Slf4j
public class GetClockInTimeListCmd extends AbstractCommonCommand<Map<String,Object>> {
    public GetClockInTimeListCmd(Map<String, Object> params){
        this.params=params;
    }
    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        //打卡日期
        String needGetDate = Util.null2String(params.get("date"));
        //打卡数据
        List<Map<String,Object>> clockInTimeList = (List<Map<String,Object>>)params.get("clockInTimeList");
        //班次数据
        Map<String, List<Map<String,Object>>> schedulingResultCollect = (Map<String, List<Map<String,Object>>>)params.get("schedulingResultCollect");
        //出勤结果日期对应的进出数据
        Map<String,Map<String,Object>> clockInTimeMap = (Map<String,Map<String,Object>>)params.get("clockInTimeMap");
        //当天班次
        List<Map<String,Object>> needGetDateScheduling = schedulingResultCollect.get(needGetDate);
        //
        Map<String, List<Map<String,Object>>> collect = (Map<String, List<Map<String,Object>>>)params.get("clockInTimeCollect");
        //分析人员
        String userId = Util.null2String(params.get("userId"));

        //没有打卡记录
        if (clockInTimeList == null ||clockInTimeList.size() == 0){
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",Lists.newArrayList());

            return resultMap;
        }

        if (needGetDateScheduling == null || needGetDateScheduling.size() == 0){
            //没有排班，默认取当天和第二天的打卡数据
            List<Map<String,Object>> effectiveclockInTimeList = Lists.newArrayList();
            if (collect.get(needGetDate) != null){
                effectiveclockInTimeList.addAll(collect.get(needGetDate));
            }
            if (collect.get(DateUtil.AfterDay(needGetDate,1)) != null){
                effectiveclockInTimeList.addAll(collect.get(DateUtil.AfterDay(needGetDate,1)));
            }
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",effectiveclockInTimeList);

            return resultMap;
        }


        List<Map<String, Object>> scheduleList = needGetDateScheduling.stream().filter(e -> {
            if (!ClassSegmentTypeEnum.REST_AND_DINE.getKey().equals(e.get("bdlx")) && !ClassSegmentTypeEnum.REST_PERIOD.getKey().equals(e.get("bdlx")) &&
                    !ClassSegmentTypeEnum.DINING_PERIOD.getKey().equals(e.get("bdlx")) && (CheckBoxEnum.CHECKED.getKey().equals(e.get("ksdk")) || CheckBoxEnum.CHECKED.getKey().equals(e.get("jsdk")))){
                return true;
            }else {
                return false;
            }
        }).collect(Collectors.toList());
        if (scheduleList == null || scheduleList.size() == 0){
            //没有排班，默认取当天和第二天的打卡数据
            List<Map<String,Object>> effectiveclockInTimeList = Lists.newArrayList();
            if (collect.get(needGetDate) != null){
                effectiveclockInTimeList.addAll(collect.get(needGetDate));
            }
            if (collect.get(DateUtil.AfterDay(needGetDate,1)) != null){
                effectiveclockInTimeList.addAll(collect.get(DateUtil.AfterDay(needGetDate,1)));
            }
            Map<String,Object> resultMap = Maps.newHashMap();
            resultMap.put("resultList",effectiveclockInTimeList);

            return resultMap;
        }

        Map<String, Object> firstKsdkSchedule = null;
        Map<String, Object> lastKsdkSchedule = null;
        for (int i=0;i<scheduleList.size();i++){
            if (CheckBoxEnum.CHECKED.getKey().equals(scheduleList.get(i).get("ksdk"))){
                firstKsdkSchedule = scheduleList.get(i);
                break;
            }
        }
        for (int j=scheduleList.size()-1;j>=0;j--){
            if (CheckBoxEnum.CHECKED.getKey().equals(scheduleList.get(j).get("jsdk"))){
                lastKsdkSchedule = scheduleList.get(j);
                break;
            }
        }
        //当天班次最早会打卡的时间点
        String earliestTime = "";
        if (firstKsdkSchedule != null){
            earliestTime = Utils.getkssjEarliestTime(firstKsdkSchedule,needGetDate);
        }
        String earlyTime = Utils.getkssjEarliestTime(needGetDateScheduling.get(0),needGetDate);
        if (earliestTime == "" || DateUtil.getTime(earliestTime).compareTo(DateUtil.getTime(earlyTime)) > 0){
            earliestTime = earlyTime;
        }
        //当天班次最晚会打卡的时间点
        String lastestTime = "";
        if (lastKsdkSchedule != null){
            lastestTime = Utils.getjssjLastestTime(lastKsdkSchedule,needGetDate);
        }
        String lastTime = Utils.getjssjLastestTime(needGetDateScheduling.get(needGetDateScheduling.size()-1),needGetDate);
        if (lastestTime == "" || DateUtil.getTime(lastestTime).compareTo(DateUtil.getTime(lastTime)) < 0){
            lastestTime = lastTime;
        }


        if (DateUtil.getTime(earliestTime).compareTo(DateUtil.getTime(needGetDate+" 00:00:00")) < 0){
            //当最早打卡时间点在前一天时，获取前一天的出勤结果打卡数据
            String earliestDate = earliestTime.split(" ")[0];
            Map<String,Object> clockIntime = clockInTimeMap.get(earliestDate);
            if (clockIntime == null){
                String sql = "select rq,j1,c1,j2,c2,j3,c3,j4,c4,j5,c5,j6,c6,j7,c7,j8,c8 from uf_jcl_kq_cqjg where ygid=? and rq>=? and rq<=?";
                List<Map<String,Object>> attendanceResult = DbTools.getSqlToList(sql,userId,DateUtil.beforeDay(earliestDate,1),earliestDate);
                Map<String, List<Map<String,Object>>> attendanceCollect = attendanceResult.stream().collect(Collectors.groupingBy(e->e.get("rq").toString()));
                clockIntime = attendanceCollect.get(earliestDate) == null?null:attendanceCollect.get(earliestDate).get(0);
                if (clockIntime == null){
                    //取不到当天的就再往前取一天
                    clockIntime = attendanceCollect.get(DateUtil.beforeDay(earliestDate,1)) == null?null:attendanceCollect.get(DateUtil.beforeDay(earliestDate,1)).get(0);
                }
            }
            if (clockIntime !=null){
                for (int i=8;i>0;i--){
                    String in  = Util.null2String(clockIntime.get("j"+i));
                    String out  = Util.null2String(clockIntime.get("c"+i));
                    if (!"".equals(out) && !"NULL".equals(out)){
                        if (DateUtil.getTime(out).compareTo(DateUtil.getTime(earliestTime)) > 0){
                            earliestTime = out;
                        }
                        break;
                    }else if (!"".equals(in) && !"NULL".equals(in)){
                        if (DateUtil.getTime(in).compareTo(DateUtil.getTime(earliestTime)) > 0){
                            earliestTime = in;
                        }
                        break;
                    }
                }
            }
        }
        log.info("earliestTime :[{}],lastestTime: [{}]",earliestTime,lastestTime);
        String finalEarliestTime = earliestTime;
        String finalLastestTime = lastestTime;
        List<Map<String,Object>> effectiveclockInTimeList = clockInTimeList.stream().filter(e->{
            String signDate = e.get("signdate")+" "+e.get("signtime");
            if ("".equals(Util.null2String(finalEarliestTime)) && "".equals(Util.null2String(finalLastestTime))){
                return true;
            }else if ("".equals(Util.null2String(finalEarliestTime)) && !"".equals(Util.null2String(finalLastestTime))){
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalLastestTime)) <=0){
                    return true;
                }else {
                    return false;
                }

            }else if (!"".equals(Util.null2String(finalEarliestTime)) && "".equals(Util.null2String(finalLastestTime))){
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalEarliestTime)) >=0){
                    return true;
                }else {
                    return false;
                }

            }else{
                if (DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalEarliestTime)) >=0 && DateUtil.getTime(signDate).compareTo(DateUtil.getTime(finalLastestTime)) <=0){
                    return true;
                }else {
                    return false;
                }
            }
        }).collect(Collectors.toList());
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("resultList",effectiveclockInTimeList);

        return resultMap;
    }
}
