package com.jsowell.common.util.id;

import com.google.common.collect.Lists;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.redis.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

/**
 * 生成sn号Util
 */
@Component
public class SnUtils {

	private static Logger logger = LoggerFactory.getLogger(SnUtils.class);

	@Autowired
	public RedisCache redisCache;

	private String prefix = "88";

	/**
	 * 获取递增的序列号
	 * 充电桩编号定义为14位: 固定位88 + 年份23 + 10位自增数字不足补0
	 * @param prefix 生成序列号的前缀
	 * @return
	 */
	private String getPileSn(String prefix) {
		//序列号前缀加特定标识，如系统模块名之类的 防止重复
		String key = CacheConstants.PILE_SN_GENERATE_KEY + prefix;
		String increResult = null;
		try {
			Long increNum = redisCache.increment(key, 1);
			// 年份
			int year = LocalDate.now().getYear() - 2000;
			//不足补位
			increResult = prefix + year + String.format("%1$010d", increNum);
		} catch (Exception e) {
			logger.error("获取序列号失败", e);
		}
		return increResult;
	}



	/**
	 * 生成sn号
	 *
	 * @return
	 */
	public List<String> generateSN() {
		return generateSN(1);
	}

	/**
	 * 批量生成sn号
	 *
	 * @param size
	 * @return
	 */
	public List<String> generateSN(int size) {
		List<String> resultList = Lists.newArrayList();
		if (size <= 0) {
			return resultList;
		}
		for (int i = 0; i < size; i++) {
			resultList.add(getPileSn(prefix));
		}
		return resultList;
	}

}
