package com.ssyf.common.web.config;

import com.ssyf.common.web.i18n.CustomMessageSource;
import com.ssyf.common.web.i18n.CustomLocaleResolver;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.servlet.LocaleResolver;

import javax.validation.Validator;
import java.text.SimpleDateFormat;

/**
* web 基础配置
* @author huwei
* @date 2022/7/5 15:28
*/
@Configuration
public class WebConfig {
	@Autowired
	private CustomMessageSource customMessageSource;

	/**
	 * 定义Jackson全局的时间格式转换器
	 * @return
	 */
	@Bean
	public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
		MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
		converter.setObjectMapper(mapper);
		return converter;
	}

	/**
	 * 参数校验 描述： 方法上参数的校验所依赖的对象
	 */
	@Bean
	public MethodValidationPostProcessor methodValidationPostProcessor() {
		return new MethodValidationPostProcessor();
	}

	/**
	 * 国际化校验资源数据配置
	 */
	@Bean
	public Validator validator() {
		LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
		validator.setValidationMessageSource(customMessageSource);
		return validator;
	}
	/**
	 * 自定义国际化解析器
	 */
	@Bean
	public LocaleResolver localeResolver() {
		return new CustomLocaleResolver();
	}
}
