package com.zcxk.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;

/**
 * 分布式锁实现类
 */
/**
 * @author Andy
 * @date 2021-07-22 11:03
 */
@Component
@Slf4j
public class LocalRedisDistributedLock extends AbstractBaseRedis implements DistributedLock {

    private ThreadLocal<String> lockFlag = new ThreadLocal<>();

    private static final String UNLOCK_LUA;

    static {
        UNLOCK_LUA = "if utils.call(\"get\",KEYS[1]) == ARGV[1] "
            + "then "
            + "    return utils.call(\"del\",KEYS[1]) "
            + "else "
            + "    return 0 "
            + "end ";
    }

    @Override
    public boolean lock(String key, long expire, int retry, long sleepMillis) {
        // 如果获取锁失败，按照传入的重试次数进行重试
        boolean result = setRedis(key, expire);
        while ((!result) && retry-- > 0) {
            try {
                log.debug("lock failed, retrying..." + retry);
                Thread.sleep(sleepMillis);
            } catch (InterruptedException e) {
                return false;
            }
            result = setRedis(key, expire);
        }
        return result;
    }

    private boolean setRedis(final String key, final long expire) {
        try {
            RedisCallback<Boolean> callback = (connection) -> {
                String uuid = UUID.randomUUID().toString();
                lockFlag.set(uuid);
                return connection.set(key.getBytes(StandardCharsets.UTF_8), uuid.getBytes(
                    StandardCharsets.UTF_8), Expiration
                    .milliseconds(expire), RedisStringCommands.SetOption.SET_IF_ABSENT);
            };
            return (Boolean) redisTemplate.execute(callback);
        } catch (Exception e) {
            log.error("set utils lock error.", e);
        }
        return false;
    }


    @Override
    public boolean releaseLock(String key) {
        // 释放锁的时候，有可能因为持锁之后方法执行时间大于锁的有效期，此时有可能已经被另外一个线程持有锁，所以不能直接删除
        try {
            RedisCallback<Boolean> callback = (connection) -> {
                String value = lockFlag.get();
                // 不采用eval指令，因为运维出于安全考虑已经重命名了改命令
                byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
                if (Arrays.equals(value.getBytes(StandardCharsets.UTF_8), connection.get(keyBytes))){
                    return connection.del(keyBytes) > 0;
                }
                return false;
            };
            return (Boolean) redisTemplate.execute(callback);
        } catch (Exception e) {
            log.error("release lock occured an exception", e);
        } finally {
            // 清除掉ThreadLocal中的数据，避免内存溢出
            lockFlag.remove();
        }
        return false;
    }

//    private boolean setRedis(String key, long expire) {
//        try {
//            String uuid = UUID.randomUUID().toString();
//            lockFlag.set(uuid);
//            String result = jedisCluster.set(key, uuid, "NX", "PX", expire);
//            return !StringUtils.isEmpty(result);
//        } catch (Exception e) {
//            logger.error("set utils occured an exception", e);
//        }
//        return false;
//    }
//
//    @Override
//     boolean releaseLock(String key) {
//        // 释放锁的时候，有可能因为持锁之后方法执行时间大于锁的有效期，此时有可能已经被另外一个线程持有锁，所以不能直接删除
//        try {
//            List<String> keys = new ArrayList<>();
//            keys.add(key);
//            List<String> args = new ArrayList<>();
//            args.add(lockFlag.get());
//            // 使用lua脚本删除redis中匹配value的key，可以避免由于方法执行时间过长而redis锁自动过期失效的时候误删其他线程的锁
//            Long result = (Long) jedisCluster.eval(UNLOCK_LUA, keys, args);
//            return result != null && result > 0;
//        } catch (Exception e) {
//            logger.error("release lock occured an exception", e);
//        }
//        return false;
//    }



}
