package com.yonge.cooleshow.config;

import com.microsvc.toolkit.common.webportal.converter.EnumsConvertorFactory;
import com.yonge.cooleshow.biz.dal.config.LocalFastJsonHttpMessageConverter;
import com.yonge.cooleshow.common.config.EnumConverterFactory;
import com.yonge.cooleshow.interceptor.MDCInterceptor;
import com.yonge.cooleshow.interceptor.OperationLogInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	private OperationLogInterceptor operationLogInterceptor;
	@Autowired
	private EnumConverterFactory enumConverterFactory;
	@Autowired
	private MDCInterceptor mdcInterceptor;

	/**
	 * 枚举类的转换器 addConverterFactory
	 */
	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(enumConverterFactory);
		// 枚举映射转换
		registry.addConverterFactory(new EnumsConvertorFactory());
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {

		// MDC拦截器
		registry.addInterceptor(mdcInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
		// 日志请求拦截器
		registry.addInterceptor(operationLogInterceptor).addPathPatterns("/**").excludePathPatterns("/login");
	}

	@Order(0)
	@Primary
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		LocalFastJsonHttpMessageConverter converter = new LocalFastJsonHttpMessageConverter();
		List<MediaType> fastMediaTypes = new ArrayList<MediaType>();
		fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		converter.setSupportedMediaTypes(fastMediaTypes);
		return new HttpMessageConverters(converter);
	}
}
