package com.ssm.web;

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ssm.common.PermissionDeniedException;
import com.ssm.model.system.SysUser;
import com.ssm.service.system.SysUserService;
import com.ssm.util.Util;

public class AuthorityAdvice {
	
	@Autowired
	private SysUserService sysUserService;
	
	@SuppressWarnings("unused")
	public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {

		// 获取request和session
				RequestAttributes ra = RequestContextHolder.getRequestAttributes();
				ServletRequestAttributes sra = (ServletRequestAttributes) ra;
				HttpServletRequest request = sra.getRequest();
				HttpSession session = request.getSession();

				Signature signature = pjp.getSignature();
				MethodSignature methodSignature = (MethodSignature) signature;
				Method method = methodSignature.getMethod();
				
				if(method.isAnnotationPresent(WithoutUserLogin.class))
					return pjp.proceed();
				
				String url = request.getRequestURL().toString();
				Map<String, Object> result = new HashMap<String, Object>();
				boolean flag = isCheckLimit(request, method);
				if (!flag) {
					throw new PermissionDeniedException("您的权限不足", new Throwable("无法访问").getCause());
				} else {
					// 调用目标对象的方法
					Object retVal = pjp.proceed();
					
					return retVal;
				}
	}
	/**
	 * <b>方法说明：权限验证</b>
	 * 
	 * @param request
	 * @param method
	 * @return
	 */
	private boolean isCheckLimit(HttpServletRequest request, Method method) {
		if (method == null) {
			return false;
		}

		// 获取注解
		boolean isAnnotationPresent = method.isAnnotationPresent(RoleLimit.class);
		if (!isAnnotationPresent) {
			return false;
		}
		RoleLimit limit = method.getAnnotation(RoleLimit.class);

		// 获取注解上的值
		String pid = limit.pid();
		String mid = limit.mid();
		boolean flag = false;

		if (pid.equals(Const.SYSTEM_ROLE_LIMIT_PID) && mid.equals(Const.SYSTEM_ROLE_LIMIT_MID)) {
			return true;
		}

		HttpSession session = request.getSession();
		
		mid = mid.startsWith("/")?mid.substring(1):mid;
		pid = pid.startsWith("/")?pid.substring(1):pid;
		String action = pid + "/" + mid;
		
		SysUser user = Util.getUserSession(request);
		if(user != null) {
			int count = sysUserService.selectPerssion(user.getUserid(), action);
			if(count > 0)
				return true;
		}
		return flag;

	}

}
