<?php

use think\facade\Db;
use think\facade\Config;
use think\facade\Env;
use Symfony\Component\VarExporter\VarExporter;

/**
 * 打印格式化数据
 * @param $str
 */
function p($str)
{
    if (is_bool($str)) {
        dump($str);
    } else if (is_null($str)) {
        dump($str);
    } else if ($str == '') {
        dump($str);
    } else {
        echo '<pre>' . print_r($str, true) . '</pre>';
    }
}

/**
 * 截取html
 * @param $string
 * @param int $l
 * @param int $r
 * @param string $bm
 * @return string|string[]
 */
function cutstr_html($string, $l = 0, $r = 0, $bm = 'utf-8')
{
    $string = mb_substr(trim(strip_tags($string)), $l, $r, $bm);
    return str_replace(['&nbsp;', PHP_EOL], '', trim($string));
}

/**
 * @param $l   左边的变量
 * @param $r   右边的变量
 * @param $str 样式
 */
function Cur($l, $r, $str)
{
    if ($l == $r) {
        return $str;
    }
}

/**
 * 字段默认值
 * @param $str
 * @param string $end
 * @return string
 */
function __empty($str, $end = '-')
{
    if (empty($str)) {
        return $end;
    } else {
        return $str;
    }
}

/**
 * 过滤函数
 * @param $val
 * @return mixed
 */
function imDataFilter($val)
{
    return $val;
}

/**
 * @param $table 数据表名称
 * @param $where 条件
 * @param $limit 数量
 */
function getDataLists($table, $where = '', $limit = '')
{
    $DB = Db::name($table)->where($where);
    if ($limit) {
        $DB = $DB->limit($limit);
    }
    return $DB->select();
}

/**
 * 加 checked 属性
 * @param $l 左侧数据
 * @param $r 右侧数据
 * @return string
 */
function checked($l, $r)
{
    if ($l == $r) {
        return ' checked';
    }
}

/**
 * 加 hide隐藏
 * @param $l 左侧数据
 * @param $r 右侧数据
 * @return string
 */
function hide($l, $r)
{
    if ($l == $r) {
        return 'hide';
    }
}

/**
 * 加 selected 属性
 * @param $l 左侧数据
 * @param $r 右侧数据
 * @return string
 */
function selected($l, $r)
{
    if ($l == $r) {
        return ' selected';
    }
}

/**
 * 随机生成英文数字组合字符串
 * @param int $len 长度
 * @return string
 */
function random_user($len = 8)
{
    $user = '';
    $lchar = 0;
    $char = 0;
    for ($i = 0; $i < $len; $i++) {
        while ($char == $lchar) {
            $char = rand(48, 109);
            if ($char > 57) $char += 7;
            if ($char > 90) $char += 6;
        }
        $user .= chr($char);
        $lchar = $char;
    }
    return $user;
}

function get_avatar_id($id)
{
    $fiy = intval(floor($id % 200));
    if ($fiy == 0) {
        return 200;
    } else {
        return $fiy;
    }
}

/**
 * 重写url方法
 */
function Furl($url, $pam = [], $suffix = true, $domain = false)
{
    return \think\facade\Route::buildUrl($url, $pam)
        ->suffix($suffix)->domain($domain)->build();
}

/**
 * 客服生成专属链接
 */
function exclusiveUrl($data)
{
    $url = chatUrl('chat/say/redchat', $data, true);
    return urldecode($url);
}

/**
 * 公钥加密
 * @param string 明文
 * @return string 密文（base64编码）
 */
function encodeing($sourcestr)
{
    $key_content = Config::get('encrypt.public_key');
    $pubkeyid = openssl_get_publickey($key_content);
    if (openssl_public_encrypt($sourcestr, $crypttext, $pubkeyid)) {
        return base64_encode("" . $crypttext);
    }
}

/**
 * 私钥解密
 * @param string 密文（二进制格式且base64编码）
 * @param string 密文是否来源于JS的RSA加密
 * @return string 明文
 */
function decodeing($crypttext)
{
    $key_content = Config::get('encrypt.private_key');
    $prikeyid = openssl_get_privatekey($key_content);
    $crypttext = base64_decode($crypttext);
    if (openssl_private_decrypt($crypttext, $sourcestr, $prikeyid, OPENSSL_PKCS1_PADDING)) {
        return "" . $sourcestr;
    }
    return;
}

