package com.dhcc.finance.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.core.RedisTemplate;

import com.dhcc.common.constant.enums.DatacenterIdEnum;
import com.dhcc.common.util.SnowflakeIdWorker;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @功能描述:生成雪花算法实例
 * @author chenrui
 * @date 2019年12月13日 下午4:52:58
 * @修改日志:
 */
@Configuration
@Slf4j
public class IdWorkerConfig {

	@Value("${spring.application.name}") 
    private String applicationName;  
	
	@Value("${eureka.instance.instanceId}") 
    private String instanceId;  

	@Bean
	@DependsOn("redisTemplate")
	public SnowflakeIdWorker idWorker(RedisTemplate<String, Object> redisTemplate) {
		Long workerId = this.genWorkerId(redisTemplate);
		SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(workerId, DatacenterIdEnum.DHCC_FINANCE_SERVER.getCode());
		SnowflakeIdWorker.setInstance(snowflakeIdWorker);
		return snowflakeIdWorker;
	}
	
	/**
	 * 
	 * @Title: genWorkerId
	 * @Description: 生成工作区ID
	 * @param redisTemplate
	 * @return Long
	 * @author chenrui
	 * @date 2019年12月13日 下午4:53:13
	 * @modifyLog:
	 */
	private Long genWorkerId(RedisTemplate<String, Object> redisTemplate) {
		Integer workerId = 0;
		try {
			redisTemplate.setEnableTransactionSupport(true);
			workerId = (Integer) redisTemplate.opsForValue().get(instanceId);
			if( workerId == null ) {
				Integer genWorkerId = redisTemplate.opsForValue().increment(applicationName, 1).intValue();
				if( genWorkerId  > SnowflakeIdWorker.MAX_WORKER_ID ) {
					genWorkerId = 1;
					redisTemplate.opsForValue().set(applicationName, 0);
				} 
				workerId = genWorkerId;
				redisTemplate.opsForValue().set(instanceId, workerId);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("\r\n当前服务实例工作区ID:{}", workerId);	
		return workerId.longValue();
	}
}