package com.platform.modules.app.interceptor;

import com.platform.common.exception.RRException;
import com.platform.modules.app.annotation.AppPermission;
import com.platform.modules.app.annotation.Login;
import com.platform.modules.app.utils.JwtUtils;
import com.platform.modules.sys.service.ShiroService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * 权限(Token)验证<br>
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private ShiroService shiroService;

    public static final String USER_KEY = "userId";
    public static final String USER_TENANT_KEY = "userTenantId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        // 获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }

        // 凭证为空
        if (StringUtils.isBlank(token)) {
            throw new RRException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new RRException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
        String subject = claims.getSubject();
        if (subject.indexOf("#") <= 0) {
            throw new RRException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }
        String[] subjects = StringUtils.split(subject, "#");
        Long userId = Long.parseLong(subjects[0]);
        Long userTenantId = Long.parseLong(subjects[1]);
        // 设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, userId);
        request.setAttribute(USER_TENANT_KEY, userTenantId);
        // 校验是否需要app权限
        AppPermission appPermission;
        appPermission = ((HandlerMethod) handler).getMethodAnnotation(AppPermission.class);
        if (appPermission == null) {
            return true;
        }

        // 需要app权限
        String permission = appPermission.permision();
        Set<String> permsSet = shiroService.getUserPermissions(userId);
        if (permsSet != null && permsSet.size() > 0 && permsSet.contains(permission)) {
            return true;
        } else {
            throw new RRException("没有权限，请联系管理员授权");
        }

    }
}
