package com.ylx.web.controller.massage;

import com.ylx.common.core.domain.R;
import com.ylx.common.exception.ServiceException;
import com.ylx.massage.domain.TRecharge;
import com.ylx.massage.service.TRechargeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 充值记录表 前端控制器
 */
@RestController
@Slf4j
@Api(tags = {"充值记录"})
@RequestMapping("api/recharge/v1")
public class TRechargeController {
    @Resource
    private TRechargeService rechargeService;

    @Resource
    private RedissonClient redissonClient;

    @ApiOperation("微信充值")
    @RequestMapping(value = "wx/add", method = RequestMethod.POST)
    private R add(@RequestBody TRecharge recharge) {
        try {
            return R.ok(rechargeService.recharge(recharge));
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.fail("系统异常");
        }
    }

    @ApiOperation("微信充值")
    @RequestMapping(value = "test", method = RequestMethod.POST)
    private R test(@RequestBody TRecharge recharge) {
        RLock lock = redissonClient.getLock("lock"+recharge.getRechargeNo());

        try {
            if(!lock.tryLock()){
                return R.ok("当前单号正在操作");
            }else {
                Thread.sleep(10000);
                return R.ok("好");
            }
        } catch (ServiceException s) {
            log.error(s.getMessage());
            return R.fail(s.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.fail("系统异常");
        } finally {
            if(lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


}
