package com.bcxin.ferry.scheduling;

import cn.hutool.core.date.DateUtil;
import com.bcxin.ferry.common.utils.ObsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

/**
 * description：上传日志任务，用于互联网排查问题
 * author：linchunpeng
 * date：2024/9/11
 */
@Slf4j
@Component
public class UploadLogsTask {

    @Value("${spring.profiles.active}")
    private String activeFile;

    @Scheduled(cron = "0 59 */1 * * ?")
    public void createFerryTask() {
        log.info("===================================上传日志任务，用于互联网排查问题===================================");
        if (activeFile.contains("out")) {
            log.info("政务网，需要上传日志文件");
            String region = activeFile.substring(4);
            String obsLogPath = "data/logs/auto-ferry/" + region;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            log.info("当前时间：{}，当前时间点：{}", DateUtil.formatDateTime(calendar.getTime()), hour);
            if (hour == 0) {
                log.info("当前时间是0点，需要上传昨天的日志");
                //info-2024-09-08.0.log
                calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - 1);
                String infoLog = "/data/logs/auto-ferry/info-".concat(DateUtil.formatDate(calendar.getTime())).concat(".0.log");
                File infoLogFile = new File(infoLog);
                if (infoLogFile.exists()) {
                    log.info("需要上传昨天的info日志：{}", infoLog);
                    ObsUtil.uploadFile(infoLogFile, obsLogPath + infoLog.substring(21));
                }

                String errorLog = "/data/logs/auto-ferry/auto-ferry-error-".concat(DateUtil.formatDate(calendar.getTime())).concat(".0.log");
                File errorLogFile = new File(errorLog);
                if (errorLogFile.exists()) {
                    log.info("需要上传昨天的error日志：{}", errorLog);
                    ObsUtil.uploadFile(errorLogFile, obsLogPath + errorLog.substring(21));
                }
            }
            File infoLogFile = new File("/data/logs/auto-ferry/info.log");
            if (infoLogFile.exists()) {
                ObsUtil.uploadFile(infoLogFile, obsLogPath + "/info.log");
            }
            File errorLogFile = new File("/data/logs/auto-ferry/error.log");
            if (errorLogFile.exists()) {
                ObsUtil.uploadFile(errorLogFile, obsLogPath + "/error.log");
            }
        } else {
            log.info("内网，不需要上传日志文件");
        }
        log.info("===================================上传日志任务结束===================================");
    }

}
