package cn.palmte.work.config;

import cn.palmte.work.config.interceptor.TokenLoggingInterceptor;
import cn.palmte.work.utils.StrKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 配置拦截器等
 * @author xiongshiyan
 */
@Component
public class GoodWebAppConfigurer extends WebMvcConfigurerAdapter {

    @Autowired
    private TokenLoggingInterceptor tokenLoggingInterceptor;

    /**
     * 排除某些url不需要校验
     */
    @Value("${fourcal.excluded.client.urls}")
    private String excludesClientUrls;
    @Value("${fourcal.excluded.pc.urls}")
    private String excludesPCUrls;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**拦截任意URL,打印token header参数*/
        addInterceptor(registry , tokenLoggingInterceptor , "" , "/**");

        /**拦截所有排除指定的*/
    }
    private void addInterceptor(InterceptorRegistry registry , HandlerInterceptor handlerInterceptor , String excludeUrls , String... addPartterns) {
        InterceptorRegistration registration = registry.addInterceptor(handlerInterceptor)
                .addPathPatterns(addPartterns);
        String[] p = excludeUrls.split(",");
        StrKit.trim(p);
        if( p.length > 0 ){
            registration.excludePathPatterns(p);
        }
    }


    /**
     * 允许跨域
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
                .allowCredentials(false).maxAge(3600);
    }
}