package com.ruoyi.credit.scheduler;

import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ruoyi.credit.config.ValidationLoggingConfig;
import com.ruoyi.credit.service.IValidationLogService;

/**
 * 验证日志清理调度器
 * 
 * @author ruoyi
 * @date 2025-12-31
 */
@Component
@ConditionalOnProperty(prefix = "loan.validation.logging", name = "log-cleanup-enabled", havingValue = "true", matchIfMissing = true)
public class ValidationLogCleanupScheduler {

    private static final Logger log = LoggerFactory.getLogger(ValidationLogCleanupScheduler.class);

    @Autowired
    private IValidationLogService validationLogService;

    @Autowired
    private ValidationLoggingConfig validationLoggingConfig;

    /**
     * 定时清理过期的验证日志
     * 每天凌晨3点执行
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanupExpiredLogs() {
        if (!validationLoggingConfig.isLogCleanupEnabled()) {
            log.debug("验证日志清理功能已禁用，跳过清理任务");
            return;
        }

        try {
            log.info("开始清理过期的验证日志");
            
            // 计算清理截止日期
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -validationLoggingConfig.getLogRetentionDays());
            Date cleanupDate = calendar.getTime();
            
            log.info("清理{}之前的验证日志", cleanupDate);
            
            // 执行清理
            int deletedCount = validationLogService.deleteLogsByTimeRange(cleanupDate);
            
            log.info("验证日志清理完成，删除记录数: {}", deletedCount);
            
        } catch (Exception e) {
            log.error("清理验证日志时发生异常", e);
        }
    }

    /**
     * 定时清理异常日志（保留时间更短）
     * 每周日凌晨4点执行
     */
    @Scheduled(cron = "0 0 4 * * SUN")
    public void cleanupExceptionLogs() {
        if (!validationLoggingConfig.isLogCleanupEnabled()) {
            log.debug("验证日志清理功能已禁用，跳过异常日志清理任务");
            return;
        }

        try {
            log.info("开始清理过期的异常日志");
            
            // 异常日志保留7天
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -7);
            Date cleanupDate = calendar.getTime();
            
            log.info("清理{}之前的异常日志", cleanupDate);
            
            // 查询并删除异常日志
            // 这里可以添加更复杂的清理逻辑，比如只删除特定类型的异常日志
            
            log.info("异常日志清理完成");
            
        } catch (Exception e) {
            log.error("清理异常日志时发生异常", e);
        }
    }

    /**
     * 定时统计日志信息
     * 每天早上8点执行
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void generateLogStatistics() {
        try {
            log.info("开始生成验证日志统计信息");
            
            // 统计昨天的日志
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date startTime = calendar.getTime();
            
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date endTime = calendar.getTime();
            
            // 统计各级别日志数量
            java.util.List<java.util.Map<String, Object>> levelStats = validationLogService.countLogsByLevel(startTime, endTime);
            log.info("昨日日志级别统计: {}", levelStats);
            
            // 统计各类型日志数量
            java.util.List<java.util.Map<String, Object>> typeStats = validationLogService.countLogsByType(startTime, endTime);
            log.info("昨日日志类型统计: {}", typeStats);
            
            // 查询性能警告日志
            java.util.List<com.ruoyi.credit.domain.ValidationLog> performanceWarnings = validationLogService.selectPerformanceWarningLogs(
                validationLoggingConfig.getPerformanceWarningThreshold());
            log.info("昨日性能警告数量: {}", performanceWarnings.size());
            
            // 查询异常日志
            java.util.List<com.ruoyi.credit.domain.ValidationLog> exceptionLogs = validationLogService.selectExceptionLogs();
            log.info("昨日异常日志数量: {}", exceptionLogs.size());
            
            log.info("验证日志统计信息生成完成");
            
        } catch (Exception e) {
            log.error("生成验证日志统计信息时发生异常", e);
        }
    }

    /**
     * 定时检查日志存储空间
     * 每小时执行一次
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void checkLogStorageSpace() {
        try {
            // 这里可以添加检查日志存储空间的逻辑
            // 比如检查数据库表大小、磁盘空间等
            
            // 简单的日志数量检查
            int totalLogs = validationLogService.countValidationLogs(null);
            
            if (totalLogs > 1000000) { // 超过100万条日志
                log.warn("验证日志数量过多: {}, 建议清理历史日志", totalLogs);
            }
            
        } catch (Exception e) {
            log.error("检查日志存储空间时发生异常", e);
        }
    }
}