package com.ruoyi.framework.interceptor;

import com.ruoyi.system.service.ISysLicenseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 许可证验证拦截器
 * 在用户登录后验证系统许可证是否有效
 *
 * @author ruoyi
 * @date 2026-02-09
 */
@Component
public class LicenseInterceptor implements HandlerInterceptor
{
    private static final Logger log = LoggerFactory.getLogger(LicenseInterceptor.class);

    @Autowired
    private ISysLicenseService sysLicenseService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        // 获取请求URI
        String uri = request.getRequestURI();

        // 排除登录、登出、静态资源等请求
        if (uri.contains("/login") || uri.contains("/logout") ||
            uri.contains("/captchaImage") || uri.contains("/static") ||
            uri.contains("/css") || uri.contains("/js") || uri.contains("/img") ||
            uri.contains("/fonts") || uri.contains("/ajax"))
        {
            return true;
        }

        // 验证许可证
        boolean isValid = sysLicenseService.validateLicense();

        if (!isValid)
        {
            log.warn("许可证验证失败，拒绝访问: {}", uri);

            // 设置响应状态码和错误信息
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");

            String errorMessage = "{\"code\":601,\"msg\":\"系统许可证已过期或无效。\"}";

            response.getWriter().write(errorMessage);
            return false;
        }

        return true;
    }
}
