package com.keao.edu.common.service.impl;

import com.keao.edu.common.redis.service.RedisCache;
import com.keao.edu.common.service.IdGeneratorService;
import org.apache.commons.lang3.StringUtils;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class RedisIdGeneratorService implements IdGeneratorService {

	private final static Logger log = LoggerFactory.getLogger(RedisIdGeneratorService.class);

	private static final String keyPrefix = "smart";

	private final String defaultPwd = "666666";

	@Autowired
	private RedisCache<String, Object> redisCache;

	@Value("${message.debugMode}")
	private boolean debugMode;

	/**
	 * @Description
	 * @author butterfly
	 */
	private String getIDPrefix() {
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int day = c.get(Calendar.DAY_OF_MONTH); // 今天是第多少天
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		String monthFmt = String.format("%1$02d", month);
		String dayFmt = String.format("%1$02d", day); // 0补位操作 必须满足三位
		String hourFmt = String.format("%1$02d", hour); // 0补位操作 必须满足2位
		String minuteFmt = String.format("%1$02d", minute); // 0补位操作 必须满足2位
		String secondFmt = String.format("%1$02d", second); // 0补位操作 必须满足2位
		StringBuffer prefix = new StringBuffer();
		prefix.append((year - 2000)).append(monthFmt).append(dayFmt).append(hourFmt).append(minuteFmt).append(secondFmt);
		return prefix.toString();
	}

	/**
	 * @author butterfly
	 */
	private long incrDistrId(String biz) {
		String prefix = getIDPrefix();
		String orderId = null;
		String key = "#{biz}:id:".replace("#{biz}", biz).concat(prefix); // 001
		RedisTemplate<String, Object> redisTemplate = redisCache.getRedisTemplate();
		try {
			ValueOperations<String, Object> valueOper = redisTemplate.opsForValue();
			Long index = valueOper.increment(key, 1);
			orderId = prefix.concat(String.format("%1$05d", index)); // 补位操作 保证满足3位
		} catch (Exception ex) {
			log.error("分布式订单号生成失败异常。。。。。", ex);
		} finally {
			redisTemplate.expire(key, 600, TimeUnit.SECONDS);// 保留10分钟内的key
		}
		if (StringUtils.isEmpty(orderId))
			return 0;
		return Long.parseLong(orderId);
	}

	/**
	 * @Description 生成分布式ID
	 * @author butterfly
	 */
	@Override
	public long generatorId(String biz) {
		// 转成数字类型，可排序
		return incrDistrId(biz);
	}

	@Override
	public long generatorId() {
		return incrDistrId(keyPrefix);
	}

	@Override
	public boolean verifyValidCode(String mobile, String authCode) {
		if (debugMode) {
			if (defaultPwd.equals(authCode)) {
				return true;
			}
		} else {
			String key = "verificationCodeSMS_VERIFY_CODE_LOGIN" + mobile;
			Object object = redisCache.get(key);
			log.info("*********************mobile:{} smsCode:{} inutCode:{}******************", key, object, authCode);
			String verifyCode = object == null ? null : object.toString();
			if (StringUtils.isNoneEmpty(verifyCode) && StringUtils.equalsIgnoreCase(verifyCode, authCode)) {
				return true;
			}
		}
		return false;
	}

}