/**
 * 自动判断把gbk或gb2312编码的字符串转为utf8
 * 能自动判断输入字符串的编码类，如果本身是utf-8就不用转换，否则就转换为utf-8的字符串
 * 支持的字符编码类型是：utf-8,gbk,gb2312
 * @$str:string 字符串
 */
function gbk2utf8($str)
{
    $charset = mb_detect_encoding($str, ['UTF-8', 'GBK', 'GB2312']);
    $charset = strtolower($charset);
    if ('cp936' == $charset) {
        $charset = 'GBK';
    }
    if ("utf-8" != $charset) {
        $str = iconv($charset, "UTF-8//IGNORE", $str);
    }
    return $str;
}

/**
 * curl get请求
 * @param $url
 */
function curl_get($target_url, $get_data = array())
{
    $curl = curl_init();
    $headers = [
        "User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36",
        "Host: www.ip138.com",
    ];
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_URL, $target_url . '?' . http_build_query($get_data));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

/**
 * curl post请求
 * @param $url
 */
function curl_post($url, $data = [], $header = [])
{
    // 模拟提交数据函数
    // 初始化curl
    $curl = curl_init();
    // 绑定url
    curl_setopt($curl, CURLOPT_URL, $url);
    // 绑定头部信息
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
    // 为1时返回结果中将带有响应头信息
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 验证服务器证书有效性，0为跳过，2为开启
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    // 检验证书中的主机名和你访问的主机名是否一致，1为开启
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    // 判断请求类型是否为post
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    }
    // 为0时直接输出返回结果
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 发送请求
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

/**
 * 通过typeid获取配置
 * @param $type_id
 * @param $main_id
 */
function get_typeid_options($type_id, $main_id)
{
    $type = Db::name('im_options_type')->find($type_id);
    $options = Db::name('im_options')
        ->where([
            'type_id' => $type['type_id'],
            'cuid' => 1
        ])->select();

    return [
        'type' => $type,
        'lists' => $options->toArray()
    ];
}

/**
 * 显示配置表单
 * option_type 1=text, 2=textarea, 3=select, 4=open, 5=checkbox, 6=file, 7=password, 8=radio, 9=tags
 */
function options_generate($options)
{
    if (!empty($options) && is_array($options)) {
        $options_temp = "";
        foreach ($options as $key => $item) {
            $options_temp .= '<div class="form-group row">';
            $options_temp .= '<div class="col-xs-3">' . $item['option_cname'] . '</div>';
            $options_temp .= '<div class="col-xs-6">';
            if ($item['option_type'] == 1) {
                $options_temp .= '<input class="form-control options-text" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 2) {
                $options_temp .= '<textarea class="form-control options-textarea" rows="6" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 3) {
                $options_temp .= '<input class="form-control options-text" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 4) {
                $options_temp .= '<label class="lyear-switch switch-success">';
                $options_temp .= '<input type="checkbox" class="options-open"' . checked($item['option_value'], 1) . ' data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '">';
                $options_temp .= '<span></span></label>';
            } elseif ($item['option_type'] == 5) {
                $options_temp .= '<input class="form-control options-text" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 6) {
                $options_temp .= '<input class="form-control options-text" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 7) {
                $options_temp .= '<input class="form-control options-text" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            } elseif ($item['option_type'] == 8) {
                $option_value = array_filter(explode('|', $item['option_default']));
                if (!empty($option_value)) {
                    foreach ($option_value as $key2 => $item2) {
                        $value2 = array_filter(explode(',', $item2));
                        $checked = "";
                        if ($value2[1] == $item['option_value']) {
                            $checked = " checked";
                        }
                        $options_temp .= '<label class="lyear-radio radio-inline radio-primary">';
                        $options_temp .= '<input' . $checked . ' type="radio" class="options-radio" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '_' . $key2 . '" name="' . $item['option_ename'] . '" value="' . ($key2 + 1) . '">';
                        $options_temp .= '<span>' . $value2[0] . '</span></label>';
                    }
                }
            } elseif ($item['option_type'] == 9) {
                $options_temp .= '<input class="form-control options-tags" type="text" data-id="' . $item['option_id'] . '" id="' . $item['option_ename'] . '" name="' . $item['option_ename'] . '" value="' . $item['option_value'] . '">';
            }
            $options_temp .= '</div></div>';
        }
        return $options_temp;
    }
}


/**
 * zip解压方法
 * @param string $filePath 压缩包所在地址
 * @param string $path 解压路径
 * @return bool
 */
