package com.jsowell.pile.util;

import com.google.common.collect.Lists;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.service.PileBasicInfoService;
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
	private RedisCache redisCache;

	@Autowired
	private PileBasicInfoService pileBasicInfoService;

	private String prefix = "88";

	/**
	 * 获取递增的序列号
	 * 充电桩编号定义为14位: 固定位88 + 年份23 + 10位自增数字不足补0
	 * @param prefix 生成序列号的前缀
	 * @return
	 */
	public String getPileSn(String prefix) {
		//序列号前缀加特定标识，如系统模块名之类的 防止重复
		String key = CacheConstants.PILE_SN_GENERATE_KEY + prefix;
		String increResult = null;
		try {
			// 取缓存
			Integer pileNum = redisCache.getCacheObject(key);
			if (pileNum == null) {
				// 缓存中没有，从数据库中取
				PileBasicInfo pileInfo = pileBasicInfoService.getMaxNumPileInfo();
				String pileSn = pileInfo.getSn();
				// 将前四位截取，并将后面转为long
				Long pileSnNum = Long.parseLong(StringUtils.substring(pileSn, 4, pileSn.length()));
				// String pileSnNum = StringUtils.substring(pileSn, 4, pileSn.length());
				// 再将该值存入数据库
				redisCache.setCacheObject(key, pileSnNum.intValue());

			}
			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;
	}

	public static void main(String[] args) {
		// String pileSn = "88230000002060";
		// String substring = StringUtils.substring(pileSn, 4, pileSn.length());
		// long l = Long.parseLong(substring);
		// System.out.println(substring);
		// System.out.println(l);

		Long a = 3147483647L;
	}

	/**
	 * 生成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;
	}

}
