package com.storlead.framework.web.process;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**"); //对应的接口
            }
        };
    }

    public WebMvcConfigurer() {

    }

    /**
     * 配置路由匹配模式
     *
     * **/
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        /***
         *
         * setUseSuffixPatternMatch : 设置是否是后缀模式匹配，如“/user”是否匹配/user.*，默认真即匹配；
         * setUseTrailingSlashMatch : 设置是否自动后缀路径模式匹配，如“/user”是否匹配“/user/”，默认真即匹配；
         configurer.setUseSuffixPatternMatch(false)
         .setUseTrailingSlashMatch(true);
         **/
        configurer.setUseSuffixPatternMatch(false);
        configurer.setUseTrailingSlashMatch(true);
        configurer.setUseRegisteredSuffixPatternMatch(true);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        pathMatcher.setTrimTokens(true);
        configurer.setPathMatcher(pathMatcher);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);

        converters.add(fastConverter);
    }


    /** 自定义一个MappingJackson2HttpMessageConverter放在所有默认Converter的前面,使其拥有最高优先级 */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        ArrayList<HttpMessageConverter<?>> copy = new ArrayList<>(converters.size());
        Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                iterator.remove();
            } else {
                copy.add(converter);
            }
        }
        //converters.clear();

        converters.add(createMappingJackson2HttpMessageConverter());
        converters.addAll(copy);
    }

    private MappingJackson2HttpMessageConverter createMappingJackson2HttpMessageConverter() {
        if (objectMapper == null) {
            final ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"));
            this.objectMapper = objectMapper;
        }
        return new MappingJackson2HttpMessageConverter(this.objectMapper);
    }

    /**
     * 配置返回的数据内容 ， 如 json,html
     * **/
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        /* 是否通过请求Url的扩展名来决定media type */
        /**/
        configurer.favorPathExtension(true)
                // 不检查Accept请求头,客户端传过来Accept要求返回的请求头，不做理会
                .ignoreAcceptHeader(true).parameterName("mediaType")
                // 请求以.html与 .jsp结尾的会被当成MediaType.TEXT_HTML
                .mediaType("html", MediaType.TEXT_HTML).mediaType("jsp", MediaType.TEXT_HTML)
                // 请求以.do与.json结尾的会被当成MediaType.APPLICATION_JSON
                .mediaType("do", MediaType.APPLICATION_JSON_UTF8).mediaType("json", MediaType.APPLICATION_JSON_UTF8);

        /**
         configurer.mediaTypes(ImmutableMap.of("do", MediaType.APPLICATION_JSON_UTF8,"json",MediaType.APPLICATION_JSON_UTF8 ));
         **/
        // configurer.mediaTypes(ImmutableMap.of("do", MediaType.APPLICATION_JSON_UTF8));
    }

    /**
     * 添加拦截器
     * **/
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

    }
}
