package com.ruoyi.framework.interceptor;

import com.ruoyi.common.exception.LicenseException;
import com.ruoyi.system.service.ILicenseService;
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;
import java.util.Date;

@Component
public class LicenseInterceptor implements HandlerInterceptor {

    @Autowired
    private ILicenseService licenseService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 白名单路径直接放行
        if (isExcludePath(request.getRequestURI())) {
            return true;
        }

        // 验证授权状态
        if (!licenseService.checkLicense()) {
            throw new LicenseException("系统授权已过期，请更新授权！");
        }

        // 检查剩余有效期（提前30天提醒）
        Date expireDate = licenseService.getExpireDate();
        if (expireDate != null && isNearExpire(expireDate)) {
            Long licw = getRemainingDays(expireDate);
            response.setHeader("License-Warning", licw.toString());//系统到期天数存到header中，用于前端获取
           // response.setHeader("Access-Control-Expose-Headers", "License-Warning");
        }
        return true;
    }

    private boolean isExcludePath(String uri) {
        return uri.startsWith("/license") ||
                uri.startsWith("/login") ||
                uri.startsWith("/static");
    }

    private boolean isNearExpire(Date expireDate) {
        long diff = expireDate.getTime() - System.currentTimeMillis();
        return diff > 0 && diff < 30L * 24 * 60 * 60 * 1000;
    }

    private long getRemainingDays(Date expireDate) {
        return (expireDate.getTime() - System.currentTimeMillis()) / (1000 * 60 * 60 * 24);
    }
}
