package com.pcloud.common.core.interceptor;

import java.lang.reflect.Method;
import java.util.Map;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.permission.Permission;
import com.pcloud.common.utils.SessionUtil;

/**
 * 
 * @描述：请求拦截器
 * @作者：songx
 * @创建时间：2017年9月11日,下午6:27:43 @版本：1.0
 */
public class GlobalHandlerInterceptor implements HandlerInterceptor {

	/**
	 * 
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(GlobalHandlerInterceptor.class);

	private static final String TOKEN = "token";

	/**
	 * 该方法在请求之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		if (method.isAnnotationPresent(Permission.class)) {
			Permission permission = method.getAnnotation(Permission.class);
			String token = request.getHeader(TOKEN);
			Map<String, Object> map = SessionUtil.getToken4Redis(token);
			JSONArray permissions = JSONArray.parseArray(JSON.toJSONString(map.get(SessionUtil.PERMISSIONS)));
			boolean flag = false;
			if (permissions != null) {
				for (int i = 0; i < permissions.size(); i++) {
					JSONObject object = permissions.getJSONObject(i);
					String accessPath = object.getString("accessPath");
					if (accessPath != null && permission.Code().contains(accessPath)) {
						flag = true;
						break;
					}
				}
			}
			if (!flag)
				throw BizException.PERMISSION_NOT_FOUND;
			LOGGER.info("【权限验证】调用--" + method.getName() + "--方法，token为-->" + token);
		} else {
			LOGGER.info("【权限验证】调用--" + method.getName() + "--方法，不需要权限。");
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception exception) throws Exception {
	}

}
