package com.ruoyi.system.service;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HolidayUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AttendanceTime;
import com.ruoyi.system.domain.KaoqinConfig;
import com.ruoyi.system.domain.KaoqinRecord;
import com.ruoyi.system.mapper.AttendanceTimeMapper;
import com.ruoyi.system.mapper.KaoqinConfigMapper;
import com.ruoyi.system.mapper.KaoqinRecordMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.Constants.*;

@Component
public class Task {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private KaoqinRecordMapper kaoqinRecordMapper;
    @Autowired
    private AttendanceTimeMapper attendanceTimeMapper;
    @Autowired
    private KaoqinConfigMapper kaoqinConfigMapper;
    @Autowired
    private RedisCache redisCache;

    /***
     * 定时插入未打卡数据
     */
    @Async
    //@Scheduled(cron = "0 0/2 * * * ? ")
    @Scheduled(cron = "0 1 0 * * ? ")
    public void thirdNucleicAcid() {
        String day = DateUtils.getDate();
        //获取前一天的日期
        String data = DateUtils.plusSeconds(DateUtils.getDate(),-1,"yyyy-MM-dd");
        //判断当天天是否是法定节假日  0 上班 1周末 2节假日
        String jsonResult = HolidayUtils.request(data);
        if(!"0".equals(jsonResult)){
            //是节假日的话不需要插入数据，直接返回
            return;
        }
        //查询考勤日期规则
        AttendanceTime attendanceTime = new AttendanceTime();
        List<AttendanceTime> attendanceTimes = attendanceTimeMapper.selectAttendanceTimeList(attendanceTime);
        //根据部门分类
        //Map<Long, List<AttendanceTime>> collect = attendanceTimes.stream().collect(Collectors.groupingBy(AttendanceTime::getDeptId));
        KaoqinConfig kaoqinConfig = kaoqinConfigMapper.selectKaoqinConfigBynew();

        //获取所有有部门的人员
        List<SysUser> userList = userMapper.selectUserListNoDept();
        //获取前一天的所有考勤记录
        KaoqinRecord kaoqinRecord = new KaoqinRecord();
        kaoqinRecord.setKaTime(data);
        List<KaoqinRecord> kaoqinRecordList = kaoqinRecordMapper.selectKaoqinRecordList(kaoqinRecord);
        if(kaoqinRecordList == null || kaoqinRecordList.isEmpty()){
            return;
        }
        for (SysUser sysUser : userList) {
            boolean blt = false;
            if(attendanceTimes != null && !attendanceTimes.isEmpty()){
                for (AttendanceTime time : attendanceTimes) {
                    if(time.getDeptName().contains(sysUser.getDept().getDeptName()) && DateUtils.isDateBetween(DateUtils.parseDate(data), time.getStartTime(), time.getEndTime())){
                        blt = true;
                        break;
                    }
                }
            }
            if(blt){
                continue;
            }
            boolean bl = true;
            for (KaoqinRecord record : kaoqinRecordList) {
                if(record.getUserId().equals(sysUser.getUserId())){
                    if(StringUtils.isNotBlank(record.getKaTypeAmIn())){
                        record.setKaTypeAmIn(FIVE);
                    }
                    if(FOUR.equals(kaoqinConfig.getKaNum())){
                        if(StringUtils.isNotBlank(record.getKaTypeAmOut())){
                            record.setKaTypeAmOut(FIVE);
                        }
                        if(StringUtils.isNotBlank(record.getKaTypePmIn())){
                            record.setKaTypePmIn(FIVE);
                        }
                    }
                    if(StringUtils.isNotBlank(record.getKaTypePmOut())){
                        record.setKaTypePmOut(FIVE);
                    }
                    bl = false;
                }
            }
            if(bl){
                //将日期拆分成年月日的数组
                String[] datas = data.split("-");
                KaoqinRecord kaoqinRecords = new KaoqinRecord();
                kaoqinRecords.setUserId(sysUser.getUserId());
                kaoqinRecords.setUserName(sysUser.getNickName());
                kaoqinRecords.setPhone(sysUser.getPhonenumber());
                kaoqinRecords.setDeptId(sysUser.getDeptId());
                kaoqinRecords.setDeptName(sysUser.getDept().getDeptName());
                kaoqinRecords.setAncestors(sysUser.getDept().getAncestors());
                kaoqinRecords.setKaYear(datas[0]);
                kaoqinRecords.setKaMonth(datas[1]);
                kaoqinRecords.setKaDay(datas[2]);
                kaoqinRecords.setKaWeek(DateUtils.dateToWeek(data));
                kaoqinRecords.setKaTime(data);
                kaoqinRecords.setKaTypeAmIn(FIVE);
                kaoqinRecords.setKaNum(kaoqinConfig.getKaNum());
                if (kaoqinConfig!=null && "4".equals(kaoqinConfig.getKaNum())) {
                    kaoqinRecords.setKaTypeAmOut(FIVE);
                    kaoqinRecords.setKaTypePmIn(FIVE);
                }
                kaoqinRecords.setKaTypePmOut(FIVE);
                kaoqinRecords.setKaStatus(TWO);
                kaoqinRecords.setCreateTime(DateUtils.getNowDate());
                kaoqinRecordMapper.insertKaoqinRecord(kaoqinRecords);
            }

        }

    }
    //0 上班 1周末 2节假日
    /*public static void main(String[] args) {
        String data = DateUtils.plusSeconds(DateUtils.getDate(),-1,"yyyy-MM-dd");
        System.out.println(data);
    }*/

