package com.cweb.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.hfkj.common.security.UserCenter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Configuration
public class AuthConfig implements WebMvcConfigurer {

	private static Logger log = LoggerFactory.getLogger(AuthConfig.class);

	@Resource
	private UserCenter userCenter;

	/**
	 * 获取配置文件debug变量
	 */
	@Value("${debug}")
	private boolean debug = false;

	/**
	 * 解决18位long类型数据转json失去精度问题
	 * @param converters
	 */
	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
		MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();

		ObjectMapper objectMapper = jsonConverter.getObjectMapper();
		SimpleModule simpleModule = new SimpleModule();
		simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
		simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
		objectMapper.registerModule(simpleModule);

		converters.add(jsonConverter);
	}

	public void addInterceptors(InterceptorRegistry registry) {
	      registry.addInterceptor(new HandlerInterceptorAdapter() {

	          @Override
	          public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                                       Object handler) throws Exception {
	        	  if(debug){
	        		  return true;
	        	  }
	        	  String token = request.getHeader("Authorization");

	        	  if(StringUtils.isNotBlank(token) && userCenter.isLogin(token)){//如果未登录，将无法使用任何接口
	            	  return true;
	              } else if(request instanceof StandardMultipartHttpServletRequest) {
	            	  StandardMultipartHttpServletRequest re = (StandardMultipartHttpServletRequest)request;
	            	  if(userCenter.isLogin(re.getRequest())){
	            		  return true;
	            	  } else {
	            		  log.error("the user is not logged in,remoteAddr:"+getIpAddress(request)+",requestUrl:"+request.getRequestURL());
		            	  response.setStatus(401);
	            		  return false;
	            	  }
	              } else{
	            	  log.error("the user is not logged in,remoteAddr:"+getIpAddress(request)+",requestUrl:"+request.getRequestURL());
	            	  response.setStatus(401);
	            	  return false;
	              }
	          }
	      })
	      .addPathPatterns("/**")
	      .excludePathPatterns("/swagger-resources/**")
	      .excludePathPatterns("/**/api-docs")
	      .excludePathPatterns("/**/springfox-swagger-ui/**")
	      .excludePathPatterns("/**/swagger-ui.html")
	      .excludePathPatterns("/goods/*")
	      .excludePathPatterns("/cms/*")
	      .excludePathPatterns("/common/*")
	      .excludePathPatterns("/fileUpload/*")
	      .excludePathPatterns("/wxMsg/*")
	      .excludePathPatterns("/cinema/*")
	      .excludePathPatterns("/starbucks/*")
	      .excludePathPatterns("/c/*")
	      ;
	  }

	public String getIpAddress(HttpServletRequest request) {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

}
