<?php

function apiReturn($errCode = 0, $errMsg = 'ok', $data = [])
{
    $data = [
        'err_code' => $errCode,
        'err_msg' => $errMsg,
        'code' => $errCode,
        'msg' => $errMsg,
    ];
    if (!empty($data['total'])) {
        $data['count'] = $data['total'];
    }

    if (!empty($data)) {
        foreach ($data as $k => $v) {
            $data[$k] = $v;
        }
    }
    return response()->json($data, 200);
}

function curl($url, $params = false, $isPost = 0, $https = 0, $cookie = '', $timeout = 1000)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT,
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_REFERER, Config('website.data'));
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
    if ($isPost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            if (is_array($params)) {
                $params = http_build_query($params);
            }
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }

    $response = curl_exec($ch);
    if ($response === false) {
        echo "cURL Error: " . curl_error($ch);
        return false;
    }
    curl_close($ch);
    return $response;
}

//检查权限,仅支持验证单个权限
function perm($userId, $perm1 = '')
{
    $permArr = config('perm.perm');
    $NotAuth = $permArr['notAuth'];
    $AdminID = $permArr['adminGroup'];
    if ((!in_array($perm1, $NotAuth)) && !in_array($userId, $AdminID)) {//过滤不用鉴权的方法与用户
        $permID = $permArr['id'];
        $url = $permArr['url'] . '/' . $userId . '/' . $permID . '?perms=' . $perm1;
        $result = json_decode(curl($url, '', 0), true);
        if (!isset($result['retcode']) || $result['retcode'] !== 0 || $result['data']['perms'][$perm1] == false) {
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
}

//根据权限生成菜单
function menu($menu, $user)
{
    $perm = chils($menu);
    $perm1 = implode(',', $perm);
    $permArr = config('perm.perm');
    $perm = $permArr['id'];

    $url = $permArr['url'] . '/' . $user . '/' . $perm . '?perms=' . $perm1;
    $result = json_decode(curl($url, '', false), true);
    if ($result['retcode'] === 0) {
        $find = $result['data']['perms'];
        $menu = DeleteMenu($menu, $find);
        if (!empty($menu) && is_array($menu)) {
            foreach ($menu as $k => $v) {
                $v = (array)$v;
                if ($v['title'] != 'Dashboard' && count($v['childs']) == 0 && empty($v['href'])) {
                    unset($menu[$k]);
                }
            }
        }
        return array_merge($menu);
    } else {
        return [];
    }
}

//提取菜单
function chils($chils)
{
    $perms = [];
    foreach ($chils as $k => $v) {
        $perm_a = [];
        $perm = [];
        if (strlen($v['href']) > 2) {
            $action = explode('/', $v['href']);
            $perm[] = end($action);
        }
        if (count($v['childs']) > 0) {
            $perm_a = chils($v['childs']);
        }
        $perms = array_merge($perms, array_merge($perm, $perm_a));
    }
    return $perms;
}

//删除没有权限的菜单
function DeleteMenu($menu, $find)
{
    foreach ($menu as $k => $v) {
        if (strlen($v['href']) > 2) {
            $action = explode('/', $v['href']);
            $key = end($action);
            if (empty($find[$key]) || $find[$key] == false) {
                unset($menu[$k]);
            }
        } else {
            if (count($v['childs']) > 0) {
                $menu[$k]['childs'] = array_values(DeleteMenu($v['childs'], $find));
            }
            if (!count($v['childs']) > 0 && $v['title'] != '首页') {
                unset($menu[$k]);
            }//为了删除没有下级的目录
        }
    }
    return array_values($menu);
}

//处理iframe的Url
function iframeUrl($Url)
{
    if (strstr($Url, '?') === false) {
        $Url .= '?view=iframe';
    } else {
        $Url .= '&view=iframe';
    }
    return $Url;
}

//上传文件接口签名
function Autograph()
{
    $url = Config('website.UploadUrl');
    $data['k1'] = time();
    $data['k2'] = MD5(MD5($data['k1']) . Config('fixed.UploadKey'));
    echo '<script>
            k1="' . $data['k1'] . '";
            k2="' . $data['k2'] . '";
            UploadImgUrl="' . $url . '"
        </script>';
}

//判断是否有对应的权限
//request()->perms是CheckLogin中间件过来的
function checkPerm($perm)
{
    $perms = request()->perms;
    return in_array($perm, $perms);
}

//批量清楚前后空格
function BatchTrim($data)
{
    if (!empty($data)) {
        foreach ($data as &$item) {
            $item = trim($item);
        }
        unset($item);
    }
    return $data;
}