package com.brilliance.isc.common.lock.common;

import com.brilliance.isc.common.transaction.vo.BaseTransactionVo;
import com.brilliance.isc.constant.ErrorCode;
import com.brilliance.isc.exception.RestBizException;
import com.brilliance.mda.runtime.mda.util.MdaUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class BizRepeatComponent {

    private final Logger logger = LoggerFactory.getLogger(BizRepeatComponent.class);


    @Resource
    private RedissonClient redissonClient;


    /**
     * 校验是否发生提交
     * @param baseTransactionVo
     */
    public void checkAndSetRepeatLock(BaseTransactionVo baseTransactionVo){
        if(baseTransactionVo.getTrnInfo() == null){
            logger.warn("当前请求没有发送交易流水号");
            return;
        }
        String transId = baseTransactionVo.getTrnInfo().getFormNo();
        RBucket bucket = redissonClient.getBucket(transId);
        //锁定一天，避免被重复提交
        boolean isSuccess = bucket.trySet("X",23, TimeUnit.HOURS);
        if (!isSuccess) {
            logger.error("当前交易{},表单号{},重复提交",baseTransactionVo.getTransName(),transId);
            throw  new RestBizException(ErrorCode.LOCK_SUBMIT_REPEAT,"业务数据已提交，请勿重复提交!");
        }
        logger.info("当前交易{},表单号{},设置防重复提交状态位成功",baseTransactionVo.getTransName(),transId);
    }

    public void releaseRepeatLock(BaseTransactionVo baseTransactionVo){
        if(baseTransactionVo.getTrnInfo() == null){
            logger.warn("当前请求没有发送交易流水号");
            return;
        }
        String transId = baseTransactionVo.getTrnInfo().getFormNo();
        RBucket bucket = redissonClient.getBucket(transId);
        bucket.delete();
        logger.info("完成解锁{}业务{},",baseTransactionVo.getTransName(),transId);
    }


    public void checkAndSetRepeatLock(String transId,String transName){
        if(MdaUtils.isEmpty(transId)){
            return;
        }
        RBucket bucket = redissonClient.getBucket(transId);
        //锁定一天，避免被重复提交
        boolean isSuccess = bucket.trySet("X",23, TimeUnit.HOURS);
        if (!isSuccess) {
            logger.error("当前交易{},表单号{},重复提交",transName,transId);
            throw  new RestBizException(ErrorCode.LOCK_SUBMIT_REPEAT,"业务数据已提交，请勿重复提交!");
        }
        logger.info("当前交易{},表单号{},设置防重复提交状态位成功",transName,transId);
    }

    public void releaseRepeatLock(String transId,String transName){
        if(MdaUtils.isEmpty(transId)){
            logger.warn("当前请求没有发送交易流水号");
            return;
        }
        RBucket bucket = redissonClient.getBucket(transId);
        bucket.delete();
        logger.info("完成解锁{}业务{},",transName,transId);
    }
}
