package com.imdroid.beidou.task;

import com.imdroid.secapi.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.sql.Timestamp;

/***
 * 定时任务：
 * 1、定时清理消息表（缺省保留3个月）
 * 2、定时清理原始数据表（缺省保留1个月）
 * 3、定时清理操作日志（缺省保留1年）
 * 4、定时检查设备是否在线
 * 5、定时检查FwdRecords(1 year)
 */

@Slf4j
@Configuration
@EnableScheduling
public class DatasetCleaner {
    @Autowired
    GnssMsgMapper gnssMsgMapper;
    @Autowired
    GnssStatusMsgMapper statusMsgMapper;
    @Autowired
    GnssTrxMsgMapper trxMsgMapper;
    @Autowired
    GnssRawDataMapper rawDataMapper;
    @Autowired
    ResendRecordMapper resendRecordMapper;
    @Autowired
    FwdRecordMapper fwdRecordMapper;

    //cron表达式格式：
    //{秒数} {分钟} {小时} {日期} {月份} {星期} {年份(可为空)}

    @Scheduled(cron = "0 10 0 * * *") // 每天凌晨执行一次(0:10:0)
    //@Scheduled(cron = "0 */2 * * * ?") // 每60分钟执行一次
    //@Scheduled(cron = "*/5 * * * * ?") // 每5秒执行一次
    public void dayTask() {
        checkMsgDataset();
        checkRawDataset();
        checkFwdDataset();
        checkStatusDataset();
    }

    void checkMsgDataset(){
        long before = System.currentTimeMillis() -
                (long)30 * 24 * 3600 * 1000;
        Timestamp t = new Timestamp(before);
        int count = gnssMsgMapper.deleteTimeBefore(t);
        log.info("clean msg dataset num: "+count);
    }

    void checkStatusDataset(){
        long before = System.currentTimeMillis() -
                (long)90 * 24 * 3600 * 1000;
        Timestamp t = new Timestamp(before);
        int count = statusMsgMapper.deleteTimeBefore(t);
        log.info("clean status msg dataset num: "+count);
        count = trxMsgMapper.deleteTimeBefore(t);
        log.info("clean trx msg dataset num: "+count);
    }

    void checkRawDataset(){
        long before = System.currentTimeMillis() -
                (long)30 * 24 * 3600 * 1000;
        Timestamp t = new Timestamp(before);
        int count = rawDataMapper.deleteTimeBefore(t);
        log.info("clean raw dataset num: "+count);
    }

    void checkFwdDataset(){
        long before = System.currentTimeMillis() -
                (long)180 * 24 * 3600 * 1000;
        Timestamp t = new Timestamp(before);
        int count = fwdRecordMapper.deleteTimeBefore(t);
        log.info("clean fwd dataset num: "+count);
        count = resendRecordMapper.deleteTimeBefore(t);
        log.info("clean resend dataset num: "+count);
    }
}