function unzip($filePath, $path)
{
    if (empty($path) || empty($filePath)) {
        return false;
    }

    $zip = new ZipArchive();

    if ($zip->open($filePath) === true) {
        $zip->extractTo($path);
        $zip->close();
        return true;
    } else {
        return false;
    }
}

/**
 * 判断php数组是否索引数组
 * @param $array
 * @return bool
 */
function is_assoc($array)
{
    $keys = array_keys($array);
    return $keys != array_keys($keys);
}

if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {
    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

/**
 * 获取来源
 */
function get_source()
{
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'miniprogram') !== false) {
            return '微信小程序';
        } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return '微信';
        }
    }
    return isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
}

/**
 * 获取来源设备
 * @return string
 */
function get_equipment()
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
        $os = 'Windows 95';
    } elseif (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
        $os = 'Windows ME';
    } elseif (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
        $os = 'Windows 98';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
        $os = 'Windows Vista';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
        $os = 'Windows 7';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
        $os = 'Windows 8';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
        $os = 'Windows 10';#添加win10判断
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
        $os = 'Windows XP';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
        $os = 'Windows 2000';
    } elseif (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
        $os = 'Windows NT';
    } elseif (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
        $os = 'Windows 32';
    } elseif (preg_match('/iPhone/i', $agent)) {
        $os = 'iPhone';
    } elseif (preg_match('/iPad/i', $agent)) {
        $os = 'iPad';
    } elseif (preg_match('/Android/i', $agent)) {
        $os = 'Android';
    } elseif (preg_match('/Mac/i', $agent) && preg_match('/OS/i', $agent)) {
        $os = 'Mac OS';
    } elseif (preg_match('/PowerPC/i', $agent)) {
        $os = 'PowerPC';
    } elseif (preg_match('/linux/i', $agent)) {
        $os = 'Linux';
    } elseif (preg_match('/unix/i', $agent)) {
        $os = 'Unix';
    } elseif (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'SunOS';
    } elseif (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
        $os = 'IBM OS/2';
    } elseif (preg_match('/AIX/i', $agent)) {
        $os = 'AIX';
    } elseif (preg_match('/HPUX/i', $agent)) {
        $os = 'HPUX';
    } elseif (preg_match('/NetBSD/i', $agent)) {
        $os = 'NetBSD';
    } elseif (preg_match('/BSD/i', $agent)) {
        $os = 'BSD';
    } elseif (preg_match('/OSF1/i', $agent)) {
        $os = 'OSF1';
    } elseif (preg_match('/IRIX/i', $agent)) {
        $os = 'IRIX';
    } elseif (preg_match('/FreeBSD/i', $agent)) {
        $os = 'FreeBSD';
    } elseif (preg_match('/teleport/i', $agent)) {
        $os = 'teleport';
    } elseif (preg_match('/flashget/i', $agent)) {
        $os = 'flashget';
    } elseif (preg_match('/webzip/i', $agent)) {
        $os = 'webzip';
    } elseif (preg_match('/offline/i', $agent)) {
        $os = 'offline';
    } else {
        $os = '未知';
    }
    return $os;
}

/**
 * 格式化评价情况
 */
function getEvaluationOf($pjqk)
{
    if (!empty($pjqk)) {
        $pjqk_strs = "";
        $pjqk_lists = explode(',', $pjqk);
        foreach ($pjqk_lists as $item) {
            $items = explode('|', $item);
            $pjqk_strs .= '<div class="xingxing_list"><span>' . $items[0] . ' </span>';
            for ($i = 0; $i < 5; $i++) {
                if ($i < $items[1]) {
                    $pjqk_strs .= '<i class="iconfont icon-xingxing_selected huang"></i>';
                } else {
                    $pjqk_strs .= '<i class="iconfont icon-xingxing_selected hui"></i>';
                }
            }
            $pjqk_strs .= '</div>';
        }
        return $pjqk_strs;
    }
}

/**
 * @param $data array  数据
 * @param $parent  string 父级元素的名称 如 parent_id
 * @param $son     string 子级元素的名称 如 comm_id
 * @param $pid     int    父级元素的id 实际上传递元素的主键
 * @return array
 */
function getSubTree($data, $pid = 0)
{
    $tmp = array();
    foreach ($data as $key => $value) {
        if ($value['pid'] == $pid) {
            $value['child'] = getSubTree($data, $value['id']);
            $tmp[] = $value;
        }
    }
    return $tmp;
}

/**
 * 过滤成 应用名://控制器/方法 格式
 */
