package com.mortals.xhx.base.login.interceptor;

import com.mortals.framework.annotation.UnAuth;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import com.mortals.framework.ap.CookieService;
import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.model.CookieInfo;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.interceptor.BaseInterceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Order(1)
@Component
public class AuthJsonInterceptor extends BaseInterceptor {

    @Autowired
    private InterceptorConfig config;

    @Autowired
    private ICacheService cacheService;

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE - 9;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        try {
            if(handler instanceof HandlerMethod){
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                UnAuth annotation = method.getAnnotation(UnAuth.class);
                if (annotation != null) {
                    //取消校验
                    return true;
                }
            }
            String uri = request.getServletPath();
            if (config.needCheckAuth(uri)) {
                boolean auth = this.checkAuth(request, uri, config.getSecurityKey());
                if (!auth) {
                    CookieInfo cookie = CookieService.getLoginCookie(request, config.getSecurityKey());
                    if (cookie == null || cookie.getUser() == null) {
                        writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "用户未登录或登录失效，请重新登录");
                        return false;
                    } else if (cookie.getUser().isAdmin()) {
                        return super.preHandle(request, response, handler);
                    } else {
                        writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户无该操作权限");
                        return false;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("权限校验拦截请求处理异常-->" + e.getMessage());
            writeJsonResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "用户权限校验异常");
            return false;
        }

        return super.preHandle(request, response, handler);
    }

    private boolean checkAuth(HttpServletRequest request, String requestUrl, String securityKey) throws Exception {
        int code = requestUrl.hashCode() & (Integer.MAX_VALUE - 1);
        String cacheKey = HttpUtil.getCookieValue(request, SysConstains.COOKIE_MENU);
        if (StringUtils.isEmpty(cacheKey)) {
            return false;
        }
        String menuUrl = cacheService.get(cacheKey);
        if (StringUtils.isEmpty(menuUrl)) {
            return false;
        }
        menuUrl = AESUtil.decrypt(menuUrl, securityKey);
        String codes = "," + menuUrl + ",";
        String codeKey = "," + code + ",";
        if (codes.indexOf(codeKey) != -1) {
            return true;
        }
        return false;
    }
}
