<?php

use Illuminate\Support\Facades\Lang;

/**
 * @notes 生成密码加密密钥
 * @param string $plaintext
 * @param string $salt
 * @return string
 * @author 段誉
 * @date 2021/12/28 18:24
 */
function create_password(string $plaintext, string $salt = 'likeadmin') : string
{
    return md5($salt . md5($plaintext . $salt));
}

if (!function_exists('env')) {
    function env($key, $default = null)
    {
        return env($key, $default); // 直接使用 Laravel 全局 env() 函数
    }
}

/**
 * 格式化小数：去掉末尾无用的0，但至少保留1位小数
 * @param float|string $number 要格式化的数字
 */
function formatDecimal($number, $len = 1)
{
    // 先转成浮点数，去掉末尾多余的0
    $num = (float)$number;

    // 判断是否是整数（如 2.000 → 2）
    if (floor($num) == $num) {
        return number_format($num, $len); // 强制保留$len位小数
    }

    // 非整数，返回去掉末尾0的结果
    return rtrim(rtrim((string)$num, '0'), '.');
}

/**
 * @notes 随机生成token值
 * @param string $extra
 */
function create_token(string $extra = '')
{
    $salt = env('unique_identification', 'likeadmin');
    $encryptSalt = md5( $salt . uniqid());
    return md5($salt . $extra . time() . $encryptSalt);
}


if (!function_exists('list_to_tree')) {
    function list_to_tree($elements, $parentKey = "parent_id", $parentId = 0): array
    {
        $branch = [];
        foreach ($elements as $element) {
            if ($element[$parentKey] == $parentId) {
                $children = list_to_tree($elements, $parentKey, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }
        return $branch;
    }
}

if (!function_exists('custom_sort')) {
    function custom_sort($a, $b)
    {
        // 定义排序规则
        $order = [
            '大', '小', '单', '双',
            '大单', '大双', '小单', '小双',
            '极大', '极小',
            '对子', '顺子', '豹子',
            '0操', '1操', '2操', '3操', '4操', '5操', '6操', '7操', '8操', '9操',
            '10操', '11操', '12操', '13操', '14操', '15操', '16操', '17操', '18操',
            '19操', '20操', '21操', '22操', '23操', '24操', '25操', '26操', '27操',
            '尾大', '尾小', '尾单', '尾双',
            '尾大双', '尾大单', '尾小双', '尾小单',
            '0尾', '1尾', '2尾', '3尾', '4尾', '5尾', '6尾', '7尾', '8尾', '9尾',
            'A大', 'A小', 'A单', 'A双',
            'B大', 'B小', 'B单', 'B双',
            'C大', 'C小', 'C单', 'C双',
            '0A', '1A', '2A', '3A', '4A', '5A', '6A', '7A', '8A', '9A',
            '0B', '1B', '2B', '3B', '4B', '5B', '6B', '7B', '8B', '9B',
            '0C', '1C', '2C', '3C', '4C', '5C', '6C', '7C', '8C', '9C',
            '一段', '二段', '三段', '四段',
        ];

        // 找出每个元素的排序位置
        $index_a = array_search($a, $order);
        $index_b = array_search($b, $order);

        // 如果找不到，则按字母和数字升序排列
        if ($index_a === false && $index_b === false) {
            return strcmp($a, $b);
        }

        return $index_a - $index_b;
    }
}

if (!function_exists('lang')) {
    function lang(string $key, array $data = []): string
    {
        $msg = Lang::get("messages.{$key}", $data);
        if ($msg === "messages.{$key}") return $key;
        return $msg;
    }
}


if (!function_exists('get_cache_key')) {
    function get_cache_key(string $id): string
    {
        return 'user_' . $id . '_captcha_code';
    }
}

if (!function_exists('get_step_key')) {
    function get_step_key($chatId)
    {
        return "{$chatId}_status";
    }
}

if (!function_exists('is_valid_date')) {
    function is_valid_date($date)
    {
        // 使用正则表达式匹配 yyyy-mm-dd 格式的日期
        return preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) === 1;
    }
}


if (!function_exists('getUuid')) {
    function getUuid()
    {
        // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
        $data = random_bytes(16);

        // Set version to 0100
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set bits 6-7 to 10
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

        // Output the 36 character UUID.
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
}

if (!function_exists('calculate_age')) {
    function calculate_age($birthDate)
    {
        $currentDate = new DateTime();
        $birthDate = new DateTime($birthDate);
        $age = $currentDate->diff($birthDate);
        return $age->y;
    }
}


if (!function_exists('get_string_translate')) {
    function get_string_translate(string $key): string
    {
        $value = __("messages.translate.{$key}");
        if ($value == "messages.translate.{$key}") return $key;
        return $value;
    }
}

if (!function_exists('generate_random_string')) {
    function generate_random_string(int $length = 6): string
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }
}


if (!function_exists('get_tags')) {
    function get_tags(int $length = 3): array
    {
        $array = ['Reading', 'Traveling', 'Photography', 'Music', 'Painting', 'Yoga', 'Cooking', 'Calligraphy', 'Crafts',
            'History', 'Drinking', 'Coding', 'Valuing family', 'Skydiving', 'Diving'];
        $length = $length < 1 ? 1 : ($length > count($array) ? count($array) : $length);
        $random_keys = array_rand($array, $length);
        $random_elements = [];
        foreach ($random_keys as $key) {
            $random_elements[] = $array[$key];
        }
        return $random_elements;
    }
}

/**
 * 辅助函数：十进制转十六进制（支持大数）
 */
function bcdechex($dec)
{
    $hex = '';
    while (bccomp($dec, 0) > 0) {
        $last = bcmod($dec, 16);
        $hex = dechex($last) . $hex;
        $dec = bcdiv($dec, 16, 0);
    }
    return $hex ?: '0';
}

if (!function_exists('is_multiple_of_eight')) {
    function is_multiple_of_eight(int $number): bool
    {
        if ($number % 8 == 0) {
            return true;  // 是 8 的倍数
        } else {
            return false; // 不是 8 的倍数
        }
    }
}

if (!function_exists('get_invitation_code')) {
    function get_invitation_code(): string
    {
        do {
            $invitation_code = generate_random_string();
        } while (\App\Models\User::where('invitation_code', $invitation_code)->first() != null);
        return $invitation_code;
    }
}

if (!function_exists('generate_order_number')) {

    function generate_order_number()
    {
        $dateTime = date('YmdHis');
        $randomNumber = mt_rand(1000, 9999);
        $orderNumber = $dateTime . $randomNumber;
        return $orderNumber;
    }
}


function removeZero($str)
{
    if (empty($str)) {
        return 0;
    }
    if (!is_numeric($str)) {
        return $str;
    }

    $number = number_format($str, 10, '.', '');

    // 使用 rtrim 移除末尾的零和小数点
    return rtrim(rtrim($number, '0'), '.');
}

/**
 * 唯一订单号
 * @return string
 */
function createOrderNo(): string
{
    $str = microtime(true);
    $arr = explode('.', $str);
    $decimal = $arr[1];

    return date('YmdHis') . $decimal;
}

/**
 * 获取精度
 * @param $number
 * @return int
 */
function getScale($number): int
{
    if (!is_numeric($number)) {
        return 1;
    }

    $sub = strrchr($number, ".");
    if (empty($sub)) {
        return 1;
    }

    $scale = strlen(substr($sub, 1));
    if ($scale == 0) {
        return 1;
    }

    return $scale;
}



