package com.czg.config;

import cn.dev33.satoken.application.ApplicationInfo;
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 jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotatedElementUtils;
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.CLIENT_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().getRequestPath());
            // 重置根路径，防止satoken切割根路径导致匹配不到路径
            ApplicationInfo.routePrefix = "";

            SaRouter.match("/user/**").notMatch("/user/login", "/user/test", "/user/geo/**", "/user/home/**", "/user/home/**", "/user/dict/**", "/user/openId")
                    .notMatch("/pay/**")
                    .notMatch("/notify/**")
                    .check(r -> MyStpLogic.CLIENT_LOGIC.checkLogin())
                    .setHit(true)
//                    .match("/**")
                    .notMatch("/user/**")
                    .notMatch("/pay/**")
                    .notMatch("/notify/**")
                    .notMatch("/admin/auth/**")
                    .notMatch("/admin/shopMsgPush/subscribe/**")
                    .check(r -> MyStpLogic.ADMIN_LOGIC.checkLogin());

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

    }
}
