package cn.hmsoft.application.web;

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

import javax.servlet.ServletContext;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.BufferedImageHttpMessageConverter;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import cn.hmsoft.helper.JsonHelper;
import cn.hmsoft.log.LogHelper;

/*******************************
 * Web配置文件
 * 
 * @author zxq
 * @create 2019-05-27 11:49:10
 * @version 2.0.0
 * @email: revisit@126.com
 * @Company: www.hmsoft.cn
 */

@Configuration
@ComponentScan(basePackages = "cn.hmsoft")
@ImportResource("classpath:spring*.xml")

public class WebAppConfig extends WebMvcConfigurationSupport {
	/*************************
	 * 全局的WebServletContext，系统启动时设置该变量
	 */
	public static ServletContext WebServletContext = null;

	public static String getRealPath(String path) {
		return WebServletContext.getRealPath("/") + path.replaceAll("/", File.separator);
	}

	@Override
	protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

		List<MediaType> list = new ArrayList<MediaType>();
		list.add(MediaType.APPLICATION_JSON);
		list.add(MediaType.TEXT_HTML);
		list.add(MediaType.APPLICATION_JSON_UTF8);

		GsonHttpMessageConverter json = new GsonHttpMessageConverter();
		json.setSupportedMediaTypes(list);
		json.setGson(JsonHelper.createJson());
		converters.add(json);
		// 设置提交格式，统一用utf-8，防止乱码
		converters.add(new FormHttpMessageConverter());
		converters.add(new StringHttpMessageConverter(Charset.forName("utf-8")));
		converters.add(new ByteArrayHttpMessageConverter());
		converters.add(new BufferedImageHttpMessageConverter());
	}

	/**********************************
	 * 定义文件上传的最大文件大小
	 */
	@Bean(name = "multipartResolver")
	public CommonsMultipartResolver getCommonsMultipartResolver() {
		CommonsMultipartResolver cmr = new CommonsMultipartResolver();
		cmr.setDefaultEncoding("utf-8");
		// 上传最大的文件大小1G
		//cmr.setMaxUploadSize(WebAppHelper.MaxUploadSize);
		//cmr.setMaxInMemorySize(WebAppHelper.MaxInMemorySize);
		return cmr;
	}

	/****************************************
	 * 加载默认拦截器，加载用户自定义拦截器
	 */
	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		// 添加默认的拦截器
		DefaultInterceptor defaultInterceptor = new DefaultInterceptor();
		registry.addInterceptor(defaultInterceptor);
		if (StringUtils.isEmpty(WebAppHelper.AppInterceptors))
			return;
		String[] array = WebAppHelper.AppInterceptors.trim().split(",");
		if (array.length > 0)
			LogHelper.log("check custom interceptor, initializing it");
		// 判断是否还有自定义的拦截器
		for (String s : array) {
			try {
				HandlerInterceptor inetrceptor = (HandlerInterceptor) Class.forName(s.trim()).newInstance();
				registry.addInterceptor(inetrceptor);
			} catch (Exception e) { // 如果类型错误,判断是否是web的拦截器
				try {
					WebRequestInterceptor interceptor = (WebRequestInterceptor) Class.forName(s.trim()).newInstance();
					registry.addWebRequestInterceptor(interceptor);
				} catch (Exception ex) {
					LogHelper.error(
							"custom interceptor init error,please check it:[" + WebAppHelper.AppInterceptors + "]");
				}
			}
		}
	}

	/************************
	 * 允许跨域访问
	 */
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE",
				"OPTIONS", "TRACE");
	}
}
