package com.greenorange.promotion.aop;
 
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.greenorange.promotion.annotation.RequiresPermission;
import com.greenorange.promotion.model.entity.User;
import com.greenorange.promotion.service.user.UserService;
import com.wechat.pay.java.core.exception.ServiceException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 权限校验AOP
 */

@Slf4j
@Aspect
@Component
public class PermissionCheck {


    @Resource
    private UserService userService;
 
 
    /***
     * @MethodName: permissionCheckPointCut
     * @description: 定义一个切点
     * @Author: LiuTao
     * @UpdateTime: 2023/6/20 19:34
     **/
    @Pointcut("@annotation(com.greenorange.promotion.annotation.RequiresPermission)")
    public void permissionCheckPointCut() {
 
    }
 
    /***
     * @MethodName: check
     * @description: 环绕通知
     * @Author: LiuTao
     * @Param: [pjp]
     * @UpdateTime: 2023/6/20 19:34
     * @Return: java.lang.Object
     * @Throw: Throwable
     **/
    @Around("permissionCheckPointCut()")
    public Object check(ProceedingJoinPoint pjp) throws Throwable {
        // 获取请求对象
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // 记录日志
        log.info("===============系统操作日志===============");
        Signature signature = pjp.getSignature();
        // 请求的类
        String className = pjp.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.info("请求类：{}", className);
        log.info("请求方法：{}", methodName);
        log.info("请求方式：{}", request.getMethod());
        log.info("请求ip：{}", request.getRemoteAddr());
        log.info("请求类方法：{}", signature);
        log.info("请求参数：{}", Arrays.toString(pjp.getArgs()));
        // 权限注解校验
        MethodSignature handlerMethod = (MethodSignature) signature;
        Method method = handlerMethod.getMethod();
        System.out.println("method:" + method);
        System.out.println("-------------------------------------------");
        // 判断当前方法上有没有注解
        System.out.println(method.isAnnotationPresent(RequiresPermission.class));
        System.out.println("-------------------------------------------");

        if (method.isAnnotationPresent(RequiresPermission.class)) {
            RequiresPermission auth = method.getAnnotation(RequiresPermission.class);
            System.out.println("++++++++++++++++++++++++++++auth:" + auth);
            String roles = auth.roles();
            String permissions = auth.permissions();
 
            String token = request.getHeader("token");
            // 认证
            if (StrUtil.isBlank(token)) {
//                throw new ServiceException(Constants.CODE_401, "请登录!!!");
            }
            String id = null;
//            try {
//                id = JWT.decode(token).getAudience().get(0);
//            } catch (JWTDecodeException jwtDecodeException) {
////                throw new ServiceException(Constants.CODE_401, "token验证失败，请重新登录");
//            }
//            User user = userService.getById(id);
            // 校验角色
//            if (StrUtil.isNotBlank(roles)) {
//                if (!Arrays.asList(roles.split(",")).contains(user.getRole())) {
////                    throw new ServiceException(Constants.CODE_403, "当前角色权限不足");
//                }
//            }
            // 校验权限
//            if (StrUtil.isNotBlank(permissions)) {
//                List<String> userPermissions = menuUtil
//                        .getPermissions(user.getRole())
//                        .stream()
//                        .map(BtnVo::getPermission)
//                        .collect(Collectors.toList());
//                if (!new HashSet<>(userPermissions).containsAll(Arrays.asList(permissions.split(",")))) {
//                    throw new ServiceException(Constants.CODE_401, "无权限访问资源");
//                }
//            }
        }
        return pjp.proceed();
    }
 
}