package com.tuoheng.common.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;

/**
 * 生成无人机产品识别码
 */
public class DroneCodeUtils {

    public static final String[] X36_ARRAY = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z".split(",");

    /**
     * @param brand  品牌 eg：THJS
     * @param series 系列 eg：Y0
     * @param type   型号 eg：A 一代
     * @return
     */
    public String createDroneCode(String brand, String series, String type) throws InterruptedException {
        return brand + series + type + createCode();
    }

    /**
     * 生成不重复的36进制字符串
     * @return
     * @throws InterruptedException
     */
    public String createCode() throws InterruptedException {
        String createCode="";
        synchronized (this) {
            Date date = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("MMddHHmmssSS");
            SimpleDateFormat dateFormaty = new SimpleDateFormat("yyyy");
            String code = dateFormat.format(date);
            String nowYear = dateFormaty.format(date);
            long addSum = (long) ((Integer.parseInt(nowYear) - 2021) * 12 * Math.pow(10, 11));
            Thread.sleep(100);
            String string36 = tenTo36(Long.parseLong(code) + addSum);
            createCode=nowYear + string36;
        }
        return createCode;
    }

    /**
     * 十进制转36精制
     * @param num
     * @return
     */
    public static String tenTo36(long num) {
        StringBuffer sBuffer = new StringBuffer();
        if (num == 0) {
            sBuffer.append("0");
        }
        while (num > 0) {
            sBuffer.append(X36_ARRAY[Integer.parseInt(String.valueOf(num % 36))]);
            num = num / 36;
        }
        return sBuffer.reverse().toString();
    }
}
