package com.qmth.file.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qmth.file.core.ApiResult;
import com.qmth.file.core.MD5;
import com.qmth.file.core.Token;
import com.qmth.file.exception.FileServerException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口鉴权
 * 
 * @author tianjun
 *
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {

	private Logger logger = LoggerFactory.getLogger(ApiInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("@@API Request URI:"+request.getRequestURI());
		HandlerMethod method = (HandlerMethod) handler;
		RequestMapping annotation = method.getMethodAnnotation(RequestMapping.class);
		if (annotation == null) {
			return false;
		}
		String header = StringUtils.trimToNull(request.getHeader("Authorization"));
		if (StringUtils.isNotEmpty(header)) {
			//1 校验token合法性
			String authorization = StringUtils.trimToNull(request.getHeader("Authorization"));
			if(StringUtils.isEmpty(authorization) || !authorization.startsWith("jk")){
				errorReturn(response, FileServerException.TOKEN_INVALID);
				return false;
			}
			String tokenParam = authorization.substring(2);
			Token token = Token.deserialize(tokenParam);
			//2校验签名
			String timestamp = StringUtils.trimToNull(request.getHeader("timestamp"));
			String sign = StringUtils.trimToNull(request.getHeader("sign"));
			if(StringUtils.isEmpty(timestamp)){
				errorReturn(response, FileServerException.TIMESTAMP_IS_NULL);
				return false;
			}
			if(StringUtils.isEmpty(sign)){
				errorReturn(response,  FileServerException.SIGN_INVALID);
				return false;
			}
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(authorization);
			stringBuffer.append("examCode=").append(token.getExamCode()).append("&");
			stringBuffer.append("timestamp=").append(timestamp).append("&");
			stringBuffer.append("uri=").append(request.getRequestURI()).append("&");
			stringBuffer.append("mac=").append(token.getMac());
			stringBuffer.append(authorization);
			String mysign = MD5.encrypt(stringBuffer.toString());
			if(!mysign.equals(sign)){
				errorReturn(response, FileServerException.SIGN_INVALID);
				return false;
			}
			else{
				return true;
			}
		}
		else{
			errorReturn(response, FileServerException.TOKEN_NEEDED);
			return false;
		}
	}


	private void errorReturn(HttpServletResponse response, FileServerException exception) {
		ApiResult result = new ApiResult();
		result.returnError(exception.getCode(), exception.getMessage());
		try {
			ObjectMapper mapper = new ObjectMapper();
			String returnResult = mapper.writeValueAsString(result);
			logger.debug("响应信息:" + returnResult);
			response.setStatus(200);
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(returnResult);
		} catch (Exception e) {
		}
	}

	// 获取客户端的IP
	public String getRemoteAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
	}
}
