package com.hzs.common.core.aspect;

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.context.SecurityContextHolder;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.system.sys.IMenuColumnServiceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 接口访问权限拦截器
 * @Author: jiang chao
 * @Time: 2024/11/18 15:57
 * @Classname: AccessPermissionsAspectAdvice
 * @PackageName: com.hzs.common.core.aspect
 */
@Slf4j
@Order(5)
@Aspect
@Component
public class AccessPermissionsAspectAdvice {

    @DubboReference
    IMenuColumnServiceApi iMenuColumnServiceApi;

    /**
     * 定义切点Pointcut
     */
    @Pointcut("@annotation(com.hzs.common.core.annotation.AccessPermissions)")
    public void accessPermissionsPointCut() {
    }

    /**
     * 请求前处理接口权限
     *
     * @param joinPoint
     * @param accessPermissions
     */
    @Before(value = "accessPermissionsPointCut() && @annotation(accessPermissions)")
    public void accessPermissionsPointBefore(JoinPoint joinPoint, AccessPermissions accessPermissions) {
        List<String> permList = Arrays.asList(accessPermissions.value());

        if (CollectionUtil.isNotEmpty(permList) && !MagicNumberConstants.PK_ADMIN.equals(SecurityContextHolder.getUserId())) {
            // 需要处理权限 并且 不是超级管理员，则进行处理
            if (!iMenuColumnServiceApi.checkMenuPerms(permList, SecurityContextHolder.getUserId()).isSuccess()) {
                // 权限标记有值，需要进行判断是否有权限读取数据
                throw new BaseException("当前用户无权查看，如有需要请联系超级管理员");
            }
        }
    }

}
