<?php
/**
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/28
 */

namespace app\models\wechat;

use app\models\store\StoreOrder;
use app\models\user\User;
use app\models\user\UserBill;
use app\models\user\UserExtract;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\facade\Config;
use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;
use crmeb\services\WechatService;
use crmeb\services\SystemConfigService;
use app\models\store\StoreOrderStatus;
use app\models\wechat\WechatUser as UserModel;

/**
 * 微信用户 model
 * Class WechatUser
 * @package app\models\wechat
 */
class WechatUser extends BaseModel
{

    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'uid';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'wechat_user';

    use ModelTrait;

    protected $insert = ['add_time'];

    /**
     * 用uid获得 微信openid
     * @param $uid
     * @return mixed
     * @throws \Exception
     */
    public static function uidToOpenid($uid)
    {
        $openid = self::where('uid', $uid)->value('openid');
        if (!$openid) exception('对应的openid不存在!');
        return $openid;
    }

    /**
     * 用uid获得 小程序 openid
     * @param $uid
     * @return mixed
     * @throws \Exception
     */
    public static function uidToRoutineOpenid($uid)
    {
        $openid = self::where('uid', $uid)->value('routine_openid');
        if (!$openid) exception('对应的routine_openid不存在!');
        return $openid;
    }

    public static function setAddTimeAttr($value)
    {
        return time();
    }

    protected function getAddTimeAttr($value)
    {
        if ($value) return date('Y-m-d H:i', $value);
        return $value;

    }

    /**
     * .添加新用户
     * @param $openid
     * @return object
     */
    public static function setNewUser($openid)
    {
        $userInfo = WechatService::getUserInfo($openid);
        $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
        return self::create($userInfo);
    }

    /**
     * 更新用户信息
     * @param $openid
     * @return bool
     */
    public static function updateUser($openid)
    {
        $userInfo = WechatService::getUserInfo($openid);
        $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
        return self::edit($userInfo, $openid, 'openid');
    }

    /**
     * 用户存在就更新 不存在就添加
     * @param $openid
     */
    public static function saveUser($openid)
    {
        self::be($openid, 'openid') == true ? self::updateUser($openid) : self::setNewUser($openid);
    }

    /**
     * 用户取消关注
     * @param $openid
     * @return bool
     */
    public static function unSubscribe($openid)
    {
        return self::edit(['subscribe' => 0], $openid, 'openid');
    }

    /**
     * 获取微信用户
     * @param array $where
     * @return array
     */
    public static function systemPage($where = array(), $isall = false)
    {
        $model = new self;
        $model = $model->alias('w');
        $model = $model->where('w.openid|routine_openid', 'NOT NULL');
        if ($where['nickname'] !== '') $model = $model->where('w.nickname', 'LIKE', "%$where[nickname]%");
        $model = self::getModelTime($where, $model, "w.add_time");
        if (isset($where['tagid_list']) && $where['tagid_list'] !== '') {
            $tagid_list = explode(',', $where['tagid_list']);
            foreach ($tagid_list as $v) {
                $model = $model->where('w.tagid_list', 'LIKE', "%$v%");
            }
        }
        if (isset($where['groupid']) && $where['groupid'] !== '-1') $model = $model->where('w.groupid', "$where[groupid]");
        if (isset($where['sex']) && $where['sex'] !== '') $model = $model->where('w.sex', "$where[sex]");
        if (isset($where['subscribe']) && $where['subscribe'] !== '') $model = $model->where('w.subscribe', "$where[subscribe]");
        if (isset($where['type']) && $where['type'] !== '') $model = $model->where('w.user_type', $where['type']);
        if (isset($where['mer_id']) && $where['mer_id'] !== '') $model = $model->where('u.mer_id', $where['mer_id']);
        $model = $model->join('user u', 'u.uid = w.uid');
        $model = $model->order('w.uid desc');
        $count = $model->count();
        $list = $model->page((int)$where['page'], (int)$where['limit'])
            ->field('w.uid,w.openid,w.nickname,w.headimgurl,w.sex,w.country,w.province,w.city,w.subscribe')
            ->select()
            ->each(function ($item) {
//                $groupList = UserModel::getUserGroup();
//                $tagList = UserModel::getUserTag();
//                $groupList = [2=>'222'];//测试
//                $tagList = [2=>'222'];//测试
//                if (!is_array($tagList)){
//                    $item['tag_name'] = [];
//                }else{
//                    $tagId = explode(',',$item['tagid_list']);
//                    if(!$tagList || $item['tagid_list'] == ''|| !$tagId){
//                        $item['tag_name'] = [];
//                    }else{
//                        foreach ($tagId as $k=>$vo){
//                            if (isset($tagList[$vo])){
//                                $item['tag_name'][$k] = $tagList[$vo];
////                                $item['tag_name'][$k]['name'] = $tagList[$vo];
//                            }
//                        }
//                    }
//                }
//                if (!is_array($groupList)){
//                    $item['group_name'] = '无';
//                }else{
//                    if(!$groupList || $item['groupid'] == 0 || !isset($groupList[$item['groupid']])){
//                        $item['group_name'] = '无';
//                    }else{
//                        $item['group_name'] = $groupList[$item['groupid']];
//                    }
//                }
                $item['subscribe_time'] = $item['subscribe_time'] ? date('Y-m-d H:i', $item['subscribe_time']) : '';
            });
        return compact('count', 'list');
    }