function pluginUrl($url)
{
    if (empty($url)) {
        return 'javascript:;';
    } else {
        $urls = explode('/', $url);
        if (count($urls) == 1) {
            return $url;
        } elseif (count($urls) == 2) {
            return $urls[0] . '://' . $urls[1];
        } elseif (count($urls) == 3) {
            return $urls[0] . '://' . $urls[1] . '/' . $urls[2];
        }
    }
}

/**
 * 获取后台菜单列表
 */
function we_im_admin_submenu()
{
    $submenu = "";
    $menus = Db::name('im_menu')
        ->where(['status' => 'normal', 'ismenu' => 1])
        ->order('weigh asc')->select();
    $menus = getSubTree($menus->toArray());
    $cururl = 'admin/' . request()->controller(true) . '/' . request()->action(true);
    foreach ($menus as $key => $item) {
        if (empty($item['child'])) {
            if ($item['issys'] == 1) {
                $url = ' href="' . adminUrl($item['name']) . '"';
                $liclass = '';
            } else {
                $url = ' url="' . addons_url(pluginUrl($item['name'])) . '"';
                $liclass = 'plugins ';
            }
            $cur = Cur($cururl, strtolower($item['name']), ' active');
            $notice = $item['id'] == 2 ? '<span class="notice-icon">0</span>' : '';
            $submenu .= "<li class=\"{$liclass}nav-item category-{$item['id']}{$cur}\">";
            $submenu .= "<a{$url}><i class=\"iconfont {$item['icon']}\"></i>{$item['title']}{$notice}</a>";
        } else {
            $open = '';
            if ($item['issys'] == 1) {
               $controller = request()->controller(true);
                if ($controller == 'consult' || $controller == 'clean')$controller = 'set';
                
                if (strpos(strtolower($item['name']), 'admin/' . $controller) !== false) {
                    $open = ' active open';
                }
                $liclass = '';
            } else {
                $liclass = 'plugins ';
            }
            $submenu .= "<li class=\"{$liclass}nav-item category-{$item['id']} nav-item-has-subnav{$open}\">";
            $submenu .= "<a href=\"javascript:;\"><i class=\"iconfont {$item['icon']}\"></i>{$item['title']}<span class=\"spani\"><i class=\"iconfont icon-xiangshang\"></i></span></a>";
            $submenu .= "<ul class=\"nav nav-subnav\">";
            foreach ($item['child'] as $key2 => $item2) {
                if ($item2['issys'] == 1) {
                    $url = ' href="' . adminUrl($item2['name']) . '"';
                } else {
                    $url = ' url="' . addons_url(pluginUrl($item2['name'])) . '"';
                }
                $cur = Cur($cururl, strtolower($item2['name']), ' class="active"');
                $submenu .= "<li{$cur}><a{$url}><i class=\"iconfont {$item2['icon']}\"></i>{$item2['title']}</a></li>";
            }
            $submenu .= "</ul>";
        }
        $submenu .= "</li>";
    }
    return $submenu;
}

/**
 * 格式化图片格式
 * @param $str
 * @return string
 */
function get_img_accept($str)
{
    $accept = [];
    $lists = explode(',', $str);
    foreach ($lists as $key => $item) {
        $accept[$key] = "image/" . $item;
    }
    return implode(',', $accept);
}

/**
 * 判断是否有配置
 * @param $name
 */
