package com.zzsn.modules.kgj.task;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zzsn.modules.kgj.common.Contant;
import com.zzsn.modules.kgj.entity.BaseDataVO;
import com.zzsn.modules.kgj.service.BaseDataService;
import com.zzsn.modules.kgj.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @author 刘凯歌
 * @description: 定时任务
 * @date 2020/9/28 16:46
 */
//@Component
public class CronTask {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private BaseDataService baseDataService;

    /**
     * 每天凌晨一点执行一次
     * 统计前12个月信息(按月统计)，包括疑似敏感信息数量和已确定敏感信息数量,放入redis缓存
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void dataCountByMonth() {
        String startTime = TimeUtil.getBeforeMonthFirstDate(new Date(), 12);
        String endTime = TimeUtil.getBeforeMonthEndDate(new Date());
        List<BaseDataVO> confirmDataList = baseDataService.getDataCountGroupByMonth(Contant.KGJ_TID, startTime, endTime, Contant.CONFIRM_DELFLAG);
        for (BaseDataVO vo :confirmDataList) {
            vo.setDelflag(Contant.CONFIRM_DELFLAG);
        }
        redisTemplate.opsForValue().set(Contant.DATA_KEY + "_" + Contant.CONFIRM_DELFLAG, JSON.toJSONString(confirmDataList));
        List<BaseDataVO> suspectDataList = baseDataService.getDataCountGroupByMonth(Contant.KGJ_TID, startTime, endTime, Contant.SUSPECT_DELFLAG);
        for (BaseDataVO vo :suspectDataList) {
            vo.setDelflag(Contant.SUSPECT_DELFLAG);
        }
        redisTemplate.opsForValue().set(Contant.DATA_KEY + "_" + Contant.SUSPECT_DELFLAG, JSON.toJSONString(suspectDataList));
    }

    /**
     * 每小时执行一次(整点执行)
     * 根据来源统计疑似敏感信息数量（包含已确认敏感信息数量），放入redis缓存
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void originDataList(){
        List<String> origins = baseDataService.getOrigins(Contant.KGJ_TID);
        ArrayList<BaseDataVO> resultList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(origins)){
            for (String origin :origins) {
                BaseDataVO dataByOrigin = baseDataService.getSuspectData(origin, Contant.SUSPECT_DELFLAG);
                resultList.add(dataByOrigin);
            }
        }
        //按疑似数量升序
        resultList.sort(Comparator.comparing(BaseDataVO::getCount));
        redisTemplate.opsForValue().set(Contant.DATA_BY_ORIGIN_KEY,JSON.toJSONString(resultList));
    }
}
