package com.jiuzhekan.cbkj.common.utils;

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

public class MakeOrderNum {
    /**
     * 锁对象，可以为任意对象
     */
    private static final Object lockObj = "lockerOrder";
    /**
     * 订单号生成计数器
     */
    private static long orderNumCount = 0L;
    /**
     * 每毫秒生成订单号数量最大值
     */
    private static int maxPerMSECSize = 1000;

    /**
     * 生成非重复订单号，理论上限1毫秒1000个，可扩展
     */
    public static String makeOrderNum() {
        // 最终生成的订单号
        String finOrderNum = "";
        try {
            synchronized (lockObj) {
                // 取系统当前时间作为订单号变量前半部分，精确到毫秒
                long nowLong = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
                // 计数器到最大值归零，可扩展更大，目前1毫秒处理峰值1000个，1秒100万
                if (orderNumCount >= maxPerMSECSize) {
                    orderNumCount = 0L;
                }
                //组装订单号
                String countStr = maxPerMSECSize + orderNumCount + "";
                finOrderNum = nowLong + countStr.substring(1);
                orderNumCount++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return finOrderNum;
        }
    }


    /**
     * 当前日期
     */
    private static String makeDay = "makeDay";
    /**
     * 编号
     */
    private static int dayNum = 1;
    /**
     * 编号阈值
     */
    private static int dayMaxNum = 1000;

    /**
     * 编号阈值
     */
    private static int dayMaxNum2 = 10000;


    /**
     * 生成编号（前三位从001开始自增长，后五位为1位年2位月2位日）
     *
     * @return java.lang.String
     * @author guowei
     * @date 2021/5/12
     */
    public static String makeDayNum() {
        String finalDayNum = "";
        String nowDate = DateUtil.getDateFormats("yyMMdd", new Date()).substring(1);
        if (!nowDate.equals(makeDay)) {
            makeDay = nowDate;
        }

        synchronized (lockObj) {
            if (dayNum >= dayMaxNum) {
                dayNum = 1;
            }

            String countStr = dayMaxNum + dayNum + "";
            finalDayNum = countStr.substring(1) + makeDay;
            dayNum++;
        }

        return finalDayNum;
    }

    /**
     * 生成编号（BZ+四位自增长+日期）
     *
     * @return java.lang.String
     * @author wangtao
     * @date 2021/5/12
     */
    public static String makeBzNum() {
        String finalDayNum = "";
        String nowDate = DateUtil.getDateFormats("yyyyMMdd", new Date());
        if (!nowDate.equals(makeDay)) {
            makeDay = nowDate;
        }

        synchronized (lockObj) {
            if (dayNum >= dayMaxNum2) {
                dayNum = 1;
            }

            String countStr = dayMaxNum2 + dayNum + "";
            finalDayNum = "BZ" + countStr.substring(1) + makeDay;
            dayNum++;
        }

        return finalDayNum;
    }


    public static void main(String[] args) {
      for (int i = 1; i <= 10000; i++) {
        new Thread(new MyThread()).start();
      }
    }

}