<?php

/**
 * Here is your custom functions.
 */

use app\common\service\FileService;


if (!function_exists('substr_symbol_behind')) {
    /**
     * @notes 截取某字符字符串
     * @param $str
     * @param string $symbol
     * @return string
     * @author 乔峰
     * @date 2021/12/28 18:24
     */
    function substr_symbol_behind($str, $symbol = '.'): string
    {
        $result = strripos($str, $symbol);
        if ($result === false) {
            return $str;
        }
        return substr($str, $result + 1);
    }
}


/**
 * @notes 对比php版本
 * @param string $version
 * @return bool
 * @author 乔峰
 * @date 2021/12/28 18:27
 */
function compare_php(string $version): bool
{
    return version_compare(PHP_VERSION, $version) >= 0 ? true : false;
}

/**
 * @notes 检查文件是否可写
 * @param string $dir
 * @return bool
 * @author 乔峰
 * @date 2021/12/28 18:27
 */
function check_dir_write(string $dir = ''): bool
{
    $route = base_path() . '/' . $dir;
    return is_writable($route);
}

/**
 * @notes 随机生成token值
 * @param string $extra
 * @return string
 * @author 乔峰
 * @date 2021/12/28 18:24
 */
function create_token(string $extra = ''): string
{
    return md5($extra . time());
}

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

/**
 * 多级线性结构排序
 * 转换前:
 * [{"id":1,"pid":0,"name":"a"},{"id":2,"pid":0,"name":"b"},{"id":3,"pid":1,"name":"c"},
 * {"id":4,"pid":2,"name":"d"},{"id":5,"pid":4,"name":"e"},{"id":6,"pid":5,"name":"f"},
 * {"id":7,"pid":3,"name":"g"}]
 * 转换后:
 * [{"id":1,"pid":0,"name":"a","level":1},{"id":3,"pid":1,"name":"c","level":2},{"id":7,"pid":3,"name":"g","level":3},
 * {"id":2,"pid":0,"name":"b","level":1},{"id":4,"pid":2,"name":"d","level":2},{"id":5,"pid":4,"name":"e","level":3},
 * {"id":6,"pid":5,"name":"f","level":4}]
 * @param array $data 线性结构数组
 * @param string $symbol 名称前面加符号
 * @param string $name 名称
 * @param string $id_name 数组id名
 * @param string $parent_id_name 数组祖先id名
 * @param int $level 此值请勿给参数
 * @param int $parent_id 此值请勿给参数
 * @return array
 */
function linear_to_tree($data, $sub_key_name = 'sub', $id_name = 'id', $parent_id_name = 'pid', $parent_id = 0)
{
    $tree = [];
    foreach ($data as $row) {
        if ($row[$parent_id_name] == $parent_id) {
            $temp = $row;
            $child = linear_to_tree($data, $sub_key_name, $id_name, $parent_id_name, $row[$id_name]);
            if ($child) {
                $temp[$sub_key_name] = $child;
            }
            $tree[] = $temp;
        }
    }
    return $tree;
}

function createDir($path)
{
    if (is_dir($path)) {
        return true;
    }

    $parent = dirname($path);
    if (!is_dir($parent)) {
        if (!createDir($parent)) {
            return false;
        }
    }
    return mkdir($path);
}

/**
 * @notes 删除目标目录
 * @param $path
 * @param $delDir
 * @return bool|void
 * @author 段誉
 * @date 2022/4/8 16:30
 */
function del_target_dir($path, $delDir)
{
    //没找到,不处理
    if (!file_exists($path)) {
        return false;
    }

    //打开目录句柄
    $handle = opendir($path);
    if ($handle) {
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..") {
                if (is_dir("$path/$item")) {
                    del_target_dir("$path/$item", $delDir);
                } else {
                    unlink("$path/$item");
                }
            }
        }
        closedir($handle);
        if ($delDir) {
            return rmdir($path);
        }
    } else {
        if (file_exists($path)) {
            return unlink($path);
        }
        return false;
    }
}

