package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateUtil;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.OrderCol;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikQuery;
import com.mortals.xhx.module.attendance.service.AttendanceRecordHikService;
import com.mortals.xhx.module.attendance.service.AttendanceStatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

/**
 * 统计计算考勤
 */
@Slf4j
@Service("SyncDoorsEventAfterTask")
public class SyncDoorsEventAfterTaskImpl implements ITaskExcuteService {

    @Autowired
    private AttendanceRecordHikService recordHikService;
    @Autowired
    private AttendanceStatService attendanceStatService;

    @Value("${hik.host:}")
    protected String hikhost;


    @Override
    public void excuteTask(ITask task) throws AppException {
        //判断时间段 不在时间段的 不做计算
        //早上9点 子晚上8点 计算
        Date beginDateTime = DateUtil.parseDateTime(DateUtil.today() + " 07:00:00");
        Date endDateTime = DateUtil.parseDateTime(DateUtil.today() + " 23:30:00");
        boolean in = DateUtil.isIn(new Date(), beginDateTime, endDateTime);
        if (in) {
            calculateAttendByDay();
        }
        //统计当日
        log.info("统计当日考勤");
        attendanceStatService.homeStat(null);
        log.info("统计当日考勤结束");
    }


    private void calculateAttendByDay() {
        Context context = new Context();
        UserEntity userEntity = new UserEntity();
        userEntity.setCreateUserId(1L);
        userEntity.setId(1L);
        userEntity.setCreateUserName("admin");
        userEntity.setCreateTime(new Date());
        context.setUser(userEntity);
        AttendanceRecordHikQuery recordHikQuery = new AttendanceRecordHikQuery();
        recordHikQuery.setAttendanceDateStart(DateUtil.today());
        recordHikQuery.setAttendanceDateEnd(DateUtil.today());
        recordHikQuery.setOrderColList(Arrays.asList(new OrderCol("attendanceDate")));
        try {
            recordHikService.addAttendanceRecordByQuery(recordHikQuery, context);
        } catch (Exception e) {
            log.error("计算考勤异常", e);
        }
    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
