package com.brilliance.isc.common.bopset.counter.service.impl;


import com.brilliance.isc.common.bopset.counter.mapper.CounterRmbMapper;
import com.brilliance.isc.common.bopset.counter.service.CounterRmbService;
import com.brilliance.isc.counter.service.SerialCounterService;
import com.brilliance.mda.runtime.mda.util.Strings;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

@Service()
public class CounterRmbServiceImpl implements CounterRmbService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    public CounterRmbMapper counterRmbMapper;
    public ReentrantLock lock = new ReentrantLock();

    @Value("${counter.step:1}")
    private Integer step;

    @Value("${counter.start:0}")
    private Integer start;

    @Resource
    private RedissonClient redissonClient;

    @Autowired
    private SerialCounterService serialCounterService;


    @Override
    public int dbRmbCounter(String couNam, Date dat)
    {
        //处理并发场景，替换原有发号逻辑
        String vcounam = Strings.trim(couNam);
        return (int) serialCounterService.genSerialNumberByDb("rmbcou",vcounam,dat);
        /*
        RBucket<String> bucket = redissonClient.getBucket(couNam);
        boolean success = bucket.trySet("X",1, TimeUnit.SECONDS);
        if(!success){
            success = bucket.trySet("X",1, TimeUnit.SECONDS);
            if(!success){
                throw new RestBizException("70001","无法获取报送编号");
            }
        }
        Integer couval = counterRmbMapper.getCountValWithUpdate(couNam,dat);
        if(couval != null)
        {

            try {
                couval = counterRmbMapper.getCountValWithUpdate(couNam,dat);
                if(couval != null) {
                    counterRmbMapper.updateCounter(couNam,dat); //计算器增加
                }
            }catch (Exception e){
                logger.debug("主键生成异常:{}",e);
                throw(new CommonServiceException("主键生成异常"));
            }finally {
                bucket.delete();
            }
        }else{
            counterRmbMapper.insertCounter(couNam,start,step,dat); //插入新数
        }
        couval = counterRmbMapper.getCountValWithUpdate(couNam,dat);
        bucket.delete();
        return couval;

         */
    }

}
