package org.dromara.zhishu.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import jakarta.annotation.Resource;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/test")
public class TestController {


    @Resource
    Redisson redisson;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping("/sub_stock")
    @SaIgnore
    public String deductStock5() {
        String lockKey = "lock_good_stock";
        RLock lock = redisson.getLock(lockKey);
        lock.lock(60, TimeUnit.SECONDS);
        try {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("good_stock"));
            if (stock > 0) {
                int realStock = stock - 1;
                stringRedisTemplate.opsForValue().set("good_stock", realStock + "");
                System.out.println("扣减成功，剩余库存:" + realStock);
            } else {
                System.out.println("扣减失败，库存不足");
            }
        } finally {
            lock.unlock();
        }
        return "ok";
    }

    @SaIgnore
    @RequestMapping("/add_stock")

    public String addStock() {
        stringRedisTemplate.opsForValue().set("good_stock", "60");
        return "ok";
    }

    @SaIgnore
    @RequestMapping("/get_stock")

    public String get_stock() {
        return stringRedisTemplate.opsForValue().get("good_stock");
    }


      @SaIgnore
    @RequestMapping("/sub_stock1")

    public String sub_stock1() {
          String lockKey = "lock_good_stock";
          RLock lock = redisson.getLock(lockKey);
          lock.lock(30, TimeUnit.SECONDS);
          try {
              int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("good_stock"));
              if(stock>0){
                  stringRedisTemplate.opsForValue().set("good_stock", stock-1 + "");
                  System.out.println("库存不足");
              }else{
                  System.out.println("库存不足");
              }

          }catch (Exception e){

          }finally {
              lock.unlock();
          }





        return stringRedisTemplate.opsForValue().get("good_stock");
    }




}