    /**
     * 获取微信用户
     * @param array $where
     * @return array
     */
    public static function exportData($where = array(), $isall = false)
    {
        $model = new self;
        $model = $model->where('openid|routine_openid', 'NOT NULL');
        if ($where['nickname'] !== '') $model = $model->where('nickname', 'LIKE', "%$where[nickname]%");
        $model = self::getModelTime($where, $model, "add_time");
        if (isset($where['tagid_list']) && $where['tagid_list'] !== '') {
            $tagid_list = explode(',', $where['tagid_list']);
            foreach ($tagid_list as $v) {
                $model = $model->where('tagid_list', 'LIKE', "%$v%");
            }
        }
        if (isset($where['groupid']) && $where['groupid'] !== '-1') $model = $model->where('groupid', "$where[groupid]");
        if (isset($where['sex']) && $where['sex'] !== '') $model = $model->where('sex', "$where[sex]");
        if (isset($where['subscribe']) && $where['subscribe'] !== '') $model = $model->where('subscribe', "$where[subscribe]");
        $model = $model->order('uid desc');
        $list = $model->select()->toArray();

        return $list;
    }

    public static function setSpreadWhere($where = [], $alias = 'a', $model = null)
    {
        $model = is_null($model) ? new  self() : $model;
        if ($alias) {
            $model = $model->alias($alias)->join('user u', 'a.uid=u.uid')->order('u.uid desc');
            $alias .= '.';
        }
        $status = (int)SystemConfigService::get('store_brokerage_statu');
        if ($status == 1) {
            if ($Listuids = User::where(['is_promoter' => 1])->field('uid')->select()) {
                $newUids = [];
                foreach ($Listuids as $item) {
                    $newUids[] = $item['uid'];
                }
                $uids = $newUids;
                unset($uid, $newUids);
                $model = $model->where($alias . 'uid', 'in', implode(',', $uids));
            } else
                $model = $model->where($alias . 'uid', -1);
        }
        if ($where['nickname'] !== '') $model = $model->where("{$alias}nickname|{$alias}uid|u.phone", 'LIKE', "%$where[nickname]%");
        $model = self::getModelTime($where, $model, "{$alias}add_time");
        if (isset($where['sex']) && $where['sex'] !== '') $model = $model->where($alias . 'sex', $where['sex']);
        if (isset($where['subscribe']) && $where['subscribe'] !== '') $model = $model->where($alias . 'subscribe', $where['subscribe']);
        if (isset($where['order']) && $where['order'] != '') $model = $model->order($where['order']);
        if (isset($where['user_type']) && $where['user_type'] != '') {
            if ($where['user_type'] == 1) {
                $model = $model->where($alias . 'unionid', 'neq', 'NULL');
            } else if ($where['user_type'] == 2)
                $model = $model->where($alias . 'openid', 'neq', 'NULL')->where($alias . 'unionid', 'NULL');
            else if ($where['user_type'] == 3)
                $model = $model->where($alias . 'routine_openid', 'neq', 'NULL')->where($alias . 'unionid', 'NULL');
        }
        if (isset($where['is_time']) && isset($where['data']) && $where['data']) $model = self::getModelTime($where, $model, $alias . 'add_time');
        return $model;
    }

