package cn.wisenergy.web.aspect;

import cn.wisenergy.common.annotation.DataAuth;
import cn.wisenergy.common.constant.CommonConstants;
import cn.wisenergy.common.enums.RespCodeEnum;
import cn.wisenergy.common.utils.exception.Result;
import cn.wisenergy.model.app.AccountInfo;
import cn.wisenergy.service.app.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
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 java.lang.reflect.Method;
import java.util.Map;

/**
 * 数据权限,切面处理类
 */
@Aspect
@Component
public class DataAuthAspect {
    @Autowired
    AccountService sysUserService;

    @Pointcut("@annotation(cn.wisenergy.common.annotation.DataAuth)")
    public void dataPointCut() {
    }

    @Around("dataPointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        // 获取方法上的注解
        DataAuth dataAuth = method.getAnnotation(DataAuth.class);
        if (dataAuth != null) {
            // 获取注解值
            String mapKey = dataAuth.value();
            // 获取请求参数
            Object[] args = pjp.getArgs();
            for (Object obj : args) {
                if (obj instanceof Map) {
                    Map<String, Object> map = (Map<String, Object>) obj;
                    // 获取当前用户
                    AccountInfo sysUser = (AccountInfo) SecurityUtils.getSubject().getPrincipal();
                    if (sysUser != null) {
                        // 超级管理员返回全量数据
                        if (!StringUtils.equals(sysUser.getId().toString(), CommonConstants.SUPER_ADMIN)) {
                            // 查询用户的数据权限信息,如果存在数据权限集合,将集合存入请求参数map中
//                            Set<String> dataAuthList = sysUserService.getUserDataAuth(sysUser);
//                            if (dataAuthList != null && !dataAuthList.isEmpty()) {
//                                map.put(mapKey, dataAuthList);
//                            }
                        }
                        return pjp.proceed();
                    }
                }
            }
        }
        Result result = new Result();
        result.setResult(Result.RESULT_FLG.FAIL.getValue());
        result.setErrorCode(RespCodeEnum.DATA_AUTH_UNAUTHORIZED.getCode());
        result.setErrorMsg(RespCodeEnum.DATA_AUTH_UNAUTHORIZED.getMsg());
        return result;
    }
}