package com.xxfc.platform.vehicle.config;

import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.github.wxiaoqi.security.common.interceptor.CorsInterceptor;
import com.github.wxiaoqi.security.common.log.XxLogInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.Collections;

/**
 *
 */
@Configuration("vehicleWebConfig")
@Primary
public class WebConfiguration implements WebMvcConfigurer {
    @Bean
    GlobalExceptionHandler getGlobalExceptionHandler() {
        return new GlobalExceptionHandler();
    }


    /**
     * 加入拦截器，介入相关权限验证（服务+用户）
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getCorsInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(getServiceAuthRestInterceptor()).
                addPathPatterns(getIncludePathPatterns());
        registry.addInterceptor(getUserAuthRestInterceptor()).
                addPathPatterns(getIncludePathPatterns());
    }



//    @Bean
//    XxLogInterceptor getXxLogInterceptor() {
//        return new XxLogInterceptor();
//    }

    @Bean
    ServiceAuthRestInterceptor getServiceAuthRestInterceptor() {
        return new ServiceAuthRestInterceptor();
    }

    @Bean
    CorsInterceptor getCorsInterceptor() {
        return new CorsInterceptor();
    }

    @Bean
    UserAuthRestInterceptor getUserAuthRestInterceptor() {
        return new UserAuthRestInterceptor();
    }

    /**
     * 需要用户和服务认证判断的路径
     * @return
     */
    private ArrayList<String> getIncludePathPatterns() {
        ArrayList<String> list = new ArrayList<>();
        String[] urls = {
                "/vehicleInfo/**",
                "/branchCompany/**",
                "/departure/**"
        };
        Collections.addAll(list, urls);
        return list;
    }

    /**
     * 增加执行异步任务的自定义线程池执行器
     * @return
     */
    @Bean(name = "customTaskExecutor")
    TaskExecutor getTaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);// 线程池维护线程的最少数量
        threadPoolTaskExecutor.setMaxPoolSize(10);// 线程池维护线程的最大数量
        threadPoolTaskExecutor.setQueueCapacity(50);// 缓存队列
        return threadPoolTaskExecutor;
    }

}
