<?php

use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Str;

if (! function_exists('user_admin_config')) {
    function user_admin_config($key = null, $value = null)
    {
        // 获取 session 实例
        $session = session();

        // 从 session 中获取 'admin.config',如果没有则使用默认的 'admin' 配置
        $config = $session->get('admin.config', function () {
            $adminConfig = config('admin');
            $adminConfig['lang'] = config('app.locale');
            return $adminConfig;
        });

        // 如果 $key 是数组,表示我们需要批量设置配置项
        if (is_array($key)) {
            foreach ($key as $k => $v) {
                Arr::set($config, $k, $v); // 在配置数组中设置每个键值对
            }
            $session->put('admin.config', $config); // 将更新后的配置保存到 session 中
            return;
        }

        // 如果没有传递具体的 key,返回整个配置数组
        if (is_null($key)) {
            return $config;
        }

        // 获取指定的配置项,如果不存在则返回默认值 $value
        return Arr::get($config, $key, $value);
    }
}

if (! function_exists('switchLanguage')) {
    function switchLanguage($lang)
    {

        // 验证是否是支持的语言
        if (!in_array($lang, ['en', 'zh_CN', 'zh_TW'])) {
            return false;
        }


        Cookie::queue('lang', $lang, 60 * 24 * 30); // 保存 30 天

        // 动态修改 app.locale 配置
        config(['app.locale' => $lang]);

        return true;
    }
}


if (!function_exists('getDistributor')) {
    /**
     * 获取会话中的 distributor 值
     *
     * @return mixed
     */
    function getDistributor() {
        return  Session::get('distributor');
    }
}

if (!function_exists('getDistributorDomain')) {
    function getDistributorDomain()
    {
        $domain = '';
        $row = getDistributor();
        if ($row) {
            if ($row['domain_type'] == 0) {
                $domain = 'https://'.$row['secondary_domain'];
            } else {
                $domain = 'https://'.$row['custom_domain'];
            }
        }
//        if (env('DIST_SITE_PORT') != 80) {
//            $domain .= ':' . env('DIST_SITE_PORT');
//        }
        return $domain;

    }
}

if (!function_exists('getDistributorId')) {
    /**
     * 获取会话中的 distributor 的 ID
     *
     * @return mixed
     */
    function getDistributorId() {
        $distributor = Session::get('distributor');
        return $distributor ? $distributor['id'] : null; // 假设 distributor 是一个数组,包含 id
    }
}

/*
 * 使用session记录与显示临时变量,变量名在config/dictionary.php中的temp_value
 */

if (!function_exists('setTempValue')) {
    function setTempValue($key, $value) {
        $arr = config('dictionary.temp_value');
        if (isset($arr[$key])) {
            $newKey = '_temp_value_'.$key;//加前缀
            Session::put($newKey, $value);
            return true;
        }
        return false;
    }
}
/*
 * 拿临时变量
 */
if (!function_exists('getTempValue')) {
    function getTempValue($key) {
        $arr = config('dictionary.temp_value');
        if (isset($arr[$key])) {
            $newKey = '_temp_value_'.$key; //加前缀
            $value = Session::get($newKey);
            return $value === null ? $arr[$key] : $value;
        }
        return false;
    }
}


if (!function_exists('getSiteDomain')) {
    //得到分销商域名
    function getSiteDomain($hasHttp = true) {
        $distributor = Session::get('distributor');
        $domain = $distributor['domain_type'] == 0 ?  $distributor['secondary_domain'] : $domain = $distributor['custom_domain'];
        if ($hasHttp) {
            $domain = 'https://'.$domain;
        }
        return $domain;
    }
}



//通过parent_id构建树形结构
if (!function_exists('buildTree')) {
    function buildTree(array $elements, $parentId = 0)
    {
        $branch = [];

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = buildTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }
}

// 展平树形结构
if (!function_exists('flattenTree')) {
    function flattenTree(array $tree, array &$result = [], $level = 0)
    {
        foreach ($tree as $node) {
            // 复制节点数据,但不包括子节点,并添加 level 字段
            $flattenedNode = array_diff_key($node, ['children' => null]);
            $flattenedNode['level'] = $level;
            $result[] = $flattenedNode;

            // 如果有子节点,递归处理子节点,并将 level 增加 1
            if (isset($node['children']) && is_array($node['children'])) {
                flattenTree($node['children'], $result, $level + 1);
            }
        }

        return $result;
    }
}

if (!function_exists('uniqueCode')) {

    function uniqueCode($prefix = '')
    {
        //$uniqueId = strtolower(Str::random($length));
        $uniqueId = uniqid($prefix);
        return $uniqueId;
    }
}

if (!function_exists('generateVersionNumber')) {
    /*
     * 12位版本号
     */
    function generateVersionNumber()
    {
        // 获取当前的年、月、日
        $year = date('y'); // 年份的最后两位
        $month = date('m'); // 月份,两位数字
        $day = date('d'); // 日期,两位数字
        // 获取当前的毫秒级时间戳
        $microtime = microtime(true);
        $milliseconds = round(($microtime - floor($microtime)) * 1000);
        // 将毫秒级时间戳转换为 6 位数字
        $milliseconds = str_pad($milliseconds, 3, '0', STR_PAD_LEFT);
        // 获取当前的时间戳(秒级)
        $timestamp = time();
        // 将时间戳转换为 6 位数字(如果需要更精确的时间戳,可以使用毫秒级时间戳)
        $timestamp = str_pad($timestamp % 1000000, 6, '0', STR_PAD_LEFT);
        // 组合成 12 位版本号
        $versionNumber = $year . $month . $day. $timestamp. $milliseconds ;
        return $versionNumber;
    }
}