/**
 * @notes 获取无前缀数据表名
 * @param $tableName
 * @return mixed|string
 * @author 段誉
 * @date 2022/12/12 15:23
 */
function get_no_prefix_table_name($tableName)
{
    $tablePrefix = config('database.connections.mysql.prefix');
    $prefixIndex = strpos($tableName, $tablePrefix);
    if ($prefixIndex !== 0 || $prefixIndex === false) {
        return $tableName;
    }
    $tableName = substr_replace($tableName, '', 0, strlen($tablePrefix));
    return trim($tableName);
}

/**
 * @notes 去除内容图片域名
 * @param $content
 * @return array|string|string[]
 * @author 段誉
 * @date 2022/9/26 10:43
 */
function clear_file_domain($content)
{
    $fileUrl = FileService::getFileUrl();
    return str_replace($fileUrl, '/', $content);
}

/**
 * @notes 设置内容图片域名
 * @param $content
 * @return array|string|string[]|null
 * @author 段誉
 * @date 2022/9/26 10:43
 */
function get_file_domain($content)
{
    $preg = '/(<img .*?src=")[^https|^http](.*?)(".*?>)/is';
    $fileUrl = FileService::getFileUrl();
    return preg_replace($preg, "\${1}$fileUrl\${2}\${3}", $content);
}

/**
 * @notes 下载文件
 * @param $url
 * @param $saveDir
 * @param $fileName
 * @return string
 * @author 段誉
 * @date 2022/9/16 9:53
 */
function download_file($url, $saveDir, $fileName)
{
    if (!file_exists($saveDir)) {
        mkdir($saveDir, 0775, true);
    }
    $fileSrc = $saveDir . $fileName;
    file_exists($fileSrc) && unlink($fileSrc);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($fileSrc, 'a');
    fwrite($resource, $file);
    fclose($resource);
    if (filesize($fileSrc) == 0) {
        unlink($fileSrc);
        return '';
    }
    return $fileSrc;
}

if (!function_exists('getDistance')) {

    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
        return round($s, 1);
    }
}
/**
 * 写日志
 */
if (!function_exists('write_log')) {
    function write_log($msg, $extend = [], $level = 'error', $channel = 'api')
    {
        $requestParams = [];
        $line = "\n---------------------------------------------------------------\n";
        if (empty(request())) {
            $logInfo = $line;
        } else {
            $method = request()->method();
            $requestInfo = [
                'ip' => request()->getRealIp(),
                'method' => $method,
                'uri' => ltrim(request()->fullUrl(), '/')
            ];
            $logInfo = implode(' ', $requestInfo) . $line;
            $method = strtolower($method);
            $requestParams = in_array($method, ['get', 'post']) ? request()->{$method}() : request()->all();
        }
        $logInfo .= var_export([
            'msg' => $msg,
            'extend' => $extend,
            'params' => $requestParams
        ], true);
        \support\Log::channel($channel)->addRecord(LOG_LEVEL_STATUS[$level], $logInfo);
    }
}

// LOG_LEVEL_STATUS如下:
const LOG_LEVEL_STATUS = [
    'debug' => 100,
    'info'  => 200,
    'warning' => 300,
    'error' => 400,
    'critical' => 500,
    'alert' => 550,
    'emergency' => 600
];
if (!function_exists('base64UrlDecode')) {

    /**
     * @desc base64_encode 解码
     * @param string $data
     * @return string
     * @author Tinywan(ShaoBo Wan)
     */
    function base64UrlDecode(string $data): string
    {
        $base64 = strtr($data, '-_', '+/');
        $base64Padded = str_pad($base64, strlen($base64) % 4, '=', STR_PAD_RIGHT);
        return base64_decode($base64Padded);
    }
}
if (!function_exists('getNewOrderId')) {

    /**
     * @notes 获取订单号
     * @param $type
     * @return string
     */
    function getNewOrderId($type)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = $type . $msectime . mt_rand(100, max(intval($msec * 10) + 100, 983));
        return $orderId;
    }
}

