<?php
// 应用公共文件

// 接口错误返回
if (!function_exists('error')) {
    function error($msg = '', $data = [], $status_code = 200): \think\response\Json
    {
        return \apiret\Api::error($msg, $data, $status_code);
    }
}


// 接口成功返回
if (!function_exists('success')) {
    function success($msg = '', $data = [], $status_code = 200): \think\response\Json
    {
        return \apiret\Api::success($msg, $data, $status_code);
    }
}

// 接口调结果返回
if (!function_exists('result')) {
    function result($errno, $msg = '', $data = [], $status_code = 200): \think\response\Json
    {
        return \apiret\Api::result($errno)->message($msg)->response($data, $status_code);
    }
}

// 密码加盐
if (!function_exists('password_with_salt')) {
    function password_with_salt($password, $salt)
    {
        return md5(hash('sha256', $password . $salt));
    }
}

// 生成随机字符串
if (!function_exists('random_str')) {
    /**
     * 生成随机字符串
     * @param $length integer 生成的长度
     * @param $type string 要生成的字符串类型(number, string, all)
     * @param $convert integer 大小写转换0为小写1为大写
     * @return string
     */
    function random_str($length, $type = "string", $convert = "0")
    {
        $conf = [
            'number' => '0123456789',
            'string' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789='
        ];
        $string = $conf[$type];
        if (!$string) {
            $string = $conf['string'];
        }
        $strlen = strlen($string) - 1;
        $char = '';
        for ($i = 0; $i < $length; $i++) {
            $char .= $string[mt_rand(0, $strlen)];
        }
        if ($convert > 0) {
            $res = strtoupper($char);
        } elseif ($convert == 0) {
            $res = $char;
        } elseif ($convert < 0) {
            $res = strtolower($char);
        }
        return $res;
    }
}

if (!function_exists('array_to_tree')) {
    /**
     * 数组转换为树状结构
     * @param array $data 数据
     * @param int $pid 父级ID
     * @param string $with 转换依据字段
     * @param int|bool $level 层级
     * @param bool $keep_pid 是否保留pid
     * @return array
     */
    function array_to_tree(array $data, int $pid, string $with = 'pid', int|bool $level = 1, bool $keep_pid = true, $with_ref = 'id')
    {
        $ret = [];
        foreach ($data as $item) {
            if ($item[$with] == $pid) {
                $lv = $level;
                if ($level !== false) {
                    $item['level'] = $level;
                    $lv            = $level + 1;
                }
                if ($keep_pid === false) {
                    unset($item[$with]);
                }
                $children = array_to_tree($data, $item[$with_ref], $with, $lv, $keep_pid, $with_ref);
                if ($children) {
                    $item['children'] = $children;
                }
                $ret[] = $item;
            }
        }
        return $ret;
    }
}

if (!function_exists('array_flatten')) {
    /**
     * 将多维数组转换为一维数组
     * @param array $array
     * @return array
     */
    function array_flatten(array $array, int $depth = 1): array
    {
        return \think\helper\Arr::flatten($array, $depth);
    }
}

if (!function_exists('thumb')) {
    /**
     * 获取缩略图
     * @param string $url 图片地址
     * @return string
     */
    function thumb(?string $url): string
    {
        if (empty($url)) {
            return '';
        }
        if (
            str_contains($url, '_thumb') || 
            \think\helper\Str::startsWith($url, ['http://', 'https://']) ||
            !\think\helper\Str::endsWith($url, ['.png', '.jpg', '.jpeg', '.gif', '.tif', '.svg', '.webp', '.bmp'])
        ) {
            return $url;
        }

        $idx = mb_strripos($url, '.', 0, 'utf-8');
        if ($idx === false) {
            return $url;
        }

        $len = mb_strlen($url, 'utf-8');

        return mb_substr($url, 0, $idx, 'utf-8') . '_thumb' . mb_substr($url, $idx, $len - $idx, 'utf-8');
    }
}

if (!function_exists('get_filesystem_url')) {
    /**
     * 获取文件系统的访问 URL
     * @param string $url 文件地址
     * @param string $disk 磁盘配置 key
     * @return string
     */
    function get_filesystem_url(string|null $url, string $disk): string
    {
        if (is_null($url)) {
            return '';
        }

        if (\think\helper\Str::startsWith($url, ['http://', 'https://', '//'])) {
            return $url;
        }
        if (empty($disk)) {
            return '';
        }
        return \think\facade\Filesystem::disk($disk)->url($url);
    }
}

if (!function_exists('url_filesystem_detect')) {
    /**
     * 检测文件地址并根据情况转换为文件系统地址
     * @param string $url 文件地址
     * @return string
     */
    function url_filesystem_detect(string|null $url): string
    {
        if  (is_null($url)) {
            return '';
        }

        $idx = strrpos($url, '.');
        if ($idx === false) {
            return $url;
        }

        $disks = [
            'public_qiniu' => '_' . base64_encode('public_qiniu'),
            'video_qiniu'  => '_' . base64_encode('video_qiniu')
        ];
        foreach ($disks as $disk => $marker) {
            if (str_ends_with(mb_substr($url, 0, $idx), $marker)) {
                return get_filesystem_url($url, $disk);
            }
        }

        return $url;
    }
}

if (!function_exists('url_join')) {
    /**
     * 合并URL
     * @param string $url 基础URL
     * @param string $path 路径
     * @param bool $remove_slash 是否移除首尾的斜杠
     * @return string
     */
    function url_join(string $url, string $path, bool $remove_slash = true): string
    {
        if (empty($url)) {
            return $path;
        }
        if (empty($path)) {
            return $url;
        }
        if (\think\helper\Str::startsWith($path, ['http://', 'https://', '//'])) {
            return $path;
        }
        
        if ($remove_slash) {
            if (str_ends_with($url, '/') && str_starts_with($path, '/')) {
                return $url . substr($path, 1);
            }
            if (!str_ends_with($url, '/') && !str_starts_with($path, '/')) {
                return $url . '/' . $path;
            }
        }

        return $url . $path;
    }
}