package com.mortals.xhx.module.attendance.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.common.code.GoWorkResultEnum;
import com.mortals.xhx.common.code.LeaveTypeEnum;
import com.mortals.xhx.common.code.OffWorkResultEnum;
import com.mortals.xhx.common.code.ProcessStatusEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.HomeStatInfo;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.attendance.dao.AttendanceSummaryDao;
import com.mortals.xhx.module.attendance.model.*;
import com.mortals.xhx.module.attendance.model.vo.AttendanceSummaryQuery;
import com.mortals.xhx.module.attendance.model.vo.ErrorSummaryVo;
import com.mortals.xhx.module.attendance.model.vo.LeaveSummaryVo;
import com.mortals.xhx.module.attendance.model.vo.VacationBalanceSummaryVo;
import com.mortals.xhx.module.attendance.service.AttendanceLeaveRecordService;
import com.mortals.xhx.module.attendance.service.AttendanceRecordService;
import com.mortals.xhx.module.attendance.service.AttendanceStaffStatService;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.holiday.model.HolidayEntity;
import com.mortals.xhx.module.holiday.model.HolidayQuery;
import com.mortals.xhx.module.holiday.service.HolidayService;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.attendance.dao.AttendanceStatDao;
import com.mortals.xhx.module.attendance.service.AttendanceStatService;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * AttendanceStatService
 * 考勤汇总信息 service实现
 *
 * @author zxfei
 * @date 2023-04-08
 */
@Service("attendanceStatService")
public class AttendanceStatServiceImpl extends AbstractCRUDServiceImpl<AttendanceStatDao, AttendanceStatEntity, Long> implements AttendanceStatService {
    @Autowired
    private AttendanceStaffStatService attendanceStaffStatService;
    @Autowired
    private AttendanceSummaryDao attendanceSummaryDao;
    @Autowired
    private HolidayService holidayService;

    @Autowired
    private StaffService staffService;
    @Autowired
    private DeptService deptService;

    @Autowired
    private AttendanceRecordService recordService;

    @Autowired
    private AttendanceLeaveRecordService leaveRecordService;
    @Autowired
    private ICacheService cacheService;

    @Override
    protected void findAfter(AttendanceStatEntity entity, Context context, List<AttendanceStatEntity> list) throws AppException {
        // DateUtil.parse(entity.getStartTime()).year();
        //DateUtil.parse(entity.getStartTime()).month();
        //开始时间
        String startYears = entity.getStartTime().split("-", 0)[0];
        Long startYear = Long.valueOf(startYears);
        String startMonths = entity.getStartTime().split("-", 0)[1];
        Long startMonth = Long.valueOf(startMonths);
        String startDays = entity.getStartTime().split("-", 0)[2];
        Long startDay = Long.valueOf(startDays);
        //结束时间
        String endYears = entity.getEndTime().split("-", 0)[0];
        Long endYear = Long.valueOf(endYears);
        String endMonths = entity.getEndTime().split("-", 0)[1];
        Long endMonth = Long.valueOf(endMonths);
        String endDays = entity.getEndTime().split("-", 0)[2];
        Long endDay = Long.valueOf(endDays);
        list.forEach(item -> {
            AttendanceStaffStatQuery staffStatQuery = new AttendanceStaffStatQuery();
            staffStatQuery.setStaffId(entity.getStaffId());
            if (startYear == endYear) {
                staffStatQuery.setYear(startYear.intValue());
            } else {
                staffStatQuery.setYearStart(startYear.intValue());
                staffStatQuery.setYearEnd(endYear.intValue());
            }
            if (startMonth == endMonth) {
                staffStatQuery.setMonth(startMonth.intValue());
            } else {
                staffStatQuery.setMonthStart(startMonth.intValue());
                staffStatQuery.setMonthEnd(startMonth.intValue());
            }
            if (startDay == endDay) {
                staffStatQuery.setDay(startDay.intValue());
            } else {
                staffStatQuery.setDayStart(startDay.intValue());
                staffStatQuery.setDayEnd(startDay.intValue());
            }
            //比较 year  month day todo
//            staffStatQuery.setYear(year);//相等
//            staffStatQuery.setYearStart();
//            staffStatQuery.setYearEnd();
            //month and day  同上
            List<AttendanceStaffStatEntity> attendanceStaffStatEntities = attendanceStaffStatService.find(staffStatQuery);
            item.setAttendanceStaffStatEntities(attendanceStaffStatEntities);
        });
        super.findAfter(entity, context, list);
    }

