package com.api.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.openapi.v1.service.AuthTokenService;
import com.hfkj.openapi.v1.service.impl.AuthTokenServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.io.BufferedOutputStream;
import java.util.List;

@Configuration
public class AuthConfig implements WebMvcConfigurer {

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

	@Resource
	private RedisUtil redisUtil;

	/**
	 * 获取配置文件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 merNo = request.getHeader("MerchantNo");
	        	  String token = request.getHeader("Authorization");
				  //如果未登录，将无法使用任何接口
	        	  if (StringUtils.isBlank(merNo) || StringUtils.isBlank(token)) {
					  response.setStatus(401);
					  return false;
	              }
				  // 查询校验token
				  Object merToken = redisUtil.get(merNo + AuthTokenServiceImpl.OPEN_API_TOKEN);
				  if (merToken == null) {
					  BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
					  out.write(JSONObject.toJSONString(ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_TOKEN_ERR.getCode(), ErrorCode.OPEN_API_TOKEN_ERR.getMsg(),null)).getBytes());
					  out.flush();
					  out.close();
					  return false;
				  }
				  if (!token.equals(merToken.toString())) {
					  BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
					  out.write(JSONObject.toJSONString(ResponseMsgUtil.builderResponse(SysCode.OpenApi.getCode()+ErrorCode.OPEN_API_TOKEN_ERR.getCode(), ErrorCode.OPEN_API_TOKEN_ERR.getMsg(),null)).getBytes());
					  out.flush();
					  out.close();
					  return false;
				  }*/
				  return true;
	          }
	      })
	      .addPathPatterns("/**")
	      .excludePathPatterns("/swagger-resources/**")
	      .excludePathPatterns("/**/api-docs")
	      .excludePathPatterns("/**/v1/auth/*")
	      .excludePathPatterns("/**/springfox-swagger-ui/**")
	      .excludePathPatterns("/**/swagger-ui.html")
	      ;
	  }

	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;
    }

}