//判断是否为json
if (!function_exists('isValidJson')) {
    function isValidJson($string) {
        json_decode($string);
        return (json_last_error() === JSON_ERROR_NONE);
    }

}

//判断是否为纯域名
if (!function_exists('isDomainOnly')) {
    function isDomainOnly($string) {
        // 正则表达式:匹配不带协议或路径的纯域名
        $pattern = '/^(?!:\/\/)([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$/';

        return preg_match($pattern, $string) === 1;
    }
}

//生成slug
if (!function_exists('generateSlug')) {
    function generateSlug($title)
    {
        // 1. 将所有字符转换为小写
        $slug = strtolower($title);
        // 2. 将空格替换为短横线(-)
        $slug = str_replace(' ', '-', $slug);
        // 3. 将不合法的字符(!@#$%^&*?=+)替换为空
        $slug = preg_replace('/[::^!@#$%^&*()?=+]+/u', '', $slug);
        // 4. 清理多余的短横线
        $slug = preg_replace('/-+/', '-', $slug);
        // 5. 去除开头和结尾的短横线
        $slug = trim($slug, '-');
        return $slug;
    }
}

//生成随机小写英文组成的字符串
if (!function_exists('generateRandomString')) {
    function generateRandomString($length = 3) {
        $characters = 'abcdefghijklmnopqrstuvwxyz';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
}

//翻译数组
if (!function_exists('admin_trans_array')) {
    function admin_trans_array($array) {
        array_walk($array, function(&$value, $key) {
            $value = admin_trans_label($value);
        });
        return $array;
    }
}


//curl get
if (!function_exists('curlGet')) {
    function curlGet($url,$timeout=10) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        if ($response === false) {
            return array(
                'error' => curl_error($ch),
                'http_code' => null
            );
        } else {
            $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            return array(
                'response' => $response,
                'http_code' => $http_code
            );
        }
        curl_close($ch);
    }

}

/*
 * 截取字符函数
 * $string 要截取的字符串
 * $length 截取长度
 * $append 后缀
 */
if (!function_exists('truncateString')) {
    function truncateString($string, $length = 30, $append = '') {
        // 检查字符串长度是否超过指定长度
        if (mb_strlen($string, 'UTF-8') > $length) {
            // 截取字符串
            $truncated = mb_substr($string, 0, $length, 'UTF-8');
            // 添加省略号
            return $truncated . $append;
        }
        // 如果字符串长度小于或等于指定长度,直接返回原字符串
        return $string;
    }
}


/*
 * 带http的url转化为storage_path路径
 */
if (!function_exists('toStoragePath')) {
    function toStoragePath($httpUrl) {
        $parsed = parse_url($httpUrl);
        $path =  ltrim($parsed['path'], '/');
        return storage_path('app/'.$path);
    }
}



/*
 * 将UTC时间转换为当前浏览器时区时间
 * 空,返回当前浏览器时间
 */
if (!function_exists('utcToLocalTime')) {
    function utcToLocalTime($utcTime = '') {
        $timeZoneName = Session::get('timeZoneName') ?? 'UTC';

        if (empty($utcTime)) {
            return Carbon::now($timeZoneName)->format('Y-m-d H:i:s');
        }


        // 创建 UTC 时区对象
        $utcTimezone = new DateTimeZone('UTC');

        // 解析输入时间(支持字符串和时间戳)
        if (is_numeric($utcTime)) {
            $date = DateTime::createFromFormat('U', $utcTime, $utcTimezone);
        } else {
            $date = DateTime::createFromFormat('Y-m-d H:i:s', $utcTime, $utcTimezone);
        }

        // 转换到时区
        $distTimezone = new DateTimeZone($timeZoneName);
        $date->setTimezone($distTimezone);

        return $date->format('Y-m-d H:i:s');
    }
}

/*
 * 将当前浏览器时区时间转换为UTC时间
 * 空返回当前的UTC时间
 */
if (!function_exists('localTimeToUtc')) {
    function localTimeToUtc($inputTime = '') {

        if (empty($inputTime)) {
            return Carbon::now('UTC')->format('Y-m-d H:i:s');
        }

        $timeZoneName = Session::get('timeZoneName') ?? 'UTC';

        // 创建分销商时区对象
        $distTimezone = new DateTimeZone($timeZoneName);

        // 解析输入时间(支持字符串和时间戳)
        if (is_numeric($inputTime)) {
            $date = DateTime::createFromFormat('U', $inputTime, $distTimezone);
        } else {
            $date = DateTime::createFromFormat('Y-m-d H:i:s', $inputTime, $distTimezone);
        }

        // 转换到 UTC 时区
        $date->setTimezone(new DateTimeZone('UTC'));

        return $date->format('Y-m-d H:i:s');
    }
}