package cn.com.qmth.stmms.common.interceptor;

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

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * 方法操作拦截器
 *
 * @author LS
 */
public class MethodInterceptor extends HandlerInterceptorAdapter {

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

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return (handler instanceof HandlerMethod) && validateAuth((HandlerMethod) handler, request, response);
    }

    private boolean validateAuth(HandlerMethod method, HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean result = true;
        WebUser wu = RequestUtils.getWebUser(request);
        RoleRequire roleRequire = method.getMethodAnnotation(RoleRequire.class);
        if (wu != null && roleRequire != null) {
            Role[] roles = roleRequire.value();
            if (roles != null && roles.length > 0) {
                int count = 0;
                for (Role role : roles) {
                    if (wu.getRole() == role) {
                        count++;
                    }
                }
                if (!roleRequire.nand() && count < roles.length) {
                    result = false;
                } else if (roleRequire.nand() && count == 0) {
                    result = false;
                }
            }
        }
        if (!result) {
            log.info("method auth vaildate faile!");
            String redirect = StringUtils.trimToNull(roleRequire.redirect());
            if (redirect != null) {
                response.sendRedirect(request.getContextPath() + redirect);
            } else {
                response.sendError(401, "没有权限进行此操作");
            }
        }
        return result;
    }
}
