package cn.superdesk.uniorder.config.rest;

import cn.superdesk.uniorder.config.exception.UnifiedOrderRuntimeExceptionHandler;
import cn.superdesk.uniorder.interceptor.security.JwtInterceptor;
import cn.superdesk.uniorder.common.numerical.AnDateConverter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ConversionServiceFactoryBean;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 8/20/20 7:38 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 8/20/20 7:38 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Configuration
public class CostomWebMvcConfigurerAdapter implements WebMvcConfigurer {

//	@Override
//	public void addInterceptors(InterceptorRegistry registry) {
//		registry.addInterceptor(new GlobalDefaultInterceptor()).addPathPatterns("/**");
//	}


    /**
     * 将拦截器作为bean写入配置中
     *
     * @return
     */
    @Bean
    public JwtInterceptor jwtInterceptor() {
        return new JwtInterceptor();
    }

    /**
     * 该方法用于注册拦截器 可注册多个拦截器,多个拦截器组成一个拦截器链
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 添加 拦截器 排除
        String[] arrIgnoreUrl = {
                "/user/login",
                "/user/tokenlogin",
                "/user/loginByToken",
                "/user/refreshToken",
                "/user/imageCode",
                "/error",

                "/dubbo/index",
                "/external/useMaterial",
                "/pai/**",
                "/dzmain/test",
                "/unifiedorder/*",
                "/wechat/*",
                "/fundUser/selectById",


                "/openapi/superdeskmall/core/oauth/loginByPassport",
                "/openapi/superdeskmall/core/oauth/loginBySupplier",
                "/openapi/superdeskmall/core/oauth/passport",
                "/openapi/superdeskmall/core/oauth/passport/decode",

                "/openapi/superdeskmall/core/credit/checkStatement",

                "/openapi/order/proxy/receive/optBecomeInvalid",

                "/thirdpart/szhtxx/electronicInvoiceFptxx/opPreviewPdf/**",

                "/common/excel/export/f/**",

                "/doc.html**",
                "/webjars/js/**",
                "/webjars/css/**",

                "/swagger-ui.html",
                "/swagger-ui.html**",
                "/swagger-resources/**",

                "/v2/**"
        };

        registry.addInterceptor(jwtInterceptor())
                .excludePathPatterns(arrIgnoreUrl)
                .addPathPatterns("/**");
        // .excludePathPatterns("/api/**")

    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS")
                .maxAge(3600);
    }

    /**
     * 配置全局类型转换器
     *
     * @return
     */
    @Bean
    @SuppressWarnings("rawtypes")
    public ConversionService getConversionService() {

        ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();

        // 增加日期类型转
        Set<Converter> converters = new HashSet<Converter>();

        converters.add(new AnDateConverter());
        factoryBean.setConverters(converters);

        return factoryBean.getObject();
    }

    /**
     * 默认的json转方式
     *
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

//		super.configureMessageConverters(converters);


        /****************************************** 怎么这里是 fastjson的配置呢? start ******************************************/

        FastJsonHttpMessageConverter fastConverter  = new FastJsonHttpMessageConverter();
        FastJsonConfig               fastJsonConfig = new FastJsonConfig();

        List<MediaType> supportedMediaTypes = new ArrayList<>();

        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.IMAGE_GIF);
        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
        supportedMediaTypes.add(MediaType.IMAGE_PNG);
        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        supportedMediaTypes.add(MediaType.TEXT_XML);

        fastConverter.setSupportedMediaTypes(supportedMediaTypes);

        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteMapNullValue
        );

        fastConverter.setFastJsonConfig(fastJsonConfig);

        // 将fastjson添加到视图消息转换器列表内
        converters.add(fastConverter);

        /****************************************** 怎么这里是 fastjson的配置呢? start ******************************************/
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        resolvers.add(new UnifiedOrderRuntimeExceptionHandler());
    }


}
