package com.persagy.calendar.config;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

/**
 * @description 
 * @author zhangqiankun
 * @since 2020年8月26日:	下午5:17:08
 */
@Configuration
public class SpringMVCConfig {
	private static final String ENCODE_UTF_8 = "UTF-8";
	
	/**
	 * HttpMessageConverters - FastJson
	 * 首字母会改为小写，如有必要，手动在实体类上加上@JSONField 注解
	 */
	@Bean
	public HttpMessageConverters fastJsonHttpMessageConverters() {
		// 1、定义一个convert转换消息的对象
		FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverterConfig();

		// 2、添加fastjson的配置信息
		FastJsonConfig fastJsonConfig = new FastJsonConfig();

		SerializerFeature[] serializerFeatures = new SerializerFeature[] {
				// 循环引用
				SerializerFeature.DisableCircularReferenceDetect
			};

		fastJsonConfig.setSerializerFeatures(serializerFeatures);
		fastJsonConfig.setCharset(Charset.forName(ENCODE_UTF_8));
		
		//3、设置类型
		List<MediaType> mediaTypes = new ArrayList<MediaType>();
		mediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
		mediaTypes.add(MediaType.TEXT_PLAIN);
		mediaTypes.add(MediaType.ALL);
		fastConverter.setSupportedMediaTypes(mediaTypes);
        
        //4、将转换规则应用于转换对象 
        fastConverter.setFastJsonConfig(fastJsonConfig);
        fastConverter.setDefaultCharset(Charset.forName(ENCODE_UTF_8));
        
        return new HttpMessageConverters(fastConverter);
	}

}

class FastJsonHttpMessageConverterConfig extends FastJsonHttpMessageConverter{
	
	@Override
	protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		if (obj instanceof String) {
			//设置 字符串返回的 ContentType 类型
			HttpHeaders headers = outputMessage.getHeaders();
			//headers.setContentType(MediaType.TEXT_PLAIN);
			headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
			Charset charset = this.getDefaultCharset();
	        StreamUtils.copy((String) obj, charset, outputMessage.getBody());
		} else {
			super.writeInternal(obj, outputMessage);
		}
	}

}
