package com.crm.rely.backend.util;

import com.crm.rely.backend.configuration.ApplicationContextProvider;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @description:
 * @author: houn
 * @create: 2020-07-08 14:25
 **/
public class CidUtil {
    @Autowired
    private static RedisService redisService;

    public static Integer getCid() throws InterruptedException, ServiceException {
        if (redisService == null) {
            redisService = ApplicationContextProvider.getBean(RedisService.class);
        }
        String uuid = UUIDUtil.getUUID();
        Integer autoNumber = null;
        try {
            redisService.tryLock(Constants.CID_CONTROL_AUTO_NUMBER, uuid);
            autoNumber = redisService.getObject(Constants.CID_CONTROL_AUTO_NUMBER);
            if (autoNumber == null) {
                autoNumber = 0;
            }
            autoNumber++;
            redisService.saveObject(Constants.CID_CONTROL_AUTO_NUMBER, autoNumber);
        } finally {
            redisService.unlock(Constants.CID_CONTROL_AUTO_NUMBER, uuid);
        }
        
        return autoNumber;
    }
}
