package com.casic.missiles.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description: 编号生成工具
 * @Author: wangpeng
 * @Date: 2022/11/26 15:31
 */
public class NumberGeneratorUtil {

    /**
     * 支持每天最多生成9999个序号
     *
     * @param prefix
     * @param nowNum
     * @return
     */
    public static synchronized String getContactNo(String prefix, long nowNum) {
        StringBuilder builder = new StringBuilder();
        StringBuilder num = new StringBuilder();
        AtomicLong count = new AtomicLong(nowNum);

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String datePrefix = format.format(new Date());

        if(nowNum == 0){
            count = new AtomicLong(0);
            num.append(datePrefix).append("000").append(count.incrementAndGet());
        }else{
            String s = String.valueOf(nowNum);
            String substring = s.substring(0, s.length() - 4);
            //不是当前日期，从0计算后4位
            if (Long.valueOf(datePrefix) > Long.valueOf(substring)) {
                count = new AtomicLong(0);
                num.append(datePrefix).append("000").append(count.incrementAndGet());
            } else {
                num.append(count.incrementAndGet());
            }
        }

        // 组合
        builder.append(prefix);
        builder.append(num);
        return builder.toString();
    }

    /**
     * 证书报告编号生成
     * @param prefix
     * @param nowNum
     * @return
     */

    public static synchronized String getCode(String prefix, long nowNum) {
        StringBuilder builder = new StringBuilder();
        StringBuilder num = new StringBuilder();
        AtomicLong count = new AtomicLong(nowNum);

        SimpleDateFormat format = new SimpleDateFormat("yyyyMM");
        String datePrefix = format.format(new Date());

        if(nowNum == 0){
            count = new AtomicLong(0);
            num.append(datePrefix).append("00").append(count.incrementAndGet());
        }else{
            String s = String.valueOf(nowNum);
            String substring = s.substring(0, s.length() - 3);
            //不是当前日期，从0计算后4位
            if (Long.valueOf(datePrefix) > Long.valueOf(substring)) {
                count = new AtomicLong(0);
                num.append(datePrefix).append("00").append(count.incrementAndGet());
            } else {
                num.append(count.incrementAndGet());
            }
        }

        // 组合
        builder.append(prefix);
        builder.append(num);
        return builder.toString();
    }

}
