package com.github.wxiaoqi.security.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class OrderUtil {

	public static final String DEFAULT_MID = "00";
	public static final String APP_MID = "01";

	static Date today = new Date();
	static int orderIndex = 0;

	@SuppressWarnings("deprecation")
	private static String getIndex(String midFix) {
		if(StrUtil.isBlank(midFix)) {
			midFix = DEFAULT_MID;
		}
		Date n = new Date();
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String currTime = outFormat.format(n);

		if (orderIndex > 0) {
			if (n.getYear() == today.getYear() && n.getMonth() == today.getMonth() && n.getDay() == today.getDay()) {
				orderIndex += 1;
			} else {
				today = n;
				orderIndex = 1;
			}
		} else {
			today = n;
			orderIndex = 1;
		}
		if (orderIndex > 9999) {
			orderIndex = 1;
		}
		String indexString = String.format("%s%s%04d", currTime, midFix, orderIndex);
		return indexString;
	}

	/**
	 * 生成订单号
	 * 
	 * @param preFixString
	 * @return
	 */
	public static String GetOrderNumber(String preFixString) {
		String orderNumberString = preFixString + getIndex("");
		return orderNumberString;
	}

	/**
	 * 添加中间代号数字区别，放前面不好看
	 *
	 * @param preFixString
	 * @return
	 */
	public static String GetOrderNumber(String preFixString, String midFix) {
		String orderNumberString = preFixString + getIndex(midFix);
		return orderNumberString;
	}

	/**
	 * 获取时间戳
	 * 
	 * @return
	 */
	public static String GetTimestamp() {
		return Long.toString(new Date().getTime() / 1000);
	}

	/**
	 * 生成随机数
	 * 
	 * @return
	 */
	public static String CreateNoncestr() {
		Random random = new Random();
		return MD5.GetMD5String(String.valueOf(random.nextInt(10000)));
	}
}
