package com.inkasso.auth;

import com.inkasso.adapter.bean.AbstractUser;
import com.inkasso.adapter.exception.ServiceException;
import com.inkasso.adapter.exception.enums.ExceptionEnum;
import com.inkasso.adapter.web.LoginUserHolder;
import com.inkasso.auth.interfaces.HasPermission;
import org.apache.commons.lang3.StringUtils;
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.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
public class PermissionCheckBean {

  private static Logger logger = LoggerFactory.getLogger(PermissionCheckBean.class);

//  @Autowired(required = false)
//  HasPermissionHandler handler;

  @Pointcut("@annotation(com.inkasso.auth.interfaces.HasPermission) || @annotation(com.inkasso.auth.interfaces.PermissionAndCheck)")
  public void hasPermissionCheck() {
  }

  @Before("hasPermissionCheck()")
  public void check(JoinPoint joinPoint) {
//    if (handler == null) {
//      return;
//    }
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    HasPermission annotation = AnnotatedElementUtils.findMergedAnnotation(method,
        HasPermission.class);
    String roleCode = annotation.roleCode();
    String code = annotation.value();
    AbstractUser abstractUser = LoginUserHolder.get();

    if(!StringUtils.isEmpty(roleCode)){
      if(abstractUser.getRoles()==null|| !(abstractUser.getRoles().getCode().equals(code))){
            throw new ServiceException(401, ExceptionEnum.NO_PERMISSION);
      }
    }else{
//       //说明 要通过 权限点校验
      List<String> permissionCode = abstractUser.getPermissionCode();
      if(CollectionUtils.isEmpty(permissionCode)){
        throw new ServiceException(401, ExceptionEnum.NO_PERMISSION);
      }
      if(permissionCode.indexOf(code)<0){
        throw new ServiceException(401, ExceptionEnum.NO_PERMISSION);
      }
    }
   // boolean hasPermission = permissionCheckService.hasPermission(userIdentifier, code);
//    logger.info("校验权限用户id为->{} ,权限code为->{}", new Object[]{userIdentifier, code});
//    if (!hasPermission) {
//      handler.callBackOnFail();
//    }
  }

}