    @Override
    protected void findAfter(AttendanceStatEntity params, PageInfo pageInfo, Context context, List<AttendanceStatEntity> list) throws AppException {
        //开始时间
        String startYears = params.getStartTime().split("-", 0)[0];
        Long startYear = Long.valueOf(startYears);
        String startMonths = params.getStartTime().split("-", 0)[1];
        Long startMonth = Long.valueOf(startMonths);
        String startDays = params.getStartTime().split("-", 0)[2];
        Long startDay = Long.valueOf(startDays);
        //结束时间
        String endYears = params.getEndTime().split("-", 0)[0];
        Long endYear = Long.valueOf(endYears);
        String endMonths = params.getEndTime().split("-", 0)[1];
        Long endMonth = Long.valueOf(endMonths);
        String endDays = params.getEndTime().split("-", 0)[2];
        Long endDay = Long.valueOf(endDays);
        list.forEach(item -> {
            AttendanceStaffStatQuery staffStatQuery = new AttendanceStaffStatQuery();
            staffStatQuery.setStaffId(item.getStaffId());
            if (startYear == endYear) {
                staffStatQuery.setYear(startYear.intValue());
            } else {
                staffStatQuery.setYearStart(startYear.intValue());
                staffStatQuery.setYearEnd(endYear.intValue());
            }
            if (startMonth == endMonth) {
                staffStatQuery.setMonth(startMonth.intValue());
            } else {
                staffStatQuery.setMonthStart(startMonth.intValue());
                staffStatQuery.setMonthEnd(endMonth.intValue());
            }
            if (startDay == endDay) {
                staffStatQuery.setDay(startDay.intValue());
            } else {
                staffStatQuery.setDayStart(startDay.intValue());
                staffStatQuery.setDayEnd(endDay.intValue());
            }
            //比较 year  month day todo
//            staffStatQuery.setYear(year);//相等
//            staffStatQuery.setYearStart();
//            staffStatQuery.setYearEnd();
            //month and day  同上
            List<AttendanceStaffStatEntity> attendanceStaffStatEntities = attendanceStaffStatService.find(staffStatQuery);
            item.setAttendanceStaffStatEntities(attendanceStaffStatEntities);
        });
        super.findAfter(params, pageInfo, context, list);
    }