    /***
     * 定时插入未打卡数据
     */
    @Async
    //@Scheduled(cron = "0 0/2 * * * ? ")
    @Scheduled(cron = "0 0 2 25 * ? ")
    public void getHoliday() {
        //获取当前年份
        int year=Integer.parseInt(DateUtils.getYear());
        int month=Integer.parseInt(DateUtils.justMonth());
        if(month==12){
            year = year +1;
            month = 1;
        }else{
            month = month + 1;
        }
        //查询下一个月份的放假信息
        List<String> allDate = DateUtils.getAllDateStringsInMonth(year, month);
        String dateList = String.join(",", allDate);
        String jsonResult = HolidayUtils.request(dateList);
        String key = "monthHoliday"+year+"-"+month;
        //保存两个月时间
        redisCache.setCacheObject(key,jsonResult);

        System.out.println(jsonResult);

    }

    /***
     * 项目初始化时缓存当前月和下一个月的放假信息
     * @throws InterruptedException
     */
    @PostConstruct
    public void init() throws InterruptedException {
        //获取当前年份
        String year=DateUtils.getYear();
        String month=DateUtils.justMonth();
        //查询当前月份的放假信息
        List<String> allDateDq = DateUtils.getAllDateStringsInMonth(Integer.parseInt(year), Integer.parseInt(month));
        String dateListDq = String.join(",", allDateDq);
        String jsonResultDq = HolidayUtils.request(dateListDq);
        String keyDq = "monthHoliday"+year+"-"+month;
        //保存两个月时间
        redisCache.setCacheObject(keyDq,jsonResultDq);
        //睡眠1.1秒（获取假期接口限制），每秒最多访问2次
        Thread.sleep(1100);

        //查询下一个月份的放假信息
        if("12".equals(month)){
            year = String.valueOf(Integer.parseInt(year) + 1);
            month = "01";
        }else{
            month = String.valueOf(Integer.parseInt(month) + 1);
            if(Integer.parseInt(month)<10){
                month = "0"+month;
            }
        }
        List<String> allDate = DateUtils.getAllDateStringsInMonth(Integer.parseInt(year), Integer.parseInt(month));
        String dateList = String.join(",", allDate);
        String jsonResult = HolidayUtils.request(dateList);
        String key = "monthHoliday"+year+"-"+month;
        //保存两个月时间
        redisCache.setCacheObject(key,jsonResult);
    }



}
