<?php

namespace app\common\controller;

use think\Db;
use app\common\library\Auth;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Validate;
use EasyWeChat\Foundation\Application;

/*小程序Config*/
define('appid', 'wxf0764538543e66eb');
define('secret', '195607cd34fd72688810735f51582fb1');
/*管易云Api
Config*/
define('URL', 'http://v2.api.guanyierp.com/rest/erp_open');
define('APPKEY', '149701');
define('SESSIONKEY', '57a1af5a2c9c4e5990e2859ad47e76f1');
define('SECRET', 'c804b81005504d36a2eb27114ff38ceb');

/**
 * API控制器基类
 */
class Api
{
    /**
     * @var Request Request 实例
     */
    protected $request;

    /**
     * @var bool 验证失败是否抛出异常
     */
    protected $failException = false;

    /**
     * @var bool 是否批量验证
     */
    protected $batchValidate = false;

    /**
     * @var array 前置操作方法列表
     */
    protected $beforeActionList = [];

    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = [];

    /**
     * 权限Auth
     * @var Auth
     */
    protected $auth = null;

    /**
     * 默认响应输出类型,支持json/xml
     * @var string
     */
    protected $responseType = 'json';

    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->request = is_null($request) ? Request::instance() : $request;

        // 控制器初始化
        $this->_initialize();