if (!function_exists('setUnique')) {

    /**
     * @notes 唯一值
     * @param $type
     * @return string
     */
    function setUnique(int $id, $sku, int $type)
    {
        return substr(md5($sku . $id), 12, 11) . $type;
    }
}


if (!function_exists('generateUniqueVerificationCode')) {
    function generateUniqueVerificationCode()
    {
        // 获取当前时间的毫秒部分
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');

        // 生成一个随机数作为核销码的后缀
        $randomNumber = mt_rand(100, 999); // 假设核销码是8位数

        // 将前缀、毫秒时间戳和随机数连接起来
        $type = rand(1, 10); // 生成一个1-10之间的随机数作为前缀
        return $type . '-' . $msectime . $randomNumber;
    }
}


if (!function_exists('verificationCode')) {
    function verificationCode()
    {
        $sec = time();
        // 将前缀、秒时间戳和随机数连接起来
        $type = rand(1, 10); // 生成一个1-10之间的随机数作为前缀
        $code =  $type . '-' . $sec;
        $check = \app\common\model\store_order\StoreOrder::where('verify_code', $code)->count();
        if ($check) {
            verificationCode();
        }
        return $code;
    }
}

if (!function_exists('createCode')) {
    function createCode($code)
    {
        $check = \app\common\model\store_order\StoreOrder::where('verify_code', $code)->count();
        if ($check) {
            $orderPickupCode = rand(1, 10) . '-' . str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
            return   createCode($orderPickupCode);
        }
        return $code;
    }
}

if (!function_exists('haversineDistance')) {
    function haversineDistance($latitude1, $longitude1, $latitude2, $longitude2)
    {
        $earthRadius = 6371; // 地球平均半径,单位是千米

        // 将角度转换为弧度
        $latFrom = deg2rad($latitude1);
        $lonFrom = deg2rad($longitude1);
        $latTo = deg2rad($latitude2);
        $lonTo = deg2rad($longitude2);

        $latDelta = $latTo - $latFrom;
        $lonDelta = $lonTo - $lonFrom;

        $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
            cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
        return $angle * $earthRadius;
    }
}

/**
 * 随机验证码
 */
if (!function_exists('generateRandomCode')) {
    function generateRandomCode($length = 4)
    {
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= random_int(0, 9);
        }
        return $code;
    }
}


if (!function_exists('reset_index')) {
    /**
     * 重置数组索引
     * @param array $data
     * @param string $index
     * @return array
     */
    function reset_index(array $data, string $index)
    {
        $return = [];
        foreach ($data as $item) {
            $return[$item[$index]] = $item;
        }
        return $return;
    }
}

if (!function_exists('append_to_array')) {
    /**
     * 追加元素到数组
     * @param array $data
     * @param array $append
     * @return array
     */
    function append_to_array(array $data, array $append)
    {
        $return = [];
        foreach ($data as $item) {
            if (isset($append['relation'])) {
                $item[$append['value']] = $append['relation'][$item[$append['field']]];
            } else {
                $item[$append['value']] = $item[$append['field']];
            }
            $return[] = $item;
        }
        return $return;
    }
}

if (!function_exists('countRate')) {
    /**
     * 计算环比增长率
     * @param $nowValue
     * @param $lastValue
     * @return float|int|string
     */
    function countRate($nowValue, $lastValue)
    {
        if ($lastValue == 0 && $nowValue == 0) return 0;
        if ($lastValue == 0) return round(bcmul(bcdiv($nowValue, 1, 4), 100, 2), 2);
        if ($nowValue == 0) return -round(bcmul(bcdiv($lastValue, 1, 4), 100, 2), 2);
        return bcmul(bcdiv((bcsub($nowValue, $lastValue, 2)), $lastValue, 4), 100, 2);
    }
}


if (!function_exists('payPassword')) {
    //支付密码
    function payPassword($password){
        return password_hash($password,PASSWORD_BCRYPT);
    }
}