package org.springblade.config;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

/**
 * 
 * @author William
 * @date 2022年10月31日 下午2:29:26
 */
@Configuration
public class JsonConfig implements WebMvcConfigurer {

	/**
	 * 所有Long型数据在生成Json时都转换成String，并且统一格式化时间
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		MappingJackson2HttpMessageConverter httpMessageConverters = new MappingJackson2HttpMessageConverter();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
		objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.setSerializationInclusion(Include.NON_NULL);

		// 统一格式化日期
		objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

		SimpleModule simpleModule = new SimpleModule();
		// Long对象定义的字段转化为字符串
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		// BigDecimal对象定义的字段转化为字符串
		simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);
		objectMapper.registerModule(simpleModule);
		httpMessageConverters.setObjectMapper(objectMapper);

		// 设置为第一个，否则在某种情况下会失效，比如其它地方设置过转换器
		converters.add(0, httpMessageConverters);
	}

}