        // 前置操作方法
        if ($this->beforeActionList) {
            foreach ($this->beforeActionList as $method => $options) {
                is_numeric($method) ?
                    $this->beforeAction($options) :
                    $this->beforeAction($method, $options);
            }
        }
    }

    /**
     * 初始化操作
     * @access protected
     */
    protected function _initialize()
    {
        //跨域请求检测
        check_cors_request();

        //移除HTML标签
        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->auth = Auth::instance();

        $modulename = $this->request->module();
        $controllername = Loader::parseName($this->request->controller());
        $actionname = strtolower($this->request->action());

        // token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));

        $path = str_replace('.', '/', $controllername) . '/' . $actionname;
        // 设置当前请求的URI
        $this->auth->setRequestUri($path);
        // 检测是否需要验证登录
        if (!$this->auth->match($this->noNeedLogin)) {
            //初始化
            $this->auth->init($token);
            //检测是否登录
            if (!$this->auth->isLogin()) {
                $this->error(__('Please login first'), null, 401);
            }
            // 判断是否需要验证权限
            if (!$this->auth->match($this->noNeedRight)) {
                // 判断控制器和方法判断是否有对应权限
                if (!$this->auth->check($path)) {
                    $this->error(__('You have no permission'), null, 403);
                }
            }
        } else {
            // 如果有传递token才验证是否登录状态
            if ($token) {
                $this->auth->init($token);
            }
        }

        $upload = \app\common\model\Config::upload();

        // 上传信息配置后
        Hook::listen("upload_config_init", $upload);

        Config::set('upload', array_merge(Config::get('upload'), $upload));

        // 加载当前控制器语言包
        $this->loadlang($controllername);
    }

    /**
     * 加载语言文件
     * @param string $name
     */
    protected function loadlang($name)
    {
        $name = Loader::parseName($name);
        Lang::load(APP_PATH . $this->request->module() . '/lang/' . $this->request->langset() . '/' . str_replace('.', '/', $name) . '.php');
    }

    /**
     * 操作成功返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为1
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function success($msg = '', $data = null, $code = 1, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 操作失败返回的数据
     * @param string $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为0
     * @param string $type 输出类型
     * @param array $header 发送的 Header 信息
     */
    protected function error($msg = '', $data = null, $code = 0, $type = null, array $header = [])
    {
        $this->result($msg, $data, $code, $type, $header);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 要返回的数据
     * @param int $code 错误码,默认为0
     * @param string $type 输出类型,支持json/xml/jsonp
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($msg, $data = null, $code = 0, $type = null, array $header = [])
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
            'time' => Request::instance()->server('REQUEST_TIME'),
            'data' => $data,
        ];
        // 如果未设置类型则自动判断
        $type = $type ? $type : ($this->request->param(config('var_jsonp_handler')) ? 'jsonp' : $this->responseType);

        if (isset($header['statuscode'])) {
            $code = $header['statuscode'];
            unset($header['statuscode']);
        } else {
            //未设置状态码,根据code值判断
            $code = $code >= 1000 || $code < 200 ? 200 : $code;
        }
        $response = Response::create($result, $type, $code)->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 前置操作
     * @access protected
     * @param string $method 前置操作方法名
     * @param array $options 调用参数 ['only'=>[...]] 或者 ['except'=>[...]]
     * @return void
     */
    protected function beforeAction($method, $options = [])
    {
        if (isset($options['only'])) {
            if (is_string($options['only'])) {
                $options['only'] = explode(',', $options['only']);
            }

            if (!in_array($this->request->action(), $options['only'])) {
                return;
            }
        } elseif (isset($options['except'])) {
            if (is_string($options['except'])) {
                $options['except'] = explode(',', $options['except']);
            }

            if (in_array($this->request->action(), $options['except'])) {
                return;
            }
        }

        call_user_func([$this, $method]);
    }

    /**
     * 设置验证失败后是否抛出异常
     * @access protected
     * @param bool $fail 是否抛出异常
     * @return $this
     */
    protected function validateFailException($fail = true)
    {
        $this->failException = $fail;

        return $this;
    }

    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @param mixed $callback 回调方法(闭包)
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        if (is_array($validate)) {
            $v = Loader::validate();
            $v->rule($validate);
        } else {
            // 支持场景
            if (strpos($validate, '.')) {
                list($validate, $scene) = explode('.', $validate);
            }

            $v = Loader::validate($validate);

            !empty($scene) && $v->scene($scene);
        }

        // 批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }
        // 设置错误信息
        if (is_array($message)) {
            $v->message($message);
        }
        // 使用回调验证
        if ($callback && is_callable($callback)) {
            call_user_func_array($callback, [$v, &$data]);
        }

        if (!$v->check($data)) {
            if ($this->failException) {
                throw new ValidateException($v->getError());
            }

            return $v->getError();
        }

        return true;
    }

    protected function token()
    {
        $token = $this->request->param('__token__');

        //验证Token
        if (!Validate::make()->check(['__token__' => $token], ['__token__' => 'require|token'])) {
            $this->error(__('Token verification error'), ['__token__' => $this->request->token()]);
        }

        //刷新Token
        $this->request->token();
    }

    //测试题Insert
    public function NaireInsert($UserId, $ID, $Answer)
    {
        if ($ID < 5) {
            if ($ID == 1) {
                $Time = strtotime(date($Answer));
                $Res = Db::name('sleep')->where(['user_id' => $UserId])->where('type', 0)->order('id desc')->update(['birthday' => $Time]);/*第一部分填空题*/
            } elseif ($ID == 2) {
                $Res = Db::name('sleep')->where(['user_id' => $UserId])->where('type', 0)->order('id desc')->update(['height' => $Answer]);/*第一部分填空题*/
            } elseif ($ID == 3) {
                $Res = Db::name('sleep')->where(['user_id' => $UserId])->where('type', 0)->order('id desc')->update(['weight' => $Answer]);/*第一部分填空题*/
            } elseif ($ID == 4) {
                $Array = [[$ID, $Answer]];
                $Res = Db::name('sleep')->where(['user_id' => $UserId])->where('type', 0)->order('id desc')->update(['choose' => json_encode($Array)]);/*第一部分选择题*/
            } else {
                //EQ 0
                $Res = Db::name('sleep')->insert(['user_id' => $UserId, 'sex' => $Answer, 'createtime' => time(), 'updatetime' => time(), 'type' => 0]);
            }
        } else {
            $ChooseJson = Db::name('sleep')->where('user_id', $UserId)->order('id desc')->where('type', 0)->value('choose');
            $Array = json_decode($ChooseJson);
            $Array[] = [$ID, $Answer];
            $Res = Db::name('sleep')->where(['user_id' => $UserId])->where('type', 0)->order('id desc')->update(['choose' => json_encode($Array)]);/*选择题*/
        }
        if (!$Res) {
            $this->error('第一部分ID为' . $ID . '提交失败', 0);
        }
    }

    /**
     * 检测Token
     */
    protected function is_token($token)
    {
        if (empty($token['token'])) {
            $this->error('请登录后在操作');
        }
        $is_token = Db::name('user')->where(['token' => $token['token']])->find();
        if (!$is_token) {
            $this->error('登陆已过期,请重新登陆');
        }
        return $is_token['id'];
    }

    //res
    public function Res($res)
    {
        if ($res) {
            $this->success('成功', 1);
        } else {
            $this->error('失败', 0);
        }
    }

    //分页
    function page_array($count, $page, $array, $order)
    {
        global $countpage; #定全局变量
        $page = (empty($page)) ? '1' : $page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start = ($page - 1) * $count; #计算每次分页的开始位置
        if ($order == 1) {
            $array = array_reverse($array);
        }
        $totals = count($array);
        $countpage = ceil($totals / $count); #计算总页面数
        $pagedata = array();
        $pagedata = array_slice($array, $start, $count);
        return $pagedata;  #返回查询数据
    }

    //销量排序 升序
    public function SalesAsc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['Sales'] = $v['Sales'];
        }
        array_multisort($newArr, SORT_ASC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }

    //销量排序 降序
    public function SalesDesc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['Sales'] = $v['Sales'];
        }
        array_multisort($newArr, SORT_DESC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }

    //价格排序 升序
    public function PriceAsc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['Price'] = $v['Price'];
        }
        array_multisort($newArr, SORT_ASC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }

    //价格排序 降序
    public function PriceDesc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['Price'] = $v['Price'];
        }
        array_multisort($newArr, SORT_DESC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }


    //我的草籽排序 升序
    public function MyTreeAsc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['CountMoney'] = $v['CountMoney'];
        }
        array_multisort($newArr, SORT_ASC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }

    //我的草籽排序 降序
    public function MyTreeDesc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['CountMoney'] = $v['CountMoney'];
        }
        array_multisort($newArr, SORT_DESC, $person);//SORT_DESC为降序,SORT_ASC为升序
        return $person;
    }


    //库存检查
    public function StockLook($GoodsID, $Num)
    {
        $Stock = Db::name('goods')->where('id', $GoodsID)->value('stock');
        if ($Num > $Stock) {
            $this->error('库存不足', 0);
            die;
        }
    }

    //生成订单号
    public function order_sn()
    {
        @date_default_timezone_set("PRC");
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码(YYYYMMDDHHIISSNNNNNNNNCC)
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT); //生成唯一订单号
        return $osn;
    }

    //生成支付单号
    public function PayOrder()
    {
        //生成订单号
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
//        $PayOrder = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        $PayOrder = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $PayOrder;
    }

    //计算订单总价
    public function Total($UserID, $Price)
    {
        //是否是新用户
        $IsNew = Db::name('user')->where('id', $UserID)->value('is_new');
        if ($IsNew == 1) {
            /*新人满减优惠:满199减30,满299减50,满499减100*/
            if ($Price > 498) {
                $Total = $Price - 100;
            } elseif ($Price > 298) {
                $Total = $Price - 50;
            } elseif ($Price > 198) {
                $Total = $Price - 30;
            } else {
                $Total = $Price;
            }
        } else {
            $Total = $Price;
        }
        return $Total;
    }

    //数组去重
    function second_array_unique_bykey($arr, $key)
    {
        $tmp_arr = array();
        foreach ($arr as $k => $v) {
            if (in_array($v[$key], $tmp_arr))   //搜索$v[$key]是否在$tmp_arr数组中存在,若存在返回true
            {
                unset($arr[$k]); //销毁一个变量  如果$tmp_arr中已存在相同的值就删除该值
            } else {
                $tmp_arr[$k] = $v[$key];  //将不同的值放在该数组中保存
            }
        }
        //ksort($arr); //ksort函数对数组进行排序(保留原键值key)  sort为不保留key值
        return $arr;
    }


    public function curlPost1($url, $data)
    {
        $ch = curl_init();
        $postJosnData = json_encode($data);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postJosnData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }


    //生成小程序渠道码
    public function QudaoInserMiniAppQrCode($Qudao_id)
    {
        //小程序码
        $options = [
            'app_id' => appid,
            'secret' => secret,
        ];
        $app = new Application($options);
        // 获取 access token 实例
        $accessToken = $app->access_token;
        $AccessToken = $accessToken->getToken();
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $AccessToken;
        $Json = [
            'scene' => 'qudao_id=' . $Qudao_id,
            'path' => '/pages/tabbar/home',
//            'is_hyaline' => True
        ];
        $MiniAppQrcodeVendor = $this->curlPost1($url, $Json);
        $PayOrder = $this->PayOrder();
        $path = './MiniAppQrCode/' . $PayOrder . '.png';
        $res = file_put_contents($path, $MiniAppQrcodeVendor);//将微信返回的图片数据流写入文件
        if ($res === false) {
            $this->error('生成小程序码失败', 0);
            die;
        } else {
            $MiniAppQrcodeUrl = $this->request->domain() . '/MiniAppQrCode/' . $PayOrder . '.png';
            return $MiniAppQrcodeUrl;
        }
    }

    //生成小程序码
    public function InserMiniAppQrCode($Goods_id, $UserId, $Path)
    {
        //小程序码
        $options = [
            'app_id' => appid,
            'secret' => secret,
        ];
        $app = new Application($options);
        // 获取 access token 实例
        $accessToken = $app->access_token;
        $AccessToken = $accessToken->getToken();
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' . $AccessToken;
        $Json = [
            'scene' => 'Goods_id=' . $Goods_id . '&User_id=' . $UserId,
            'path' => $Path,
//            'is_hyaline' => True
        ];
        $MiniAppQrcodeVendor = $this->curlPost1($url, $Json);
        $PayOrder = $this->PayOrder();
        $path = './MiniAppQrCode/' . $PayOrder . '.png';
        $res = file_put_contents($path, $MiniAppQrcodeVendor);//将微信返回的图片数据流写入文件
        if ($res === false) {
            $this->error('生成小程序码失败', 0);
            die;
        } else {
            $MiniAppQrcodeUrl = $this->request->domain() . '/MiniAppQrCode/' . $PayOrder . '.png';
            return $MiniAppQrcodeUrl;
        }
    }

    //收益计算
    public function CountMoney($UserId, $Map1, $Map2)
    {
        $MoneyArr = Db::name('money')->where($Map1)->where($Map2)->where('user_id', $UserId)->select();
        if (empty($MoneyArr)) {
            $CountMoney = 0;
        } else {
            foreach ($MoneyArr as $k => $v) {
                $CountMoneyArray[] = $v['money'];
            }
            $CountMoney = array_sum($CountMoneyArray);
        }
        return $CountMoney;
    }

    //上个月月末时间戳
    public function LastMoneyTime()
    {
        $thismonth = date('m');
        $thisyear = date('Y');
        if ($thismonth == 1) {
            $lastmonth = 12;
            $lastyear = $thisyear - 1;
        } else {
            $lastmonth = $thismonth - 1;
            $lastyear = $thisyear;
        }
        $lastStartDay = $lastyear . '-' . $lastmonth . '-1';
        $lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));

        $b_time = strtotime($lastStartDay);//上个月的月初时间戳
        $e_time = strtotime($lastEndDay);//上个月的月末时间戳
        return $e_time;
    }


    //检查收益待入账
    public function UpdateMoney($UserId)
    {
        //查询所有待入账信息
        $MoneyArray = Db::name('money')->where('user_id', $UserId)->where('status', 0)->select();
        $LastMoneyTime = $this->LastMoneyTime();
        $Tody = date('d');
        if (!empty($MoneyArray)) {
            foreach ($MoneyArray as $k => $v) {
                if ($v['type'] == 1) {
                    //自购返现
                    //上个月月底时间戳
                    if ($Tody > 19) {
                        //判断今天是否是20号
                        if ($v['createtime'] < $LastMoneyTime) {
                            Db::name('money')->where('user_id', $UserId)->where('id', $v['id'])->update(['status' => 1]);
                            $UserMoney = Db::name('user')->where('id', $UserId)->value('money');
                            Db::name('user')->where('id', $UserId)->update(['money' => $UserMoney + $v['money']]);
                        }
                    }
                } else {
                    //分销收入
                    //查询订单状态
                    $OrderStatus = Db::name('order')->where('OrderSn', $v['OrderSn'])->value('status');
                    if (!empty($OrderStatus)) {
                        if ($OrderStatus == 3) {
                            Db::name('money')->where('user_id', $UserId)->where('id', $v['id'])->update(['status' => 1]);
                            $UserMoney = Db::name('user')->where('id', $UserId)->value('money');
                            Db::name('user')->where('id', $UserId)->update(['money' => $UserMoney + $v['money']]);
                        }
                    }
                }
            }
        }
    }

    //指定月起止时间戳
    public function mFristAndLast($y, $m)
    {
        $y = $y ? $y : date('Y');
        $m = $m ? $m : date('m');
        $d = date('t', strtotime($y . '-' . $m));
        return array("start" => strtotime($y . '-' . $m), "end" => mktime(23, 59, 59, $m, $d, $y));
    }


    //已消费金额
    public function YiXiaofeiMoney($UserId)
    {
        $OrderArray = Db::name('order')->where('user_id', $UserId)->where('status', 3)->select();
        if (empty($OrderArray)) {
            //已消费Consumed
            $Consumed = 0;
        } else {
            foreach ($OrderArray as $k => $v) {
                $ConsumedArray[] = $v['total'];
            }
            $Consumed = array_sum($ConsumedArray);
        }
        return $Consumed;
    }


    //快递100
    public function kuaidi100($OrderSn)
    {
        $OrderInfo = Db::name('order')->where('OrderSn', $OrderSn)->find();
        if (empty($OrderInfo)) {
            $this->error('未查询到订单', 0);
            die;
        }
        $Code = Db::name('kuaidi')->where('name', $OrderInfo['ems_company'])->value('code');
        if (empty($Code)) {
            $this->error('未查询出物流信息');
            die;
        }
        $key = 'FCxizJUb2755';                        //客户授权key
        $customer = 'FC3BF8F18CF0A9A2B6C0305AD2816978';                   //查询公司编号
        $param = array(
            'com' => $Code,             //快递公司编码
            'num' => $OrderInfo['ems_order'],     //快递单号
            'phone' => '',                //手机号
            'from' => '',                 //出发地城市
            'to' => '',                   //目的地城市
            'resultv2' => '1'             //开启行政区域解析
        );
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"] . $key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址
        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";              //默认UTF-8编码格式
        }
        $post_data = substr($params, 0, -1);
