package com.mortals.xhx.base.framework.aspect;


import com.mortals.framework.ap.SysConstains;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AESUtil;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.xhx.base.framework.annotation.RequiresPermissions;
import com.mortals.xhx.base.framework.config.InterceptorConfig;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Set;

/**
 * [角色权限]控制拦截器
 *
 * @author: zxfei
 * @date: 2021/10/28 13:27
 */
@Aspect
@Slf4j
@Component
@Order(3)
public class PermissionAspect {

    @Pointcut(value = "execution(* com.mortals..*Controller.*(..))")
    private void aspectPointcut() {

    }

    @Autowired
    private InterceptorConfig config;

    @Autowired
    private ICacheService cacheService;

    @Before("aspectPointcut()")
    public void before(JoinPoint joinPoint) {
        log.info("开始校验[操作权限]");
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        RequiresPermissions a = methodSignature.getMethod().getAnnotation(RequiresPermissions.class);
        if (!ObjectUtils.isEmpty(a)) {
            String[] perms = a.value();
            log.info("校验权限code: {}", Arrays.toString(perms));
        }


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("请求路径 {} ,进入方法 {}", request.getRequestURI(), joinPoint.getSignature().getDeclaringTypeName() + ":" + joinPoint.getSignature().getName());

        String uri = request.getServletPath();
        log.info("uri:" + uri);

       /* SessionUserInfo userInfo = tokenService.getUserInfo();
        Set<String> myCodes = userInfo.getPermissionList();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        RequiresPermissions a = methodSignature.getMethod().getAnnotation(RequiresPermissions.class);
        String[] perms = a.value();
        log.debug("校验权限code: {}", Arrays.toString(perms));
        log.debug("用户已有权限: {}", myCodes);
        //5.对比[要求]的code和[用户实际拥有]的code
        if (a.logical() == Logical.AND) {
            //必须包含要求的每个权限
            for (String perm : perms) {
                if (!myCodes.contains(perm)) {
                    log.warn("用户缺少权限 code : {}", perm);
                    throw new UnauthorizedException();//抛出[权限不足]的异常
                }
            }
        } else {
            //多个权限只需包含其中一种即可
            boolean flag = false;
            for (String perm : perms) {
                if (myCodes.contains(perm)) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                log.warn("用户缺少权限 code= : {} (任意有一种即可)", Arrays.toString(perms));
                throw new UnauthorizedException();//抛出[权限不足]的异常
            }
        }*/
    }


    private boolean checkAuth(HttpServletRequest request, String requestUrl, String securityKey) throws Exception {
        int code = requestUrl.hashCode() & (Integer.MAX_VALUE - 1);
        String cacheKey = HttpUtil.getCookieValue(request, SysConstains.COOKIE_MENU);
        if (StringUtils.isEmpty(cacheKey)) {
            return false;
        }
        String menuUrl = cacheService.get(cacheKey);
        if (StringUtils.isEmpty(menuUrl)) {
            return false;
        }
        menuUrl = AESUtil.decrypt(menuUrl, securityKey);
        String codes = "," + menuUrl + ",";
        String codeKey = "," + code + ",";
        if (codes.indexOf(codeKey) != -1) {
            return true;
        }
        return false;
    }
}
