package com.haha.common.utils;


import cn.hutool.core.util.RandomUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author skyline
 * @description 订单号生成
 * @date 2023-08-12 17:26
 */
public class OrderUtils {

    // 生成24位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NNNN,NNNN-CC，
    // 其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNNNNNN=随机数，CC=检查码

    /**
     * 生成订单号 32位
     *
     * @param str 一般只会传OperatorID
     * @return
     */
    public static String getOrderNo(String... str) {
        var orderNoMain = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).concat(String.valueOf(RandomUtil.randomInt(10000000, 99999999)));
        var orderNoSum = 0;
        for (int i = 0; i < orderNoMain.length(); i++) {
            orderNoSum += Integer.parseInt(orderNoMain.substring(orderNoMain.length() - 1));
        }
        var res = orderNoMain.concat(str_pad(String.valueOf((100 - orderNoSum % 100) % 100), 2, "0", "STR_PAD_LEFT"));
        return str.length > 0 ? str[0].substring(0, 8).concat(res) : res;
    }


    public static String str_pad(String input, int length, String pad, String sense) {
        int resto_pad = length - input.length();
        String padded = "";

        if (resto_pad <= 0) {
            return input;
        }

        if (sense.equals("STR_PAD_RIGHT")) {
            padded = input;
            padded += _fill_string(pad, resto_pad);
        } else if (sense.equals("STR_PAD_LEFT")) {
            padded = _fill_string(pad, resto_pad);
            padded += input;
        } else // STR_PAD_BOTH
        {
            int pad_left = (int) Math.ceil(resto_pad / 2);
            int pad_right = resto_pad - pad_left;

            padded = _fill_string(pad, pad_left);
            padded += input;
            padded += _fill_string(pad, pad_right);
        }
        return padded;
    }


    protected static String _fill_string(String pad, int resto) {
        boolean first = true;
        String padded = "";

        if (resto >= pad.length()) {
            for (int i = resto; i >= 0; i = i - pad.length()) {
                if (i >= pad.length()) {
                    if (first) {
                        padded = pad;
                    } else {
                        padded += pad;
                    }
                } else {
                    if (first) {
                        padded = pad.substring(0, i);
                    } else {
                        padded += pad.substring(0, i);
                    }
                }
                first = false;
            }
        } else {
            padded = pad.substring(0, resto);
        }
        return padded;
    }
}
