package com.hotent.base.service.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Service;

import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.exception.BaseException;
import com.hotent.base.service.RedisLock;
import com.hotent.base.util.ResubmitLock;

import java.util.function.Supplier;

/**
 *
 * @company 广州宏天软件股份有限公司
 * @author jason
 * @email liygui@jee-soft.cn
 * @date 2021年03月02日
 */
@Service
public class MemoryLockImpl implements RedisLock{
	private final static int DELAY_SECONDS = 5;
	
	private final static Object PRESENT = new Object();
	
	@Override
	public Object commitRedisLock(String key, ProceedingJoinPoint joinPoint) throws Throwable {
		 //执行锁
        boolean lock = false;
        try {
            //设置解锁key
            lock = ResubmitLock.getInstance().lock(key, PRESENT);
            if (lock) {
                //放行
                return joinPoint.proceed();
            } else {
                //响应重复提交异常
            	throw new BaseException(ResponseErrorEnums.REPEATABLE_COMMIT);
            }
        } finally {
            //设置解锁key和解锁时间
            ResubmitLock.getInstance().unLock(lock, key, DELAY_SECONDS);
        }
	}
    @Override
    public Boolean methodRedisLock(String key, Supplier<Boolean> supplier) {
        int maxCountSloop = 10;
        for (int i=0;i<maxCountSloop;i++){
            boolean lock = false;
            try {
                //设置解锁key
                lock = ResubmitLock.getInstance().lock(key, PRESENT);
                if (lock) {
                    return supplier.get();
                }
            } finally {
                //设置解锁key和解锁时间
                ResubmitLock.getInstance().unLock(lock, key, DELAY_SECONDS);
            }
        }
        return false;
    }
}
