package com.nokia.alarm.config;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.nokia.alarm.service.AlarmSaveToGPandPGService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@SuppressWarnings("null")
@Configuration
public class CronTaskConfig implements SchedulingConfigurer {

    @Autowired
    private AlarmSaveToGPandPGService service;

    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskScheduler);

        // 入库的任务
        taskRegistrar.addCronTask(() -> {
            Date date = new Date();
            taskScheduler.submit(() -> {
                service.newAlarm(date);
                service.updateAlarm(date);
            });
        }, "0 0/5 * * * ?");

        // 删除临时文件的任务
        taskRegistrar.addCronTask(() -> {
            String day = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneId.of("Asia/Shanghai"))
                    .format(LocalDate.now().plusDays(-8));
            try {
                String command = "rm /data1/s130/alarm/csv/resultMap" + day + "*.csv -rf";
                log.info("删除文件 {} ...", command);
                int waitFor = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", command }).waitFor();
                log.info("删除文件完成 {} ...", waitFor);
            } catch (InterruptedException | IOException e) {
                e.printStackTrace();
                log.error("删除文件出错...");
            }
        }, "0 29 18 * * ?");

        log.info("已开启周期任务调度...");
    }
}