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;
import java.util.concurrent.atomic.AtomicInteger;

public class OrderUtil {

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

	static Date today = new Date();
	static AtomicInteger orderIndex = new AtomicInteger(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.intValue() > 0) {
			if (n.getYear() == today.getYear() && n.getMonth() == today.getMonth() && n.getDay() == today.getDay()) {
				orderIndex.getAndIncrement();
			} else {
				today = n;
				orderIndex = new AtomicInteger(1);
			}
		} else {
			today = n;
			orderIndex = new AtomicInteger(1);
		}
		if (orderIndex.intValue() > 9999) {
			orderIndex = new AtomicInteger(1);
		}
		String indexString = String.format("%s%s%04d", currTime, midFix, orderIndex.intValue());
		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)));
	}
}
