package com.czg.config;

import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.strategy.SaAnnotationStrategy;
import com.czg.sa.MyStpLogic;
import com.czg.utils.ServletUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Administrator
 */
@Configuration
@Slf4j
public class SaTokenConfigure implements WebMvcConfigurer {

    @PostConstruct
    public void setSaTokenConfig() {
        // admin配置
        SaTokenConfig adminConfig = new SaTokenConfig();
        adminConfig.setTokenName("token");
//        adminConfig.setTimeout(1000);
        adminConfig.setTokenStyle("simple-uuid");
        adminConfig.setIsConcurrent(true);
        adminConfig.setIsShare(false);
        adminConfig.setActiveTimeout(-1);
        MyStpLogic.ADMIN_LOGIC.setConfig(adminConfig);

        // 小程序配置
        SaTokenConfig userConfig = new SaTokenConfig();
        userConfig.setTokenName("token");
        userConfig.setIsConcurrent(true);
        userConfig.setIsShare(true);
//        config2.setTimeout(2000);
        userConfig.setTokenStyle("simple-uuid");
        MyStpLogic.USER_LOGIC.setConfig(userConfig);
    }

    @PostConstruct
    public void rewriteSaStrategy() {
        // 重写Sa-Token的注解处理器，增加注解合并功能
        SaAnnotationStrategy.instance.getAnnotation = AnnotatedElementUtils::getMergedAnnotation;
    }


    // 注册 Sa-Token 的拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            log.info("{}: {}", SaHolder.getRequest().getMethod(), SaHolder.getRequest().getRequestPath());
            if ("OPTIONS".equalsIgnoreCase(SaHolder.getRequest().getMethod())) {
                SaRouter.back();
                return;
            }
            SaRouter
                    .match(r -> "OPTIONS".equalsIgnoreCase(SaHolder.getRequest().getMethod()))
                    .stop()
                    // 完全开放的路径（不需要任何认证）
                    .match("/user/login", "/user/geo/**", "/user/home/**",
                            "/user/dict/**", "/user/openId", "/admin/auth/**",
                            "/admin/shopMsgPush/subscribe/**",
                            "/admin/coupon/grant",
                            "/pay/**",
                            "/notify/**")
                    .stop()  // 直接放行，不检查登录

                    // 用户认证路径
                    .match("/user/**")
                    .check(r -> MyStpLogic.USER_LOGIC.checkLogin())

                    // 管理端认证（内网IP免认证）
                    .match("/**")
                    .check(r -> {
                        ServletRequestAttributes attributes = (ServletRequestAttributes)
                                RequestContextHolder.getRequestAttributes();
                        if (attributes == null || (!ServletUtil.getClientIP(attributes.getRequest()).contains("192.168") && !ServletUtil.getClientIP(attributes.getRequest()).contains("127.0.0.1"))) {
                            MyStpLogic.ADMIN_LOGIC.checkLogin();
                        }
                    });

        })).addPathPatterns("/**");

    }
}
