package com.ruoyi.app.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.UserWallet;
import com.ruoyi.system.service.IUserWalletService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/myTest")
public class MyTestController {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private IUserWalletService userWalletService;

    @Anonymous
    @Auth
    @GetMapping("/testWallect")
    public AjaxResult testWallect(@RequestHeader String token, @RequestParam BigDecimal balance){
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        UserWallet userWallet = userWalletService.selectByUserId(Long.valueOf(id));
        String lockKey = "user:wallet:"+id;
        RLock lock=redissonClient.getLock(lockKey);
        try {
            // 加锁
            boolean islock = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if(islock){
//                userWalletService.updateUserWalletWithLock(userWallet.getId(),userWallet.getVersion(),null,balance);
                // 业务逻辑
                return AjaxResult.success("成功");
            }else {
                return AjaxResult.error("失败");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 解锁
            lock.unlock();
        }
    }

}
