package com.kym.admin.config;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author skyline
 * @description 权限校验
 * @date 2023-07-11 21:49
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

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

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，校验规则为 StpUtil.checkLogin() 登录校验。
        registry.addInterceptor(new SaInterceptor(handler -> {
                    // 1. 通过请求路径判断：login 接口不鉴权
                    String path = SaHolder.getRequest().getRequestPath();
                    if ("/admin-user/login".equals(path)) {
                        log.debug("SaInterceptor: 跳过 login 接口鉴权");
                        return;
                    }
                    // 2. 检查 @SaIgnore 注解，有则跳过鉴权
                    if (handler instanceof HandlerMethod hm) {
                        if (hm.hasMethodAnnotation(SaIgnore.class)
                                || hm.getBeanType().isAnnotationPresent(SaIgnore.class)) {
                            log.debug("SaInterceptor: @SaIgnore 跳过鉴权 - {}", hm.getMethod().getName());
                            return;
                        }
                    }
                    StpUtil.checkLogin();
                }))
                .addPathPatterns("/**")
                .excludePathPatterns(
                        "/wx/*",
                        "/finance/export/*",
                        "/admin-user/login",
                        "/**/error",
                        "/**/pullEnStations/*",
                        "/**/*.html",
                        "/**/*.js",
                        "/**/*.css",
                        "/**/*.png",
                        "/**/*.ico",
                        "/",
                        "/h5/**",
                        "/parking-coupon/**"
                );
        // TODO: 2023-07-11 具体功能权限校验后续开发
    }

}