package com.liquidnet.commons.lang.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class IDGenerator {
    private static final String CROSS_BAR = "-";
    private static final String EMPTY_STR = "";
    private static final DateTimeFormatter MILLISECOND = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    public static String nextSnowId() {
        return GenSnowFlowerUtil.next();
    }

    public static String nextTimeId() {
        return nextMilliId() + String.valueOf(System.nanoTime()).substring(9);
    }

    public static String nextMilliId() {
        return LocalDateTime.now().format(MILLISECOND);
    }

    public static String get32UUID() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return (new UUID(random.nextLong(), random.nextLong())).toString().replace(CROSS_BAR, EMPTY_STR);
    }

    /**
     * 根据订单id生成订单号
     *
     * @param orderTicketId
     * @return
     */
    public static String ticketOrderCode(String orderTicketId) {
        String number = orderTicketId;
        int len = orderTicketId.length();
        String time = System.currentTimeMillis() / 1000 + "";
        String orderCode = number.substring(0, len - 4);
        orderCode += time.substring(7, 8);
        orderCode += number.substring(len - 2);
        orderCode += time.substring(8, 9);
        orderCode += number.substring(len - 4, len - 2);
        return orderCode;
    }

    public static String payCode(){
        return "PAY"+nextTimeId();
    }

    public static String refundCode(){
        return "RED"+nextTimeId();
    }

    /**
     * 根据 订单号生成qrCode
     *
     * @param orderTicketId
     * @return String
     */
    public static String ticketQrCode(String orderTicketId) {
        String qrCode = MD5Utils.md5(orderTicketId).toLowerCase();
        return "QR" + qrCode.substring(5) + "" + qrCode.substring(0, 4);
    }

    public static void main(String[] args) {
        System.out.println(""+IDGenerator.payCode());
        System.out.println(""+IDGenerator.refundCode());
        System.out.println("nextTimeId==="+IDGenerator.nextTimeId());
        System.out.println("nextMilliId==="+IDGenerator.nextMilliId());
        System.out.println("nextSnowId==="+IDGenerator.nextSnowId());
        System.out.println("get32UUID==="+IDGenerator.get32UUID());
    }
}
