package com.judong.chuanyiserver.annotation;

import com.judong.chuanyiserver.dao.UserDao;
import com.judong.chuanyiserver.entity.Permission;
import com.judong.chuanyiserver.entity.User;
import com.judong.chuanyiserver.enums.ResultEnum;
import com.judong.chuanyiserver.exception.CustomException;
import com.judong.chuanyiserver.util.Blank;
import com.judong.chuanyiserver.util.ConstantStr;
import com.judong.chuanyiserver.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
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 javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Aspect
@Slf4j
public class PermissionControlAspect {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private HttpServletRequest request;

    /**
     * 定义切点 @Pointcut
     * 在注解的位置切入代码
     */
    @Pointcut("execution(* com.judong.chuanyiserver..*.*(..))")
    public void permissionControl() {
    }

    /**
     * 环绕通知
     */
    @Around(value = "permissionControl() && @annotation(PermissionControl)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        request = attributes.getRequest();
        if (Blank.isEmpty(request)) {
            throw new CustomException(ResultEnum.UNAUTHORIZED.getRespCode(), ResultEnum.UNAUTHORIZED.getRespMsg());
        }
        String userId = (String) redisUtil.get(request.getHeader("token"));
        if (Blank.isEmpty(userId)) {
            throw new CustomException(ResultEnum.UNAUTHORIZED.getRespCode(), ResultEnum.UNAUTHORIZED.getRespMsg());
        }
        User user = userDao.getUserById(userId);
        if (Blank.isEmpty(user)) {
            throw new CustomException(ResultEnum.UNAUTHORIZED.getRespCode(), ResultEnum.UNAUTHORIZED.getRespMsg());
        }
        List<Integer> roleIdList = userDao.getRoleIdListByUserId(user.getUserId());
        if (Blank.isEmpty(roleIdList)) {
            throw new CustomException(ResultEnum.NO_OPERATION_AUTHORITY.getRespCode(), ResultEnum.NO_OPERATION_AUTHORITY.getRespMsg());
        }
        List<Permission> permissionList=userDao.getPermissionByRoleList(roleIdList);
        if (Blank.isEmpty(permissionList)){
            throw new CustomException(ResultEnum.NO_OPERATION_AUTHORITY.getRespCode(), ResultEnum.NO_OPERATION_AUTHORITY.getRespMsg());
        }
        for (Permission permission : permissionList) {
            if(permission.getPermissionUrl().equals(request.getRequestURI())){
                // 获取签名
                Signature signature = joinPoint.getSignature();
                // 获取切入的包名
                String declaringTypeName = signature.getDeclaringTypeName();
                // 获取即将执行的方法名
                String funcName = signature.getName();
                Map<String, Object> params = new HashMap<>();
                String[] keys = ((MethodSignature) signature).getParameterNames();
                Object[] args = joinPoint.getArgs();
                for (int i = 0; i < keys.length; i++) {
                    params.put(keys[i], args[i]);
                }
                log.info("即将执行{}包下的方法，方法名为: {}", declaringTypeName, funcName);
                log.info("请求的参数有: {}", params.toString());
                return joinPoint.proceed();
            }
        }
        throw new CustomException(ResultEnum.NO_OPERATION_AUTHORITY.getRespCode(), ResultEnum.NO_OPERATION_AUTHORITY.getRespMsg());
    }

    @Before(value = "permissionControl() && @annotation(PermissionControl)")
    public void before(JoinPoint joinPoint) {
        // 请求参数
//        System.out.println("Before");
    }

    @After(value = "permissionControl() && @annotation(PermissionControl)")
    public void after() {
//        System.out.println("After");
    }
}
