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.controller.OrderController;
import com.bizzan.bitrade.entity.transform.AuthMember;
import com.bizzan.bitrade.util.MessageResult;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Aspect
public class OrderControllerAop {

	@Autowired
    private RedisLock redisLock;
	@Autowired
    private LocaleMessageSourceService msService;

    //@Around("execution(*com.bizzan.bitrade.controller.*.*(..)) && @annotation(concurrentLock)")
	@Around("execution(com.bizzan.bitrade.util.MessageResult com.bizzan.bitrade.controller.OrderController.* (..)) || "
			+ "execution(com.bizzan.bitrade.util.MessageResult com.bizzan.bitrade.controller.WalletNewController.modifyLeverage (..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            log.info("OrderAop, args.length={}", joinPoint.getArgs().length);
            if (joinPoint.getArgs().length > 0 && joinPoint.getArgs()[0] instanceof AuthMember) {
                AuthMember member = (AuthMember) joinPoint.getArgs()[0];
                String key = "ORDER_CONTROLLER_LOCK_:" + member.getId();
                log.info("OrderAop, key={}", key);
                if (redisLock.lockBySeconds(key, 3)) {
                    try {
                        if (redisLock.lockTradingAccount(member.getId())) {
                            log.info("OrderAop, get key success");
                            return joinPoint.proceed();
                        } else {
                            // 没有获取到锁,则把key赋值为null,以免finally里解锁
                            key = null;
                            //throw new Exception("您的操作过于频繁，请稍后再试");
                            return MessageResult.error(500, msService.getMessage("ACCOUNT_CONCURRENCE"));
                        }
                    } finally {
                        // 执行完毕后解锁
                        if (key != null) {
                            log.info("OrderAop, get key release");
                            redisLock.unlockTradingAccount(member.getId());
                        }
                    }
                } else {
                    log.info("OrderAop, error={}", msService.getMessage("OPERATION_TOO_MUCH"));
                    return MessageResult.error(500, msService.getMessage("OPERATION_TOO_MUCH"));
                }
            } else {
                log.info("OrderAop, error={}", "illegal operation");
                return MessageResult.error(500, "illegal operation");
            }
        }catch (Exception e){
            log.info("OrderAop, error={}", e.getMessage());
            return MessageResult.error(500, "illegal operation");
        }
    }

}