function is_plugin_config($name)
{
    $file = root_path() . 'addons/' . $name . DIRECTORY_SEPARATOR . 'config.php';
    if (is_file($file)) {
        if (empty(include($file))) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}

/**
 * 默认
 * @param $defarr
 */
function chat_right_tabs($defarr)
{
    $tabs_strs = "";
    $title_lists = [
        lang('Q&A')
    ];
    $content_lists = [
        $defarr
    ];
    // 钩子返回值
    $lists = event('chat_right_tabs');
    if (!empty($lists[0])) {
        if (!empty($lists[0]['title'])) {
            foreach ($lists[0]['title'] as $title) {
                $title_lists[] = $title;
            }
        }
        if (!empty($lists[0]['content'])) {
            foreach ($lists[0]['content'] as $content) {
                $content_lists[] = $content;
            }
        }
    }

    $tabs_strs .= '<div class="pnl-tabs">';
    foreach ($title_lists as $key => $item) {
        $active = $key == 0 ? ' active' : '';
        $tabs_strs .= '<div class="tab-btn' . $active . '" id="hot-tab">' . $item . '</div>';
    }
    $tabs_strs .= '</div><div class="tabs-lists">';
    foreach ($content_lists as $keys => $items) {
        $active = $keys == 0 ? '' : ' style="display:none;"';
        $tabs_strs .= '<div class="pnl-hot"' . $active . '>';
        if (is_array($items)) {
            $tabs_strs .= '<ul class="rel-list unselect" id="hots">';
            foreach ($items as $key => $item) {
                $tabs_strs .= '<li class="rel-item" data-id="' . $key . '">' . $item . '</li>';
            }
            $tabs_strs .= '</ul>';
        } else {
            $tabs_strs .= '<p>' . $items . '</p>';
        }
        $tabs_strs .= '</div>';
    }
    $tabs_strs .= '</div>';
    return $tabs_strs;
}

/**
 * 根据ID获取会员包括游客和客服的某个字段
 * @param $user_id
 * @param $user_type
 */
function getUserVlaue($user_id, $user_type, $field)
{
    $table = $user_type == 1 ? 'im_customer' : 'im_visitors';
    return Db::name($table)->where('id', $user_id)->value($field);
}

function adminUrl($url, $pam = [], $suffix = true, $domain = false)
{
    $url = Furl($url, $pam, $suffix, $domain);
    if (strpos(strtolower(PHP_SAPI), 'fcgi')
        && strpos(strtolower($_SERVER['REQUEST_URI']), 'admin.php')
        && !preg_match('/admin\.php/', $url)
    ) {
        $url = '/admin.php' . $url;
    }
    return str_replace('/admin/', '/', $url);
}

function apiUrl($url, $pam = [], $suffix = true, $domain = false)
{
    $url = Furl($url, $pam, $suffix, $domain);
    if (!preg_match('/\/api\.php\/api\//', $url)) {
        $url = preg_replace('/\/.*?\.php\/api\//', '/api.php/', $url);
    }
    return $url;
}

function chatUrl($url, $pam = [], $suffix = true, $domain = false)
{
    $url = Furl($url, $pam, $suffix, $domain);
    if (!preg_match('/\/api\.php\/chat\//', $url)) {
        $url = preg_replace('/\/.*?\.php\/chat\//', '/chat/', $url);
    }
    return request()->domain() . $url;
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
            }
        }
    }
}

/**
 * 移除空目录
 * @param string $dir 目录
 */
function remove_empty_folder($dir)
{
    try {
        $isDirEmpty = !(new \FilesystemIterator($dir))->valid();
        if ($isDirEmpty) {
            @rmdir($dir);
            remove_empty_folder(dirname($dir));
        }
    } catch (\UnexpectedValueException $e) {

    } catch (\Exception $e) {

    }
}

// 请求
if (!function_exists(curl_get)) {
    function curl_get($url, $header)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);

        // 设置请求头
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回 
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }
}
// 请求
if (!function_exists('curlPost')) {
    function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "")
    {
        $header = empty($header) ? '' : $header;
        //支持json数据数据提交
        if ($data_type == 'json') {
            $post_string = json_encode($post_data);
        } elseif ($data_type == 'array') {
            $post_string = $post_data;
        } elseif (is_array($post_data)) {
            $post_string = http_build_query($post_data, '', '&');
        }

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);

        // 打印请求的header信息
        //$a = curl_getinfo($ch);
        //var_dump($a);

        curl_close($ch);
        return $result;
    }
}

// 复制文件夹
function copydirs($source, $dest)
{
    if (!is_dir($dest)) {
        mkdir($dest, 0755, true);
    }
    foreach (
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        ) as $item
    ) {
        if ($item->isDir()) {
            $sontDir = $dest . '/' . $iterator->getSubPathName();
            if (!is_dir($sontDir)) {
                mkdir($sontDir, 0755, true);
            }
        } else {
            copy($item, $dest . '/' . $iterator->getSubPathName());
        }
    }
}

/**
 * goalone调用钩子函数
 *
 * @param $event
 * @param null $params
 * @param bool $once
 * @return mixed
 */
function goalong_hook($event, $params = null, bool $once = false)
{
    return \think\facade\Event::trigger($event, $params, $once);
}

/**
 * 支付插件列表
 *
 * @return array
 */
