package com.ms.biz.paas;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 用redis实现的FIFO队列
 */
@Slf4j
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void set(String key, String value, long expire) {
        log.info("set key: {}, value: {}", key, value);
        redisTemplate.opsForValue().set(key, value, expire);
    }

    public String get(String key) {
        log.info("get key: {}", key);
        return redisTemplate.opsForValue().get(key);
    }

    public void delete(String key) {
        log.info("delete key: {}", key);
        redisTemplate.delete(key);
    }

    public long push(String key, String value) {
        log.info("push key: {}, value: {}", key, value);
        return redisTemplate.opsForList().leftPush(key, value);
    }

    /**
     * 优先插入队列头部
     * @param key
     * @param value
     */
    public long pushHead(String key, String value) {
        log.info("pushHead key: {}, value: {}", key, value);
        return redisTemplate.opsForList().leftPush(key, value);
    }

    public String pop(String key) {
        String result = redisTemplate.opsForList().rightPop(key);
        log.info("pop key: {}, value: {}", key, result);
        return result;
    }

    /**
     * 优先取队列尾部
     * @param key
     * @return
     */
    public String popTail(String key) {
        String result = redisTemplate.opsForList().leftPop(key);
        log.info("popTail key: {}, value: {}", key, result);
        return result;
    }

    /**
     * 尝试获取锁
     *
     * @param key 锁的key
     * @param value 锁的value
     * @param timeout 超时时间（秒）
     * @return 是否获取成功
     */
    public boolean tryLock(String key, String value, long timeout) {
        // 使用setIfAbsent (对应于Redis的SETNX命令)来尝试设置值，成功则表示获取锁，失败表示锁已存在
        boolean lock = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
        if (!lock) {
            // 锁已存在，获取锁的值（当前持有锁的线程的标识）并检查是否与当前线程的标识相同
            String currentValue = redisTemplate.opsForValue().get(key);
            // 如果锁已过期
            if (currentValue != null && currentValue.equals(value)) {
                return true;
            }
        }
        return lock;
    }

    /**
     * 释放锁
     *
     * @param key 锁的key
     * @param value 锁的value（用于确保只有锁的持有者才能释放锁）
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = redisTemplate.opsForValue().get(key);
            if (currentValue != null && currentValue.equals(value)) {
                redisTemplate.delete(key);
            }
        } catch (Exception e) {
            // 打印异常
            e.printStackTrace();
        }
    }

}
