package com.bizzan.bitrade.service;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.util.MessageResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Aspect
public class AssetControllerAop {

	@Autowired
    private RedisLock redisLock;

    //@Around("execution(*com.bizzan.bitrade.controller.*.*(..)) && @annotation(concurrentLock)")
	@Around("execution(com.bizzan.bitrade.util.MessageResult com.bizzan.bitrade.controller.AssetController.transfer (..)) || "
			+ "execution(com.bizzan.bitrade.util.MessageResult com.bizzan.bitrade.controller.MemberController.signIn (..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		log.info("LockAop, args.length={}", joinPoint.getArgs().length);
    	if(joinPoint.getArgs().length>0 && joinPoint.getArgs()[0] instanceof AuthMember) {
    		AuthMember member = (AuthMember)joinPoint.getArgs()[0];
    		String key = "ASSET_CONTROLLER_LOCK_:" + member.getId();
    		log.info("LockAop, key={}", key);
    		try {
                if(redisLock.lockBySeconds(key, 3)) {
            		log.info("LockAop, get key success");
                    return joinPoint.proceed();
                } else {
                    return MessageResult.error(500, "您的操作过于频繁，请稍后再试");
                }
            } finally {
                redisLock.delete(key);
            }
    	}
    	return joinPoint.proceed();
    }
}
