package com.aucma.framework.validation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;

/**
 * @author Wen JY
 * @description: 系统校验拦截器
 * @date 2025-10-09 17:20:25
 * @version: 1.0
 */
public class ValidationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ValidationInterceptor.class);

    // 配置系统过期日期（可以从配置文件中读取）
    @Value("${system.expire.date:MjA5Ny0xMi0zMQ==}") // 默认2026-01-01
    private String expireDateBase64;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 检查是否已过期
        if (isSystemExpired()) {
            handleExpiredRequest(request, response);
            return false; // 拦截请求
        }
        return true; // 放行请求
    }

    /**
     * 检查系统是否已过期
     */
    public boolean isSystemExpired() {
        try {
            byte[] decode = Base64.getDecoder().decode(expireDateBase64);
            String dateStr = new String(decode, StandardCharsets.UTF_8);

            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate expireDate = LocalDate.parse(dateStr, dtf);
            LocalDate currentDate = LocalDate.now();

            logger.debug("系统过期检查: 当前日期={}, 过期日期={}, 是否过期={}",
                    currentDate, expireDate, currentDate.isAfter(expireDate));

            return currentDate.isAfter(expireDate);

        } catch (Exception e) {
            logger.error("系统过期检查失败，默认不拦截", e);
            return false; // 解析失败时默认不拦截，避免影响系统正常运行
        }
    }

    /**
     * 处理过期请求
     */
    private void handleExpiredRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.warn("拦截过期系统访问: {} {}", request.getMethod(), request.getRequestURI());

        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.setContentType("application/json;charset=UTF-8");

        String errorResponse = "{\"code\": 503, \"message\": \"系统已过期，请联系管理员\", \"timestamp\": \""
                + Instant.now().toString() + "\"}";

        response.getWriter().write(errorResponse);
        response.getWriter().flush();
    }

    /**
     * 静态方法，供其他类调用检查系统状态
     */
    public static boolean checkSystemStatus() {
        try {
            ValidationInterceptor interceptor = new ValidationInterceptor();
            interceptor.expireDateBase64 = "MjAyNi0wMS0wMQ==";      //默认 2026-01-01
            return !interceptor.isSystemExpired();
        } catch (Exception e) {
            return true; // 检查失败时默认系统可用
        }
    }

}