function pay_addons()
{
    $list = goalong_hook('pay_addons');

    $result = [];
    foreach ($list as $val) {

        foreach ($val as $ke => $va) {

            if (!is_array($va) || !isset($va['name']) || !isset($va['title']) || !isset($va['pay'])) continue;//参数判断

            if (isset($va['pay_scene']) && !in_array('any', $va['pay_scene'])) {

                //使用场景判断
                $is_mobile = request()->isMobile();
                if ($is_mobile) {
                    if (!in_array('mobile', $va['pay_scene'])) continue;//使用场景不包含手机
                } else {
                    if (!in_array('pc', $va['pay_scene'])) continue;//使用场景不包含电脑
                }
            }

            $result[$va['name'] . '-' . $ke] = $va['title'];
        }
    }

    return $result;
}

/**
 * 重写插件配置文件函数
 *
 * @param $name
 * @return mixed
 */
function rewrite_addons_config($name)
{
    $addons = get_addons_instance($name);
    $config = $addons->getConfig(1, 0);

    foreach ($config as $k => &$v) {

        if ($v['name'] === 'pay_type') {
            $list = goalong_hook('pay_addons');

            $result = [];
            foreach ($list as $val) {

                foreach ($val as $ke => $va) {

                    if (!is_array($va) || !isset($va['name']) || !isset($va['title']) || !isset($va['pay'])) continue;//参数判断
                    if (isset($addons->use_pay_result) &&//插件设置了支付方式的限制
                        is_array($addons->use_pay_result) &&//限制变量类型正确
                        (!isset($va['pay_result']) ||
                            !is_string($va['pay_result']) ||
                            !in_array($va['pay_result'], $addons->use_pay_result))//支付插件使用方式不适合
                    ) continue;//判断支付结果是否符合

                    $result[$va['name'] . '-' . $ke] = $va['title'];
                }
            }

            $v['content'] = $result;
        } else if ($v['name'] === 'send') {

            $list = goalong_hook('sms_addons');

            $result = [];
            foreach ($list as $val) {

                foreach ($val as $va) {

                    if (!is_array($va) || !isset($va['name']) || !isset($va['title']) || !isset($va['send'])) continue;//参数判断

                    $result[$va['name'] . '-' . $va['send']] = $va['title'];
                }
            }

            $v['content'] = array_merge($v['content'], $result);
        }
    }

    return $config;
}

/**
 * 支付辅助函数
 *
 * @param $key
 * @param $params
 * @return mixed
 */
function goalong_pay($key, $params)
{
    $list = explode('-', $key);
    if (!isset($list[1])) return goalong_hook($key, $params, 1);

    list($addons_name, $addons_key) = $list;
    $addons = get_addons_instance($addons_name);

    $pays = $addons->pay_addons();
    if (!isset($pays[$addons_key])) return goalong_hook($key, $params, 1);

    if (isset($pays[$addons_key]['params'])) $params['pay_addons_params'] = $pays[$addons_key]['params'];

    $addons_function = $pays[$addons_key]['pay'];
    return $addons->$addons_function($params);
}

/**
 * 根据
 *
 * @param $type
 * @param $param
 * @return string
 */
function use_pay_content($type, $param)
{
    switch ($type) {
        case 'url':
            return "<br/>请在打开的页面进行支付或<a target='_blank' href='{$param['message']}'>点击支付</a>";
        case 'qr':
            return "<br/>请扫描下方二维码支付！";
        default:
            return '';
    }
}

/**
 * 判断是否https函数
 *
 * @return string
 */
function is_https()
{
    return request()->scheme();
}

/**
 * 短信插件列表
 *
 * @return array
 */
function sms_addons()
{
    $list = goalong_hook('sms_addons');

    $result = [];
    foreach ($list as $val) {

        foreach ($val as $va) {

            if (!is_array($va) || !isset($va['name']) || !isset($va['title']) || !isset($va['send'])) continue;//参数判断

            $result[$va['name'] . '-' . $va['send']] = $va['title'];
        }
    }

    return $result;
}

/**
 * 短信辅助函数
 *
 * @param $key
 * @param $params
 * @return mixed
 */
function goalong_sms($key, $params)
{
    $list = explode('-', $key);
    if (!isset($list[1])) return goalong_hook($key, $params, 1);

    list($addons_name, $addons_key) = $list;
    $addons = get_addons_instance($addons_name);

    $pays = $addons->sms_addons();
    if (!isset($pays[$addons_key])) return goalong_hook($key, $params, 1);

    if (isset($pays[$addons_key]['params'])) $params['sms_addons_params'] = $pays[$addons_key]['params'];

    $addons_function = $pays[$addons_key]['send'];
    return $addons->$addons_function($params);
}

function stat_wjd()
{
    return Db::name('im_unread')->where('number', '>', 0)->count();
}