package cn.component.logger;

import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import cn.common.annotation.VLicense;
import cn.common.exception.UserException;
import cn.security.license.core.verify.LicenseVerifyManager;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;

/**
 * 系统加载安装好证书后，此类控制登录用户数不能大于授权人数
 * 
 * */
@Component
@Aspect
public class VLicenseAspect 
{
	//已经登陆用户数量
    private static int loginUserAmount = 0;
  
    //配置织入点
    @Pointcut("@annotation(cn.common.annotation.VLicense)")
    public void licensePointCut() {
    }
   	/**
     * 处理完请求后执行
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "licensePointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
    	// 获得注解
		VLicense ctrlVLicense = null;
		try {
			ctrlVLicense = getAnnotationLog(joinPoint);
		} catch (Exception e) {
			return;
		}
        if (IsKit.isNull(ctrlVLicense)) {
            return;
        }
        if("LOGIN".equals(ctrlVLicense.LoginOut())){
			++loginUserAmount;
		}
		else {
			--loginUserAmount;
		}
      //会缓存证书中最大用户注册数的
    	int registerAmount = TypeKit.objToInt(LicenseVerifyManager.info().get("registerAmount"));
		LogKit.info("目前在线人数："+ (loginUserAmount));
    	if(loginUserAmount > registerAmount){
         	LogKit.info("系统当前用户数超过最大用户注册限制数【"+registerAmount+"】");
         	throw new UserException("user.login.num",null);
        }
    }
    /**
     * 是否存在注解，如果存在就获取
     */
    private VLicense getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(VLicense.class);
        }
        return null;
    }
}
