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


import com.engine.jucailinkq.attendance.attendanceanalysis.service.UtilService;
import com.engine.jucailinkq.attendance.attendanceanalysis.service.impl.UtilServiceImpl;
import com.engine.jucailinkq.attendance.attendanceanalysis.wrapper.AttendanceAnalysisWrapper;
import com.engine.jucailinkq.attendance.attendanceplan.service.AttendancePlanService;
import com.engine.jucailinkq.attendance.attendanceplan.service.impl.AttendancePlanServiceImpl;
import com.engine.jucailinkq.attendance.workflow.service.AllowanceService;
import com.engine.jucailinkq.attendance.workflow.service.impl.AllowanceServiceImpl;
import com.engine.common.util.*;
import com.engine.jucailinkq.common.util.CommonUtil;
import com.engine.jucailinkq.common.util.DateUtil;
import com.engine.jucailinkq.common.util.DbTools;
import com.engine.jucailinkq.common.util.Utils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;

import java.time.ZoneOffset;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class AttendanceAnalysisJob extends BaseCronJob {
    private AttendancePlanService basicsetService = ServiceUtil.getService(AttendancePlanServiceImpl.class);

    private AttendanceAnalysisWrapper attendanceAnalysisService = ServiceUtil.getService(AttendanceAnalysisWrapper.class);

    private AllowanceService allowanceService = ServiceUtil.getService(AllowanceServiceImpl.class);

    private UtilService utilService = ServiceUtil.getService(UtilServiceImpl.class);

    private String executeDate;
    @Override
    public void execute() {
        log.debug("********AttendanceAnalysisJob  start********");

        if (executeDate == null || "".equals(executeDate)){
            executeDate = DateUtil.getCurrentDate();
        }

        String queryUserSql = "select id,departmentid,subcompanyid1 from hrmresource where status <> '5' and status <> '4' and status <> '7'";
        List<Map<String,Object>> userList = DbTools.getSqlToList(queryUserSql);


        Map<String, Object> getAttendanceparam = Maps.newHashMap();
        getAttendanceparam.put("userList",userList);
        getAttendanceparam.put("executeDate",executeDate);

        Map<String, Object> attendanceCycle = utilService.getAttendanceCycle(getAttendanceparam);
        Set<String> allDates = Sets.newHashSet();
        for (Map.Entry<String, Object> entry : attendanceCycle.entrySet()){
            allDates.addAll((Set<String>)entry.getValue());
        }
        List<String> allDateList = Lists.newArrayList(allDates);
        allDateList = allDateList.stream().sorted(Comparator.comparing(e -> DateUtil.getTime(e).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());


        String sql = "select id,userid,signdate,signtime from hrmschedulesign where isincom=1 and signdate >= ? and signdate <= ? order by signdate,signtime";
        List<Map<String,Object>> dataList = DbTools.getSqlToList(sql,DateUtil.beforeDay(allDateList.get(0),2),executeDate);
        //补打卡记录
        sql = "select id,bdkry userid,dkrq signdate,dksj signtime from uf_jcl_kq_bdkjl where dkrq >= ? and dkrq <= ? and jlzt=1 order by dkrq,dksj";
        List<Map<String,Object>> makeUpList = DbTools.getSqlToList(sql,DateUtil.beforeDay(allDateList.get(0),2),executeDate);
        if (makeUpList.size() > 0){
            dataList.addAll(makeUpList);
        }
        dataList = dataList.stream().sorted(Comparator.comparing(e->DateUtil.getTime(e.get("signdate")+" "+e.get("signtime")).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());
        Map<String, List<Map<String,Object>>> collect = dataList.stream().collect(Collectors.groupingBy(e -> Util.null2String(e.get("userid"))));
        sql = "select sjzt,sgsj,ygid,rq from uf_jcl_kq_cqjg where rq in ("+String.join(",",allDateList)+")";
        List<Map<String,Object>> attendaceResult = DbTools.getSqlToList(sql);
        Map<String,List<Map<String,Object>>> attendaceGroupById = attendaceResult.stream().collect(Collectors.groupingBy(e->e.get("ygid").toString()));


        //初始化扩展类
        CommonUtil.initExtensionClassHolder();

        for (Map<String,Object> userMap:userList){
            String userId = Util.null2String(userMap.get("id"));
            List<String> analysisDateList = Lists.newArrayList((Set<String>)attendanceCycle.get(userId));
            analysisDateList = analysisDateList.stream().sorted(Comparator.comparing(e -> DateUtil.getTime(e).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());
            //日期对应的打卡数据
            Map<String,Map<String,Object>> clockInTimeMap = Maps.newHashMap();
            /**获得人员考勤项目*/
            Map<String,Object> paramMap = Maps.newHashMap();
            paramMap.put("startDate",executeDate);
            paramMap.put("endDate",executeDate);
            paramMap.put("resourceId",userId);
            Map<String,Object> dataMap = basicsetService.getAttendanceItemsByPerson(paramMap);
            List<Map<String,Object>> attendanceItems = (List<Map<String,Object>>)dataMap.get("data");
            /**
             *获得人员综合工时
             */
            Map<String,Object> workHourdataMap = basicsetService.getWorkHoursItemByPerson(paramMap);
            List<Map<String,Object>> workHourItems = (List<Map<String,Object>>)workHourdataMap.get("data");

            Map<String, List<Map<String, Object>>> attendaceResultMap = Maps.newHashMap();
            List<Map<String, Object>> attendaceResultByUser =  attendaceGroupById.get(userId);
            if (attendaceResultByUser != null && attendaceResultByUser.size() > 0) {
                attendaceResultMap = attendaceResultByUser.stream().collect(Collectors.groupingBy(e -> e.get("rq").toString()));
            }

            attendanceAnalysisService.attendanceAnalysis(userId,analysisDateList,collect.get(userMap.get("id")),attendanceItems,workHourItems,clockInTimeMap,attendaceResultMap);
        }
        Map<String,Object> param = Maps.newHashMap();
        param.put("startDate",DateUtil.beforeDay(allDateList.get(0),2));
        param.put("endDate",executeDate);
        allowanceService.addAllowanceRecords(param);
        log.debug("********AttendanceAnalysisJob  end********");
    }
}