    @Override
    public void doAttendanceSummary(AttendanceSummaryQuery query) {
        try {
            long currentTime = System.currentTimeMillis();
            if (query == null) {
                query = new AttendanceSummaryQuery();
            }
            if (StringUtils.isEmpty(query.getSummaryTime())) {
                Calendar now = Calendar.getInstance();
                now.setTime(new Date());
                now.add(Calendar.DAY_OF_MONTH, -1); //默认查前一天数据
                query.setSummaryTime(DateUtils.getStrDate(now.getTime()));
            }
            boolean isReturn = false;
            //判断是否为特定节假日
            HolidayQuery holidayQuery = new HolidayQuery();
            holidayQuery.setStartTimeStart(query.getSummaryTime());
            holidayQuery.setStartTimeEnd(query.getSummaryTime());
            HolidayEntity holidayEntity = holidayService.selectOne(holidayQuery);
            if (holidayEntity != null) {
                if (holidayEntity.getWorkorholiday() == 0) {
                    //特定节假日
                    isReturn = true;
                }
            } else {
                //判断是否为周末
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(DateUtils.StrToDate(query.getSummaryTime()));
                int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
                if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
                    isReturn = true;
                }
            }

            Date today = DateUtils.getCurrDate();
            if (DateUtils.StrToDate(query.getSummaryTime()).compareTo(today) >= 0) {
                //当天不统计
                isReturn = true;
            }
            if (isReturn) {
                return;
            }
            log.info("开始汇总[" + query.getSummaryTime() + "]考勤.....");
            //汇总当前日期假期余额
            List<VacationBalanceSummaryVo> vacationBalanceSummaryVoList = attendanceSummaryDao.getVacationBalanceSummary(query);
            if (CollectionUtils.isNotEmpty(vacationBalanceSummaryVoList)) {
                for (VacationBalanceSummaryVo item : vacationBalanceSummaryVoList) {
                    AttendanceStatEntity temp = this.selectOne(new AttendanceStatQuery().staffId(item.getStaffId()).year(item.getYear()).month(item.getMonth()).day(item.getDay()));
                    if (temp == null) {
                        AttendanceStatEntity attendanceStatEntity = new AttendanceStatEntity();
                        attendanceStatEntity.initAttrValue();
                        attendanceStatEntity.setStaffId(item.getStaffId());
                        attendanceStatEntity.setStaffName(item.getStaffName());
                        attendanceStatEntity.setDeptId(item.getDeptId());
                        attendanceStatEntity.setDeptName(item.getDeptName());
                        attendanceStatEntity.setPhoneNumer(item.getPhoneNumber());
                        attendanceStatEntity.setYear(item.getYear());
                        attendanceStatEntity.setMonth(item.getMonth());
                        attendanceStatEntity.setDay(item.getDay());
                        //BeanUtils.copyProperties(item, attendanceStatEntity, BeanUtil.getNullPropertyNames(item));
                        attendanceStatEntity.setCreateTime(new Date());
                        attendanceStatEntity.setCreateUserId(1l);
                        attendanceStatEntity.setGoTimes(1);   //默认当天全勤
                        this.dao.insert(attendanceStatEntity);
                    } else {
                        //BeanUtils.copyProperties(item, temp, BeanUtil.getNullPropertyNames(item));
                        temp.setUpdateTime(new Date());
                        this.dao.update(temp);
                    }
                }
            }
            log.info("完成汇总当前日期假期余额.....");

            //汇总当前日期异常考勤
            List<ErrorSummaryVo> errorSummaryVoList = attendanceSummaryDao.getErrorSummary(query);
            if (CollectionUtils.isNotEmpty(errorSummaryVoList)) {
                for (ErrorSummaryVo item : errorSummaryVoList) {
                    AttendanceStatEntity temp = this.selectOne(new AttendanceStatQuery().staffId(item.getStaffId()).year(item.getYear()).month(item.getMonth()).day(item.getDay()));
                    if (temp != null) {
                        BeanUtils.copyProperties(item, temp, BeanUtil.getNullPropertyNames(item));
                        temp.setGoTimes(0);     //默认只要有异常考勤，当天就不算全勤
                        if (item.getMorningTimes() > 0) {
                            temp.setNonCompliancePunch(new BigDecimal(item.getMorningTimes()));
                        }
                        this.dao.update(temp);
                    }
                    String attendanceSummary = "";
                    if (item.getMorningTimes() > 0) {
                        attendanceSummary += "缺卡*" + item.getMorningTimes() + "次;";
                    }
                    if (item.getLateTimes() > 0) {
                        attendanceSummary += "迟到*" + item.getLateTimes() + "次;";
                    }
                    if (item.getOvertimeTimes() > 0) {
                        attendanceSummary += "早退*" + item.getOvertimeTimes() + "次;";
                    }
                    AttendanceStaffStatEntity staffStat = new AttendanceStaffStatEntity();
                    staffStat.initAttrValue();
                    BeanUtils.copyProperties(item, staffStat, BeanUtil.getNullPropertyNames(item));
                    staffStat.setAttendanceSummary(attendanceSummary);
                    AttendanceStaffStatEntity staffStatTemp = attendanceStaffStatService.selectOne(new AttendanceStaffStatQuery().staffId(item.getStaffId()).year(item.getYear()).month(item.getMonth()).day(item.getDay()));
                    if (staffStatTemp != null) {
                        staffStat.setId(staffStatTemp.getId());
                        staffStat.setUpdateTime(new Date());
                        attendanceStaffStatService.update(staffStat);
                    } else {
                        staffStat.setCreateTime(DateUtils.StrToDate(query.getSummaryTime()));
                        staffStat.setCreateUserId(1l);
                        attendanceStaffStatService.save(staffStat);
                    }
                }
            }
            log.info("完成汇总当前日期异常考勤.....");
            //汇总当前日期请假情况
            List<LeaveSummaryVo> leaveSummaryVoList = attendanceSummaryDao.getLeaveSummary(query);
            if (CollectionUtils.isNotEmpty(leaveSummaryVoList)) {
                BigDecimal day = new BigDecimal(3600 * 8); //一天按8小时折算
                BigDecimal oneDay = new BigDecimal(1);
                for (LeaveSummaryVo item : leaveSummaryVoList) {
                    String attendanceSummary = "";
                    AttendanceStatEntity temp = this.selectOne(new AttendanceStatQuery().staffId(item.getStaffId()).year(item.getYear()).month(item.getMonth()).day(item.getDay()));
                    if (temp != null) {
                        BigDecimal leaveTime = new BigDecimal(item.getDuration()).divide(day, 1, BigDecimal.ROUND_HALF_DOWN);
                        String endStr = DateUtils.getStrDate(item.getEndTime());
                        String dayStr = query.getSummaryTime();
                        if (endStr.equals(dayStr)) {
                            if (leaveTime.compareTo(oneDay) >= 0) {
                                // 整数部分
                                BigDecimal integerPart = leaveTime.setScale(0, RoundingMode.DOWN);
                                // 小数部分
                                BigDecimal fractionalPart = leaveTime.subtract(integerPart);
                                if (fractionalPart.compareTo(new BigDecimal(0)) == 0) {
                                    leaveTime = oneDay;
                                } else {
                                    leaveTime = fractionalPart;
                                }
                            }
                        } else {
                            if (leaveTime.compareTo(oneDay) >= 0) {
                                leaveTime = oneDay;
                            }
                        }
                        temp.setGoTimes(0);     //默认只要有请假，当天就不算全勤
                        temp.setMorningTimes(0); //有请假则清空当天缺卡次数
                        temp.setLateTimes(0);
                        temp.setOvertimeTimes(0);
                        LeaveTypeEnum leaveTypeEnum = LeaveTypeEnum.getByValue(item.getLeaveType());
                        if (leaveTypeEnum == null) {
                            leaveTypeEnum = LeaveTypeEnum.其他;  //默认为事假
                        }
                        attendanceSummary = leaveTypeEnum.getDesc() + "*1";
                        switch (leaveTypeEnum) {
                            case 事假:
                                temp.setPersonalLeave(leaveTime);
                                break;
                            case 调休:
                                temp.setCompensatedLeaveDays(leaveTime);
                                break;
                            case 病假:
                                temp.setSickLeave(leaveTime);
                                break;
                            case 年假:
                                temp.setAnnualLeaveDays(leaveTime);
                                break;
                            case 产假:
                                temp.setMaternityLeave(leaveTime);
                                break;
                            case 陪产假:
                                temp.setPaternityLeaveDays(leaveTime);
                                break;
                            case 婚假:
                                temp.setMarriageLeave(leaveTime);
                                break;
                            case 例假:
                                temp.setMenstrualLeaveDays(leaveTime);
                                break;
                            case 哺乳假:
                                temp.setBreastfeedingLeaveDays(leaveTime);
                                break;
                            case 丧假:
                                temp.setFuneralLeave(leaveTime);
                                break;
                            case 回单位:
                                temp.setBackToUnit(leaveTime);
                                break;
                            case 因公请假:
                                temp.setOnDutyLeave(leaveTime);
                                break;
                            case 外出勘验:
                                temp.setOutOfOffice(leaveTime);
                                break;
                            case 值班补班:
                                temp.setShiftCompensation(leaveTime);
                                break;
                            case 体检:
                                temp.setPhysicalExamination(leaveTime);
                                break;
                            case 隔离:
                                temp.setQuarantine(leaveTime);
                                break;
                            case 因公外出:
                                temp.setBusinessTrip(leaveTime);
                                break;
                            case 公休:
                                temp.setPublicHoliday(leaveTime);
                                break;
                            case 育儿假:
                                temp.setChildRearingLeave(leaveTime);
                                break;
                            case 调回单位:
                                temp.setTransferBack(leaveTime);
                                break;
                            case 探亲假:
                                temp.setHomeLeave(leaveTime);
                                break;
                            case 其他:
                                temp.setOtherDays(leaveTime);
                                break;
                            default:
                                temp.setOtherDays(leaveTime);
                                break;
                        }
                        this.dao.update(temp);
                    }

                    AttendanceStaffStatEntity staffStat = new AttendanceStaffStatEntity();
                    staffStat.initAttrValue();
                    BeanUtils.copyProperties(item, staffStat, BeanUtil.getNullPropertyNames(item));
                    staffStat.setAttendanceSummary(attendanceSummary);
                    AttendanceStaffStatEntity staffStatTemp = attendanceStaffStatService.selectOne(new AttendanceStaffStatQuery().staffId(item.getStaffId()).year(item.getYear()).month(item.getMonth()).day(item.getDay()));
                    if (staffStatTemp != null) {
                        staffStat.setId(staffStatTemp.getId());
                        staffStat.setUpdateTime(new Date());
                        attendanceStaffStatService.update(staffStat);
                    } else {
                        staffStat.setCreateTime(DateUtils.StrToDate(query.getSummaryTime()));
                        staffStat.setCreateUserId(1l);
                        attendanceStaffStatService.save(staffStat);
                    }
                }
            }
            log.info("完成汇总当前日期请假情况.....");
            log.info("日期:" + query.getSummaryTime() + ",考勤汇总执行完成,耗时:" + (System.currentTimeMillis() - currentTime) + "毫秒....");
        } catch (Exception e) {
            log.error("考勤汇总出错", e);
        }
    }

    @Override
    public Result<AttendanceStatEntity> findExt(AttendanceSummaryQuery params, PageInfo pageInfo, Context context) throws AppException {
        if (params == null) {
            params = new AttendanceSummaryQuery();
/*            Calendar now = Calendar.getInstance();
            now.setTime(new Date());
            now.add(Calendar.DAY_OF_MONTH, -30); //默认查最近30天数据

         */
            params.setSummaryTimeStart(DateUtil.offsetDay(new Date(), -30).toDateStr());
            params.setSummaryTimeEnd(DateUtils.getCurrStrDate());
        }
        if (StringUtils.isNotEmpty(params.getStaffName())) {
            params.setStaffName("%" + params.getStaffName() + "%");
        }
        if (StringUtils.isNotEmpty(params.getPhoneNumer())) {
            params.setPhoneNumer("%" + params.getPhoneNumer() + "%");
        }
        if (pageInfo == null) {
            pageInfo = new PageInfo(10);
        }
        Result<AttendanceStatEntity> result = dao.getListExt(params, pageInfo);
        if (CollectionUtils.isNotEmpty(result.getList())) {
            for (AttendanceStatEntity item : result.getList()) {
                params.setStaffId(item.getStaffId());
                List<AttendanceStaffStatEntity> statEntities = attendanceStaffStatService.getListExt(params);
                if (CollectionUtils.isNotEmpty(statEntities)) {
                    item.setAttendanceStaffStatEntities(statEntities);
                }
            }
        }
        return result;
    }

    @Override
    public void homeStat(Context context) throws AppException {
        HomeStatInfo homeStatInfo = new HomeStatInfo();


        StaffQuery staffQuery = new StaffQuery();
        staffQuery.setStatusNotList(Arrays.asList(3));

        int totalPersonNum = staffService.count(staffQuery, context);
        homeStatInfo.setTotalPersonNum(totalPersonNum);
        staffQuery.setSource(1);


        Integer totalAttendPersonNum = staffService.count(staffQuery, context);

        int totalDeptNum = deptService.count(new DeptQuery(), context);
        homeStatInfo.setTotalDeptNum(totalDeptNum);

        AttendanceRecordHikQuery hikQuery = new AttendanceRecordHikQuery();
/*        hikQuery.setAttendanceDateStart(DateUtil.beginOfMonth(new Date()).toDateStr());
        hikQuery.setAttendanceDateEnd(DateUtil.today());        */
        hikQuery.setAttendanceDateStart(DateUtil.yesterday().toDateStr());
        hikQuery.setAttendanceDateEnd(DateUtil.yesterday().toDateStr());


        AttendanceRecordQuery attendanceRecordQuery = new AttendanceRecordQuery();
        // attendanceRecordQuery.setAttendanceDateStart(DateUtil.beginOfMonth(new Date()).toDateStr());
        //attendanceRecordQuery.setAttendanceDateEnd(DateUtil.today());
        attendanceRecordQuery.setAttendanceDateStart(DateUtil.yesterday().toDateStr());
        attendanceRecordQuery.setAttendanceDateEnd(DateUtil.yesterday().toDateStr());
        List<AttendanceRecordEntity> attendanceRecordEntities = recordService.find(attendanceRecordQuery);


        //获取当月打卡人数，如果存在
/*        Long totalCache = cacheService.hget(RedisKey.KEY_ATTENC_TOTOAL_CACHE, DateUtil.format(new Date(), "yyyy-MM"), Long.class);
        if (ObjectUtils.isEmpty(totalCache)) {
            totalCache = recordHikService.find(hikQuery).parallelStream().map(item -> item.getStaffId()).distinct().count();
            cacheService.hset(RedisKey.KEY_ATTENC_TOTOAL_CACHE, DateUtil.format(new Date(), "yyyy-MM"), totalCache);
        }*/

/*        Long totalCache = cacheService.hget(RedisKey.KEY_ATTENC_TOTOAL_CACHE, DateUtil.yesterday().toDateStr(), Long.class);
        if (ObjectUtils.isEmpty(totalCache)) {
            totalCache = recordHikService.find(hikQuery).parallelStream().map(item -> item.getStaffId()).distinct().count();
            cacheService.hset(RedisKey.KEY_ATTENC_TOTOAL_CACHE, DateUtil.yesterday().toDateStr(), totalCache);
        }*/


        //迟到次数
        long beLate = attendanceRecordEntities.parallelStream()
                .flatMap(item -> item.getAttendanceRecordDetailList().stream())
                .filter(f -> GoWorkResultEnum.迟到.getValue() == f.getGoWorkResult() || OffWorkResultEnum.迟到.getValue() == f.getOffWorkResult())
                .map(i -> i.getStaffId())
                .distinct()
                .count();

        //早退次数
        long leaveEarly = attendanceRecordEntities.parallelStream()
                .flatMap(item -> item.getAttendanceRecordDetailList().stream())
                .filter(f -> GoWorkResultEnum.早退.getValue() == f.getGoWorkResult() || OffWorkResultEnum.早退.getValue() == f.getOffWorkResult())
                .map(i -> i.getStaffId())
                .distinct()
                .count();

        //缺卡次数
        long lackOfCards = attendanceRecordEntities.parallelStream()
                .flatMap(item -> item.getAttendanceRecordDetailList().stream())
                .filter(f -> GoWorkResultEnum.缺卡.getValue() == f.getGoWorkResult() || OffWorkResultEnum.缺卡.getValue() == f.getOffWorkResult())
                .map(i -> i.getStaffId())
                .distinct()
                .count();


/*        AttendanceVacationRecordQuery vacationRecordQuery = new AttendanceVacationRecordQuery();
        vacationRecordQuery.setCreateTimeStart(DateUtil.beginOfMonth(new Date()).toDateStr());
        vacationRecordQuery.setCreateTimeEnd(DateUtil.today());
        int levealPersonNum = vacationRecordService.count(vacationRecordQuery, getContext());*/

        AttendanceLeaveRecordQuery leaveRecordQuery = new AttendanceLeaveRecordQuery();
/*        leaveRecordQuery.setCreateTimeStart(DateUtil.beginOfMonth(new Date()).toDateStr());
        leaveRecordQuery.setCreateTimeEnd(DateUtil.today());*/
        leaveRecordQuery.setCreateTimeStart(DateUtil.yesterday().toDateStr());
        leaveRecordQuery.setCreateTimeEnd(DateUtil.yesterday().toDateStr());
        leaveRecordQuery.setProcessStatus(ProcessStatusEnum.已处理.getValue());
        int levealPersonNum = leaveRecordService.count(leaveRecordQuery, context);


        //总打卡记录
/*        long totalAttend = attendanceRecordEntities.parallelStream().flatMap(item -> item.getAttendanceRecordDetailList().parallelStream()).count();

        long lackOfCardsAttend = attendanceRecordEntities.parallelStream()
                .flatMap(item -> item.getAttendanceRecordDetailList().stream())
                .filter(f -> GoWorkResultEnum.缺卡.getValue() == f.getGoWorkResult() || OffWorkResultEnum.缺卡.getValue() == f.getOffWorkResult())
                .count();*/
        //异常考勤记录
        //未考勤
        // long noAtt=lackOfCards;
        long att = totalAttendPersonNum - lackOfCards;
        // long att = totalAttend - lackOfCardsAttend;
        if (att != 0L) {

            BigDecimal bigDecimal = new BigDecimal(att).divide(new BigDecimal(totalAttendPersonNum), 4, BigDecimal.ROUND_CEILING).multiply(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_CEILING);
            homeStatInfo.setAttendRadio(bigDecimal.toString() + "%");
        } else {
            homeStatInfo.setAttendRadio("0%");
        }

        homeStatInfo.setLevealPersonNum(levealPersonNum);
        homeStatInfo.setLatePersonNum(beLate);
        homeStatInfo.setLeftEarlyPersonNum(leaveEarly);
        homeStatInfo.setMissCardPersonNum(lackOfCards);
        homeStatInfo.setAttendPersonNum(totalAttendPersonNum);

        cacheService.set(RedisKey.KEY_HOME_STAT_CACHE, JSON.toJSONString(homeStatInfo));

    }

}