package com.greenorange.promotion.aop;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.greenorange.promotion.annotation.RequiresPermission;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.exception.ThrowUtils;
import com.greenorange.promotion.model.entity.UserInfo;
import com.greenorange.promotion.model.enums.UserRoleEnum;
import com.greenorange.promotion.service.user.UserInfoService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;


/**
 * 权限校验AOP
 */

@Slf4j
@Aspect
@Component
public class PermissionCheck {


    @Resource
    private UserInfoService userInfoService;


 
    /***
     * 执行拦截
     **/
    @Around("@annotation(requiresPermission)")
    public Object check(ProceedingJoinPoint joinPoint, RequiresPermission requiresPermission) throws Throwable {
        // 获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // 接口的权限
        String mustRole = requiresPermission.mustRole();
        // 获取接口权限的枚举类
        UserRoleEnum mustUserRoleEnum = UserRoleEnum.getEnumByValues(mustRole);
        ThrowUtils.throwIf(mustUserRoleEnum == null, ErrorCode.NO_AUTH_ERROR);
        // 获取用户权限
        String token = request.getHeader("token");
        ThrowUtils.throwIf(StringUtils.isBlank(token), ErrorCode.NOT_LOGIN_ERROR);
        String id = null;
        try {
            id = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException jwtDecodeException) {
            log.info("JWT已失效");
        }
        UserInfo userInfo = userInfoService.getById(id);
        ThrowUtils.throwIf(userInfo == null, ErrorCode.OPERATION_ERROR);
        // 获取用户权限的枚举类
        String userRole = userInfo.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValues(userRole);

        // 接口权限只能是 ADMIN 或者 BOSS，用户权限是 ADMIN 或者 BOSS，USER，BAN
        // 校验角色
        ThrowUtils.throwIf(UserRoleEnum.USER.equals(userRoleEnum), ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(UserRoleEnum.BAN.equals(userRoleEnum), ErrorCode.NO_AUTH_ERROR, "用户已被封禁");
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(userRoleEnum) && UserRoleEnum.BOSS.equals(mustUserRoleEnum), ErrorCode.NO_AUTH_ERROR);

        return joinPoint.proceed();
    }
 
}