package com.liang.common.advice;


import cn.hutool.core.util.StrUtil;
import com.liang.common.annotation.DataPermissions;
import com.liang.common.base.BaseResult;
import com.liang.common.enums.Logical;
import com.liang.common.enums.ResultCode;
import com.liang.common.enums.Validation;
import com.liang.common.utils.SpringUtil;
import com.liang.common.utils.Tools;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 数据权限处理
 *
 * @author
 */
@Aspect
@Component
public class DataPermissionsAdvice {

    /**
     * 功能描述:
     */
    @Around(value = "@annotation(com.liang.common.annotation.DataPermissions)")
    public Object validationPermissions(ProceedingJoinPoint pjp) throws Throwable {

        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        DataPermissions dataPermissions = methodSignature.getMethod().getAnnotation(DataPermissions.class);

        Validation validation;//
        try {
            validation = validation(dataPermissions, pjp.getArgs());
        } catch (Exception e) {
            //发现异常认为权限不足
            validation = Validation.DENIED;
        }

        //校验成功执行方法,失败方法就不用执行了
        if (Validation.ACCESS == validation) {
            return pjp.proceed();
        } else {
            //返回失败的信息
            return BaseResult.failure(ResultCode.FAIL);
        }
    }

    private Validation validation(DataPermissions dataPermissions, Object[] args) {
        String[] permissionsArr = dataPermissions.value();
        if (Tools.isEmpty(permissionsArr)) {
            return Validation.ACCESS;
        }

        //获取用户权限
        List<String> permissionList = getPermissionList(args);
        if (Tools.isEmpty(permissionList)) {
            return Validation.DENIED;
        }

        Logical logical = dataPermissions.logical();
        //有一个不满足 认为无权限
        if (Logical.AND == logical) {
            return Arrays.stream(permissionsArr).anyMatch(permission -> !permissionList.contains(permission)) ? Validation.DENIED : Validation.ACCESS;
        }
        //只要有一个满足 认为有权限
        if (Logical.OR == logical) {
            return Arrays.stream(permissionsArr).anyMatch(permissionList::contains) ? Validation.ACCESS : Validation.DENIED;
        }
        return Validation.DENIED;
    }


    private List<String> getPermissionList(Object[] args) {
        List<String> permissionList = new ArrayList<>();
//        PermissionDao permissionsDao = SpringUtil.getBean(PermissionDao.class);
//        User user = UserUtil.getCurrentUserFromRedis();
//
//
//        permissionList = permissionsDao.listPermissionByUserId(user.getId());


        return permissionList;
    }
}