    /**
     * 获取分销用户
     * @param array $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function agentSystemPage($where = [])
    {
        //提现数据
        $exteactSql = UserExtract::merSet($where['mer_id'] ?? false)->where(['status' => 1])
            ->group('uid')
            ->field(['sum(extract_price) as extract_count_price', 'count(id) as extract_count_num', 'uid as euid'])
            ->fetchSql(true)
            ->select();
        //订单数据
        $orderSql = StoreOrder::merSet($where['mer_id'] ?? false)->alias('o')
            ->where(['o.paid' => 1, 'o.refund_status' => 0])
            ->field(['sum(o.pay_price) as order_price', 'count(o.id) as order_count', 'o.uid as ouid'])
            ->group('o.uid')
            ->fetchSql(true)
            ->select();
        //佣金数据
        $billSql = UserBill::merSet($where['mer_id'] ?? false)->where(['status' => 1])
            ->where('type', 'brokerage')
            ->where('pm', 1)
            ->group('uid')
            ->field(['sum(number) as brokerage_money', 'uid as buid'])
            ->fetchSql(true)
            ->select();
        $model = User::merSet($where['mer_id'] ?? false)->where(['status' => 1])->where('is_promoter', 1);
        $model = $model->alias('u')
            ->join('(' . $orderSql . ') o', 'o.ouid = u.uid', 'left')
            ->join('(' . $billSql . ') b', 'b.buid = u.uid', 'left')
            ->join('(' . $exteactSql . ') e', 'e.euid = u.uid', 'left');
        if ($where['nickname'] !== '') {
            $model = $model->where("u.nickname|u.uid|u.phone", 'LIKE', "%$where[nickname]%");
        }
        if ($where['data']) $model = self::getModelTime($where, $model, 'u.add_time');
        $count = $model->count();
        $list = $model->field(['avatar as headimgurl', 'brokerage_price as new_money', 'u.*', 'o.*', 'e.*', 'b.*'])
            ->page((int)$where['page'], (int)$where['limit'])
            ->order('u.uid desc')
            ->select();
        $list = count($list) ? $list->toArray() : [];
        $broken_time = intval(sys_config('extract_time'));
        $search_time = time() - 86400 * $broken_time;
        foreach ($list as &$item) {
            if ($spread_uid = User::where('uid', $item['uid'])->value('spread_uid')) {
                if ($user = User::where('uid', $spread_uid)->field(['uid', 'nickname'])->find()) {
                    $item['spread_name'] = $user['nickname'] . '/' . $user['uid'];
                }
            }
            $item['spread_count'] = User::where('spread_uid', $item['uid'])->count();
            //返佣 +
            $brokerage_commission = UserBill::where(['uid' => $item['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
                ->where('add_time', '>', $search_time)
                ->where('pm', 1)
                ->sum('number');
            //退款退的佣金 -
            $refund_commission = UserBill::where(['uid' => $item['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
                ->where('add_time', '>', $search_time)
                ->where('pm', 0)
                ->sum('number');
            $item['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
            if ($item['broken_commission'] < 0)
                $item['broken_commission'] = 0;
            if ($item['brokerage_money'] > $refund_commission)
                $item['brokerage_money'] = bcsub($item['brokerage_money'], $refund_commission, 2);
            else
                $item['brokerage_money'] = 0;
        }
        return compact('list', 'count');
    }

    /**
     * 获取导出数据
     * @param array $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function exportAgentData($where = [])
    {
        //提现数据
        $exteactSql = UserExtract::where(['status' => 1])
            ->group('uid')
            ->field(['sum(extract_price) as extract_count_price', 'count(id) as extract_count_num', 'uid as euid'])
            ->fetchSql(true)
            ->select();
        //订单数据
        $orderSql = StoreOrder::alias('o')
            ->where(['o.paid' => 1, 'o.refund_status' => 0])
            ->field(['sum(o.pay_price) as order_price', 'count(o.id) as order_count', 'o.uid as ouid'])
            ->group('o.uid')
            ->fetchSql(true)
            ->select();
        //佣金数据
        $billSql = UserBill::where(['status' => 1])
            ->where('type', 'brokerage')
            ->where('pm', 1)
            ->group('uid')
            ->field(['sum(number) as brokerage_money', 'uid as buid'])
            ->fetchSql(true)
            ->select();
        $model = User::where(['status' => 1])->where('is_promoter', 1);
        $model = $model->alias('u')
            ->join('(' . $orderSql . ') o', 'o.ouid = u.uid', 'left')
            ->join('(' . $billSql . ') b', 'b.buid = u.uid', 'left')
            ->join('(' . $exteactSql . ') e', 'e.euid = u.uid', 'left');
        if ($where['nickname'] !== '') {
            $model = $model->where("u.nickname|u.uid|u.phone", 'LIKE', "%$where[nickname]%");
        }
        if ($where['data']) $model = self::getModelTime($where, $model, 'u.add_time');
        if ($where['mer_id']) $model = $model->where('u.mer_id', $where['mer_id']);
        $count = $model->count();
        $list = $model->field(['avatar as headimgurl', 'brokerage_price as new_money', 'u.*', 'o.*', 'e.*', 'b.*'])
            ->page((int)$where['page'], (int)$where['limit'])
            ->order('u.uid desc')
            ->select();
        $list = count($list) ? $list->toArray() : [];
        $export = [];
        $broken_time = intval(sys_config('extract_time'));
        $search_time = time() - 86400 * $broken_time;
        foreach ($list as &$item) {
            $item['spread_name'] = '';
            if ($spread_uid = User::where('uid', $item['uid'])->value('spread_uid')) {
                if ($user = User::where('uid', $spread_uid)->field(['uid', 'nickname'])->find()) {
                    $item['spread_name'] = $user['nickname'] . '/' . $user['uid'];
                }
            }
            $item['spread_count'] = User::where('spread_uid', $item['uid'])->count();
            //返佣 +
            $brokerage_commission = UserBill::where(['uid' => $item['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
                ->where('add_time', '>', $search_time)
                ->where('pm', 1)
                ->sum('number');
            //退款退的佣金 -
            $refund_commission = UserBill::where(['uid' => $item['uid'], 'category' => 'now_money', 'type' => 'brokerage'])
                ->where('add_time', '>', $search_time)
                ->where('pm', 0)
                ->sum('number');
            $item['broken_commission'] = bcsub($brokerage_commission, $refund_commission, 2);
            if ($item['broken_commission'] < 0)
                $item['broken_commission'] = 0;
            if ($item['brokerage_money'] > $refund_commission)
                $item['brokerage_money'] = bcsub($item['brokerage_money'], $refund_commission, 2);
            else
                $item['brokerage_money'] = 0;
        }
        return $list;
    }

    public static function setSairOrderWhere($where, $model = null, $alias = '')
    {
        $model = $model === null ? new self() : $model;
        if (!isset($where['uid'])) return $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        if (isset($where['type'])) {
            switch ((int)$where['type']) {
                case 1:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids))
                        $model = $model->where("{$alias}uid", 'in', $uids);
                    else
                        $model = $model->where("{$alias}uid", 0);
                    break;
                case 2:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids))
                        $spread_uid_two = User::where('spread_uid', 'in', $uids)->column('uid');
                    else
                        $spread_uid_two = [0];
                    if (count($spread_uid_two))
                        $model = $model->where("{$alias}uid", 'in', $spread_uid_two);
                    else
                        $model = $model->where("{$alias}uid", 0);
                    break;
                default:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids)) {
                        if ($spread_uid_two = User::where('spread_uid', 'in', $uids)->column('uid')) {
                            $uids = array_merge($uids, $spread_uid_two);
                            $uids = array_unique($uids);
                            $uids = array_merge($uids);
                        }
                        $model = $model->where("{$alias}uid", 'in', $uids);
                    } else
                        $model = $model->where("{$alias}uid", 0);
                    break;
            }
        }
        if (isset($where['data']) && $where['data']) $model = self::getModelTime($where, $model, "{$alias}add_time");
        return $model->where("{$alias}is_del", 0)->where("{$alias}is_system_del", 0)->where($alias . 'paid', 1);
    }

    /*
    *  推广订单统计
    * @param array $where
    * @return array
    * */
    public static function getStairOrderBadge($where)
    {
        if (!isset($where['uid'])) return [];
        $data['order_count'] = self::setSairOrderWhere($where, new StoreOrder())->count();
        $data['order_price'] = self::setSairOrderWhere($where, new StoreOrder())->sum('pay_price');
        $ids = self::setSairOrderWhere($where, new StoreOrder())->where(['paid' => 1, 'is_del' => 0, 'refund_status' => 0])->where('status', '>', 1)->column('id');
        $data['number_price'] = 0;
        if (count($ids)) $data['number_price'] = UserBill::where(['category' => 'now_money', 'type' => 'brokerage', 'uid' => $where['uid']])->where('link_id', 'in', $ids)->sum('number');
        $where['type'] = 1;
        $data['one_price'] = self::setSairOrderWhere($where, new StoreOrder())->sum('pay_price');
        $data['one_count'] = self::setSairOrderWhere($where, new StoreOrder())->count();
        $where['type'] = 2;
        $data['two_price'] = self::setSairOrderWhere($where, new StoreOrder())->sum('pay_price');
        $data['two_count'] = self::setSairOrderWhere($where, new StoreOrder())->count();
        return [
            [
                'name' => '总金额(元)',
                'count' => $data['order_price'],
                'col' => 6,
            ],
            [
                'name' => '订单总数(单)',
                'count' => $data['order_count'],
                'col' => 6,
            ],
            [
                'name' => '返佣总金额(元)',
                'count' => $data['number_price'],
                'col' => 6,
            ],
            [
                'name' => '一级总金额(元)',
                'count' => $data['one_price'],
                'col' => 6,
            ],
            [
                'name' => '一级订单数(单)',
                'count' => $data['one_count'],
                'col' => 6,
            ],
            [
                'name' => '二级总金额(元)',
                'count' => $data['two_price'],
                'col' => 6,
            ],
            [
                'name' => '二级订单数(单)',
                'count' => $data['two_count'],
                'col' => 6,
            ],
        ];
    }

