package com.greenorange.promotion.aop;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.userInfo.UserInfoService;
import com.greenorange.promotion.utils.JWTUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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;


    @Resource
    private JWTUtils jwtUtils;

 
    /***
     * 执行拦截
     **/
    @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 interfaceRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        ThrowUtils.throwIf(interfaceRoleEnum == null, ErrorCode.NO_AUTH_ERROR);
        // 获取用户权限
        String token = request.getHeader("Authorization");
        ThrowUtils.throwIf(StringUtils.isBlank(token), ErrorCode.NO_AUTH_ERROR, "JWT为空");
        // 解析token
        DecodedJWT decodedJWT = jwtUtils.verify(token);
        String userAccount = decodedJWT.getClaim("userAccount").asString();
        String userPassword = decodedJWT.getClaim("userPassword").asString();
        // 查询用户信息
        LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserInfo::getUserAccount, userAccount).eq(UserInfo::getUserPassword, userPassword);
        UserInfo userInfo = userInfoService.getOne(lambdaQueryWrapper);
        ThrowUtils.throwIf(userInfo == null, ErrorCode.OPERATION_ERROR, "用户不存在");
        // 将用户id存入request，用于记录日志
        request.setAttribute("userId", userInfo.getId());

        // 获取用户权限的枚举类
        String userRole = userInfo.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(userRole);

        // 接口权限只能是 USER，ADMIN，BOSS，用户权限是 ADMIN，BOSS，USER，BAN，MANAGER，SUPERVISOR，STAFF
        // 校验角色
        ThrowUtils.throwIf(UserRoleEnum.BOSS.equals(userRoleEnum) && UserRoleEnum.USER.equals(interfaceRoleEnum), ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(UserRoleEnum.ADMIN.equals(userRoleEnum) && !UserRoleEnum.ADMIN.equals(interfaceRoleEnum), ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(UserRoleEnum.BAN.equals(userRoleEnum), ErrorCode.PARAMS_ERROR, "用户已被封禁");
        ThrowUtils.throwIf((UserRoleEnum.USER.equals(userRoleEnum)
                || UserRoleEnum.STAFF.equals(userRoleEnum)
                || UserRoleEnum.SUPERVISOR.equals(userRoleEnum)
                || UserRoleEnum.MANAGER.equals(userRoleEnum)) && !UserRoleEnum.USER.equals(interfaceRoleEnum), ErrorCode.NO_AUTH_ERROR);

        return joinPoint.proceed();
    }
 
}