//        echo '请求参数<br/>'.$post_data;
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result);
        $data = json_decode($data);

//        echo '<br/><br/>返回数据<br/>';
//        echo var_dump($data);
        return $data;
    }

    //我的下级人数
    public function MyUpInvitePeopleNum($UserID)
    {
        //初始化Config
        $Level1 = 0;
        $Level2 = 0;
        $Level3 = 0;
        //一级
        $Array = Db::name('group')->where('fuser_id', $UserID)->select();
        if (!empty($Array)) {
            foreach ($Array as $k => $v) {
                $List[$k]['id'] = $v['id'];
                $List[$k]['user_id'] = $v['user_id'];
            }
            foreach ($List as $k => $v) {
                //查询二级
                $Second = Db::name('group')->where('fuser_id', $UserID)->select();
                foreach ($Second as $key => $value) {
                    $List[$k]['id'] = $value['id'];
                    $List[$k]['user_id'] = $value['user_id'];
                }
            }
            foreach ($List as $k => $v) {
                $Userinfo = Db::name('user')->where('id', $v['user_id'])->value('level');
                if (!empty($Userinfo)) {
                    if ($Userinfo == 1) {
                        $Level1++;
                    } elseif ($Userinfo == 2) {
                        $Level2++;
                    } elseif ($Userinfo == 3) {
                        $Level3++;
                    }
                }
            }
        }
        $Array = [
            'level1' => $Level1,
            'level2' => $Level2,
            'level3' => $Level3,
        ];
        return $Array;
    }
}