1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
<?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 InviteDesc($person)
    {
        $newArr = array();
        foreach ($person as $key => $v) {
            $newArr[$key]['Num'] = $v['Num'];
        }
        array_multisort($newArr, SORT_DESC, $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', 'K', 'L');
//        $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';
        $JsonDecode = json_decode($MiniAppQrcodeVendor, true);
        if ($JsonDecode['errcode'] && $JsonDecode['errcode'] == 40001) {
            $this->error('生成海报超时');
        }
        $res = file_put_contents($path, $MiniAppQrcodeVendor);//将微信返回的图片数据流写入文件
        if ($res === false) {
            $this->error('生成小程序码失败', 0);
            die;
        } else {
            $MiniAppQrcodeUrl = $this->request->domain() . '/MiniAppQrCode/' . $PayOrder . '.png';
            return $MiniAppQrcodeUrl;
        }
    }


    //生成User小程序码
    public function UserInserMiniAppQrCode($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=0&User_id=' . $UserId,
            'path' => $Path,
//            'is_hyaline' => True
        ];
        $MiniAppQrcodeVendor = $this->curlPost1($url, $Json);
        $PayOrder = $this->PayOrder();
        $path = './MiniAppQrCode/' . $UserId . '.png';
        $res = file_put_contents($path, $MiniAppQrcodeVendor);//将微信返回的图片数据流写入文件
        if ($res === false) {
            $this->error('生成小程序码失败', 0);
            die;
        } else {
            $MiniAppQrcodeUrl = $this->request->domain() . '/MiniAppQrCode/' . $UserId . '.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;
    }

    //检测优惠券过期
    public function ExpTick($UserId)
    {
        Db::name('user_tick')->where('user_id', $UserId)->where('exp_time', '<', time())->update(['status' => 2]);
    }
}