    /**
     * 设置查询条件
     * @param array $where
     * @param object $model
     * @param string $alias
     *
     * @return WechatUser|object|null
     */
    public static function setSairWhere($where, $model = null, $alias = '')
    {
        $model = $model === null ? new self() : $model;
        if (!isset($where['uid'])) return $model;
        if ($alias) {
            $model = $model->alias($alias);
            $alias .= '.';
        }
        if (isset($where['type'])) {
            switch ((int)$where['type']) {
                case 1:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids))
                        $model = $model->where("{$alias}uid", 'in', $uids);
                    else
                        $model = $model->where("{$alias}uid", 0);
                    break;
                case 2:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids))
                        $spread_uid_two = User::where('spread_uid', 'in', $uids)->column('uid');
                    else
                        $spread_uid_two = [0];
                    if (count($spread_uid_two))
                        $model = $model->where("{$alias}uid", 'in', $spread_uid_two);
                    else
                        $model = $model->where("{$alias}uid", 0);
                    break;
                default:
                    $uids = User::where('spread_uid', $where['uid'])->column('uid');
                    if (count($uids)) {
                        if ($spread_uid_two = User::where('spread_uid', 'in', $uids)->column('uid')) {
                            $uids = array_merge($uids, $spread_uid_two);
                            $uids = array_unique($uids);
                            $uids = array_merge($uids);
                        }
                        $model = $model->where("{$alias}uid", 'in', $uids);
                    } else
                        $model = $model->where("{$alias}uid", 0);
                    break;
            }
        }
        if (isset($where['data']) && $where['data']) $model = self::getModelTime($where, $model, "{$alias}add_time");
        if (isset($where['nickname']) && $where['nickname']) $model = $model->where("{$alias}phone|{$alias}nickname|{$alias}real_name|{$alias}uid", 'LIKE', "%$where[nickname]%");
        return $model->where($alias . 'status', 1);
    }

    public static function getSairBadge($where)
    {
        $data['number'] = self::setSairWhere($where, new User())->count();
        $where['type'] = 1;
        $data['one_number'] = self::setSairWhere($where, new User())->count();
        $where['type'] = 2;
        $data['two_number'] = self::setSairWhere($where, new User())->count();
        $col = $data['two_number'] > 0 ? 4 : 6;
        return [
            [
                'name' => '总人数(人)',
                'count' => $data['number'],
                'col' => $col,
            ],
            [
                'name' => '一级人数(人)',
                'count' => $data['one_number'],
                'col' => $col,
            ],
            [
                'name' => '二级人数(人)',
                'count' => $data['two_number'],
                'col' => $col,
            ],
        ];
    }

    public static function getStairList($where)
    {
        if (!isset($where['uid'])) return [];
        $data = self::setSairWhere($where, new User())->page((int)$where['page'], (int)$where['limit'])->select();
        $data = count($data) ? $data->toArray() : [];
        $userInfo = User::where('uid', $where['uid'])->find();
        foreach ($data as &$item) {
            $item['spread_count'] = User::where('spread_uid', $item['uid'])->count();
            $item['order_count'] = StoreOrder::where('uid', $item['uid'])->where(['paid' => 1, 'is_del' => 0])->count();
            $item['promoter_name'] = $item['is_promoter'] ? '是' : '否';
            $item['add_time'] = date("Y-m-d H:i:s", $item['add_time']);
        }
        $count = self::setSairWhere($where, new User())->count();
        return ['count' => $count, 'list' => $data];
    }

    /*
    * 推广订单
    * @param array $where
    * @return array
    * */
    public static function getStairOrderList($where)
    {
        if (!isset($where['uid'])) return [];
        $data = self::setSairOrderWhere($where, new StoreOrder())->page((int)$where['page'], (int)$where['limit'])->select();
        $data = count($data) ? $data->toArray() : [];
        $Info = User::where('uid', $where['uid'])->find();
        foreach ($data as &$item) {
            $userInfo = User::where('uid', $item['uid'])->find();
            $item['user_info'] = '';
            $item['avatar'] = '';
            if (count($userInfo->toArray())) {
                $item['user_info'] = $userInfo->nickname . '|' . ($userInfo->phone ? $userInfo->phone . '|' : '') . $userInfo->real_name;
                $item['avatar'] = $userInfo->avatar;
            }
            if (count($Info->toArray()))
                $item['spread_info'] = $Info->nickname . "|" . ($Info->phone ? $Info->phone . "|" : '') . $Info->uid;
            else
                $item['spread_info'] = '';
            $item['number_price'] = UserBill::where(['category' => 'now_money', 'type' => 'brokerage', 'link_id' => $item['id']])->value('number');
            $item['_pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
            $item['_add_time'] = date('Y-m-d H:i:s', $item['add_time']);
            $item['take_time'] = ($change_time = StoreOrderStatus::where(['change_type' => 'user_take_delivery', 'oid' => $item['id']])->value('change_time')) ?
                date('Y-m-d H:i:s', $change_time) : '暂无';
        }
        $count = self::setSairOrderWhere($where, new StoreOrder())->count();
        return ['count' => $count, 'list' => $data];
    }

    /**
     * @param $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getSpreadBadge($where)
    {
        $model = self::alias('a')->join('user u', 'a.uid = u.uid')->order('u.uid desc')->where('u.is_promoter', 1);
        if ($where) {
            if (isset($where['mer_id']) && $where['mer_id']) {
                $model = $model->where('u.mer_id', $where['mer_id']);
            }
            if (isset($where['data']) && $where['data'])
                $model = self::getModelTime($where, $model, 'a.add_time');
            if (isset($where['nickname']) && $where['nickname']) {
                $model = $model->where('u.nickname|a.uid|u.phone', 'like', "%$where[nickname]%");
            }
        }
        $uids = $model->column('u.uid');
        //分销员人数
        $data['sum_count'] = count($uids);
        $data['spread_sum'] = 0;
        $data['order_count'] = 0;
        $data['pay_price'] = 0;
        $data['number'] = 0;
        $data['extract_count'] = 0;
        $data['extract_price'] = 0;
        if ($data['sum_count']) {
            //发展会员人数
            $data['spread_sum'] = User::where('spread_uid', 'in', $uids)->count();
            //订单总数
            $data['order_count'] = StoreOrder::where('uid', 'in', $uids)->where(['paid' => 1, 'refund_status' => 0])->count();
            //订单金额
            $data['pay_price'] = StoreOrder::where('uid', 'in', $uids)->where(['paid' => 1, 'refund_status' => 0])->sum('pay_price');
            //可提现金额
            $data['number'] = User::where('uid', 'in', $uids)->sum('brokerage_price');
            //提现次数
            $data['extract_count'] = UserExtract::where('uid', 'in', $uids)->count();
            //获取某个用户可提现金额
            $data['extract_price'] = User::getextractPrice($uids, $where);
        }
        return [
            [
                'name' => '分销员人数(人)',
                'count' => $data['sum_count'],
                'className' => 'md-contacts',
                'col' => 6,
            ],
            [
                'name' => '发展会员人数(人)',
                'count' => $data['spread_sum'],
                'className' => 'md-contact',
                'col' => 6,
            ],
            [
                'name' => '分销订单数(单)',
                'count' => $data['order_count'],
                'className' => 'md-cart',
                'col' => 6,
            ],
            [
                'name' => '订单金额(元)',
                'count' => $data['pay_price'],
                'className' => 'md-bug',
                'col' => 6,
            ],
            [
                'name' => '提现金额(元)',
                'count' => $data['number'],
                'className' => 'ios-beaker',
                'col' => 6,
            ],
            [
                'name' => '提现次数(次)',
                'count' => $data['extract_count'],
                'className' => 'md-basket',
                'col' => 6,
            ],
            [
                'name' => '未提现金额(元)',
                'count' => $data['extract_price'],
                'className' => 'ios-at-outline',
                'col' => 6,
            ],
        ];
    }

    /**
     * 获取筛选后的所有用户uid
     * @param array $where
     * @return array
     */
    public static function getAll($where = array())
    {
        $model = new self;
        if ($where['nickname'] !== '') $model = $model->where('nickname', 'LIKE', "%$where[nickname]%");
//        if ($where['data'] !== '') {
//            list($startTime, $endTime) = explode(' - ', $where['data']);
//            $model = $model->where('add_time', '>', strtotime($startTime));
//            $model = $model->where('add_time', '<', strtotime($endTime));
//        }
        $model = self::getModelTime($where, $model, "add_time");
        if ($where['tagid_list'] !== '') {
            $model = $model->where('tagid_list', 'LIKE', "%$where[tagid_list]%");
        }
        if ($where['groupid'] !== '-1') $model = $model->where('groupid', "$where[groupid]");
        if ($where['sex'] !== '') $model = $model->where('sex', "$where[sex]");
        return $model->column('uid', 'uid');
    }

    /**
     * 获取已关注的用户
     * @param $field
     */
    public static function getSubscribe($field)
    {
        return self::where('subscribe', 1)->column($field);
    }

    public static function getUserAll($field)
    {
        return self::column($field);
    }

    public static function getUserTag()
    {
        $tagName = Config::get('system_wechat_tag');
        return Cache::tag($tagName)->remember('_wechat_tag', function () use ($tagName) {
            Cache::tag($tagName, ['_wechat_tag']);
            $tag = WechatService::userTagService()->lists()->toArray()['tags'] ?: array();
            $list = [];
            foreach ($tag as $g) {
                $list[] = $g;
            }
            return $list;
        });
    }

    public static function clearUserTag()
    {
        Cache::delete('_wechat_tag');
    }

    public static function getUserGroup()
    {
        $tagName = Config::get('system_wechat_tag');
        return Cache::tag($tagName)->remember('_wechat_group', function () use ($tagName) {
            Cache::tag($tagName, ['_wechat_group']);
            $tag = WechatService::userGroupService()->lists()->toArray()['groups'] ?: array();
            $list = [];
            foreach ($tag as $g) {
                $list[] = $g;
            }
            return $list;
        });
    }

    public static function clearUserGroup()
    {
        Cache::delete('_wechat_group');
    }

    /**
     * 获取推广人数
     * @param $uid //用户的uid
     * @param int $spread
     * $spread 0 一级推广人数  1 二级推广人数
     * @return int|string
     */
    public static function getUserSpreadUidCount($uid, $spread = 1)
    {
        $userStair = User::where('spread_uid', $uid)->column('uid', 'uid');//获取一级推家人
        if ($userStair) {
            if (!$spread) return count($userStair);//返回一级推人人数
            else return User::where('spread_uid', 'IN', implode(',', $userStair))->count();//二级推荐人数
        } else return 0;
    }

    /**
     * 获取推广人的订单
     * @param $uid
     * @param int $spread
     * $spread 0 一级推广总订单  1 所有推广总订单
     * @return int|string
     */
    public static function getUserSpreadOrderCount($uid, $spread = 1)
    {
        $userStair = User::where('spread_uid', $uid)->column('uid', 'uid');//获取一级推家人uid
        if ($userStair) {
            if (!$spread) {
                return StoreOrder::where('uid', 'IN', implode(',', $userStair))->where('paid', 1)->where('refund_status', 0)->where('status', 2)->count();//获取一级推广人订单数
            } else {
                $userSecond = User::where('spread_uid', 'IN', implode(',', $userStair))->column('uid', 'uid');//二级推广人的uid
                if ($userSecond) {
                    return StoreOrder::where('uid', 'IN', implode(',', $userSecond))->where('paid', 1)->where('refund_status', 0)->where('status', 2)->count();//获取二级推广人订单数
                } else return 0;
            }
        } else return 0;
    }

}