<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\admin\controller\bbfxshop\fenxiao;

use app\admin\controller\bbfxshop\Base;
use think\Db;
use app\common\model\bbfxshop\User as UserMode;
use app\common\model\bbfxshop\Order;
use app\common\model\bbfxshop\FenxiaoUser;

class User extends Base
{
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Fenxiao;
    }

    public function clearCommission(){
        $user_id = $this->param("user_id/d");

        $where = ['uniacid'=>UNIACID,'commission_ok'=>['>',0]];
        if($user_id > 0){
            $where['id'] = $user_id;
        }

        $list = Db::name("bbfx_user")->where($where)->field("id,commission_ok")->select();

        if(!empty($list)){
            foreach($list as $key => $user){
                try {
                    \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($user['id'],-$user['commission_ok'],0,"后台清零");
                } catch (\Exception $e) {
                    //throw $th;
                }
            }
            $ids = array_column($list,'id');
            \app\admin\model\AdminLog::record("用户佣金清零","用户ID：".implode(",",$ids),$list);
        }

        __success("操作成功");
    }
    
    public function setCommission(){
        $type = $this->param("type/d");
        $user_id = $this->param("user_id/d");
        $notes = $this->param("notes/s");
        $money = $this->param("money/f");
        $money = round($money,2);
        $money = abs($money);
        if($type == 1){
            $money = 0 - $money;
        }
        $info = ['notes'=>$notes,'admin_id'=>$this->auth->id,'admin_username'=>$this->auth->username];
        
        if($money == 0){
            __error("请输入佣金");
        }
        
        $res = \app\common\model\bbfxshop\FenxiaoJiesuan::setUserCommission($user_id,$money,0,"后台充值",$info);
        if($res){

            \app\admin\model\AdminLog::record("佣金充值","用户ID：".$user_id."，佣金：".$money,['notes'=>$notes]);

            __success("操作成功");
        }
        else{
            __error("充值失败");
        }
    }
    
    public function all(){
        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'is_distributor'=>1,'distributor_status'=>1])->field(['id','level','avatar','nickname'])->order("id asc")->select();
        foreach ($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
        }
        unset($val);
        
        __success("操作成功",$list);
    }

    public function initTree($id,$user_list){
        $list = $user_list[$id] ?? [];

        if(!empty($list)){
            foreach($list as $key => &$val){
                $val['children'] = $this->initTree($val['id'],$user_list);
            }
            unset($val);
        }

        return $list;
    }

    public function tree(){
        $params = $this->param();
        $type = intval($params['type']);
        $uid = intval($params['uid']);
        if($uid <= 0){
            __error("请输入会员ID");
        }

        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$uid])->field('id,sup_uid,level,avatar,nickname,is_distributor,distributor_status')->select();
        if(empty($list)){
            __error("会员不存在");
        }
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
        $where = ['uniacid'=>UNIACID];
        if($type == 2){
            $where['o_sup_path'] = ['like','%-'.$uid.'-%'];
            $field = 'id,first_sup_uid,sup_uid,level,avatar,nickname,is_distributor,distributor_status';
        }
        else{
            $field = 'id,sup_uid,first_sup_uid,level,avatar,nickname,is_distributor,distributor_status';
            $where['sup_path'] = ['like','%-'.$uid.'-%'];
        }



        $user_all = Db::name("bbfx_user")->where($where)->field($field)->order("become_distributor_time asc")->select();
        if(!empty($user_all)){
            $user_list = [];

           if(empty($user_all)) $user_all = [];
            $uids = array_column($user_all,"id");

            foreach($user_all as $key => $val){
                if($type == 2){
                    $sup_uid = $val['sup_uid'];
                    if($val['first_sup_uid'] > 0){
                        $sup_uid = $val['first_sup_uid'];
                    }
                }
                else{
                    $sup_uid = $val['sup_uid'];
                }

                if($sup_uid > 0 && !in_array($sup_uid,$uids) && $sup_uid != $uid){
                    $sup_uid = 0;
                }
                
                if(empty($user_list[$sup_uid])){
                    $user_list[$sup_uid] = [];
                }
                
                $val['avatar'] = cdnurl($val['avatar']);
                $val['name'] = $val['nickname']."\r\n";
                if($val['is_distributor'] != 1 || $val['distributor_status'] != 1 || empty($levels[$val['level']])){
                    $val['name'] .= "普通用户";
                }
                else{
                    $val['name'] .= $levels[$val['level']]['title'];
                }
                $val['name'] .= '(ID:'.$val['id'].')';

                $val['sup_uid'] = $sup_uid;

                $user_list[$sup_uid][] = $val;
            }
        }

        foreach($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
            
            $val['name'] = $val['nickname']."\r\n";
            if($val['is_distributor'] != 1 || $val['distributor_status'] != 1 || empty($levels[$val['level']])){
                $val['name'] .= "普通用户";
            }
            else{
                $val['name'] .= $levels[$val['level']]['title'];
            }
            $val['name'] .= '(ID:'.$val['id'].')';

            $children = $this->initTree($val['id'],$user_list);
            
            if(!empty($children)){
                $val['children'] = $children;
            }
        }
        unset($val);
        


        /*
        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'id'=>$uid])->field(['id','sup_uid','level','avatar','nickname','is_distributor','distributor_status'])->order("become_distributor_time asc")->select();
        
        if(empty($list)){
            __error("会员不存在");
        }
        
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
        foreach($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
            
            $val['name'] = $val['nickname']."\r\n";
            if($val['is_distributor'] != 1 || $val['distributor_status'] != 1 || empty($levels[$val['level']])){
                $val['name'] .= "普通用户";
            }
            else{
                $val['name'] .= $levels[$val['level']]['title'];
            }
            
            $children = $this->getDownUser($val['id'],$levels);
            // $val['name'] .= '(ID:'.$val['id'].' 团队:'.count($children).'人)';
            $val['name'] .= '(ID:'.$val['id'].')';
            
            if(!empty($children)){
                $val['children'] = $children;
            }
        }
        unset($val);
        */
        
        __success("操作成功",['list'=>$list]);
    }
    
    protected function getDownUser($uid,$levels=[]){
        $params = $this->param();
        
        
        $list = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'sup_uid'=>$uid])->field(['id','sup_uid','level','avatar','nickname','is_distributor','distributor_status'])->order("become_distributor_time asc,createtime asc")->select();
        
        if(empty($list)){
            return [];
        }
        
        if(empty($levels)){
            $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
        }
        
        foreach($list as $key => &$val){
            $val['avatar'] = cdnurl($val['avatar']);
            
            $val['name'] = $val['nickname']."\r\n";
            
            if($val['is_distributor'] != 1 || $val['distributor_status'] != 1 || empty($levels[$val['level']])){
                $val['name'] .= "普通会员";
            }
            else{
                $val['name'] .= $levels[$val['level']]['title'];
            }
            
            $children = $this->getDownUser($val['id'],$levels);
            $val['name'] .= '(ID:'.$val['id'].' 下级:'.count($children).'人)';
            
            if(!empty($children)){
                $val['children'] = $children;
            }
        }
        unset($val);
        
        return $list;
    }

    public function statistics(){
        $params = $this->param();
        
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
        }
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
        }
        
        $where = ['uniacid'=>UNIACID,'status'=>1,'user_id'=>['>',0],'money'=>['>',0],'money_type'=>['in',[1,3]]];
	    if($startTime && $endTime){
	        $where['createtime'] = ['between',[$startTime,$endTime]];
	        $where1['createtime'] = ['between',[$startTime,$endTime]];
	    }

	    
	    $commission_total = Db::name("bbfx_fenxiao_order")->where($where)->sum('money');
	    $commission_ok_history = Db::name("bbfx_fenxiao_order")->where($where)->where(['is_daozhang'=>1])->sum('money');
	    $commission_ok = Db::name("bbfx_user")->where(['uniacid'=>UNIACID])->sum('commission_ok');
	    
	    
	    __success("操作成功",['commission_total'=>round($commission_total,2),'commission_ok_history'=>round($commission_ok_history,2),'commission_ok'=>round($commission_ok,2)]);
    }

    public function detail(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        $id = $this->param("id/d");
        
        $user = Db::name("bbfx_user")->where(["id"=>$id])->find();
        if(!empty($user)){


            $user['password'] = "";
            $user['pay_password'] = "";
            $user['avatar'] = cdnurl($user['avatar']);

            if(!empty($user['ip_gs'])) $user['ip_gs'] = iunserializer($user['ip_gs']);

            $agent_user_log = Db::name("bbfx_agent_log")->where(['uniacid'=>UNIACID,'user_id'=>$user['id'],'level'=>$user['agent_level']])->select();
            $user['region'] = $agent_user_log;


            

            $navItems = \app\common\model\bbfxshop\FenxiaoTongji::getRewardList($user['id'],true);
             
            foreach($navItems as $key => &$val){
                if(!empty($val['a_link'])){
                    if(strstr($val['a_link'], '?')){
                        $val['a_link'] .= "&user_id=".$user['id'];
                    }
                    else{
                        $val['a_link'] .= "?user_id=".$user['id'];
                    }
                }
            }   
            unset($val);
            
            $result['navItems'] = $navItems;
            $result['user'] = $user;
            __success("操作成功",$result);
        }
        else{
            __error("用户不存在");
        }
        
    }
    
    public function list(){
        global $_W;
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        
        $where = array('is_distributor'=>1,"uniacid"=>UNIACID,);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $level = trim($params['level']);
        $export = trim($params['export']);
        $type = max(1,intval($params['type']));
        $abonus_level = intval($params['abonus_level']);
        $tx_type = intval($params['tx_type']);
        
        if($keyword){
            if($type == 1){
                $where['nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['mobile'] = $keyword;
            }
            else if($type == 4){
                $where['id'] = intval($keyword);
            }
            else if($type == 5){
                // $uids = UserMode::getLevel1UserIds(intval($keyword));
                // $where['id'] = ['in',$uids];
                $where['sup_uid'] = intval($keyword);
            }
        }
        if($tx_type == 1){
            $where['commission_ok'] = ['>',0];
        }
        else if($tx_type == 2){
            $where['commission_ok'] = 0;
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
        }
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
        }
        
        if($level != ''){
            $where['level'] = $level;
        }
        
        if($abonus_level > 0 && $_W['fenxiao']['abonus_rule'] == 2){
            
            $rule_user = Db::name("bbfx_fenxiao_abonus_item")->alias("a")->join("bbfx_fenxiao_abonus_rule b","a.rule_id=b.id")->where(['a.uniacid'=>UNIACID,'a.rule_id'=>$abonus_level,'a.status'=>0])->order('b.single_purchase_money desc')->group("a.user_id")->select();
            
            $uids = [];
            foreach ($rule_user as $key => $val){
                $uids[] = $val['user_id'];
            }
            $where['id'] = ['in',$uids];
        }
        
        $set = $_W['base'];
        
        
        
        if($export == 1){
            $list = Db::name("bbfx_user")->where($where)->field('id,sup_uid,sup_path,avatar,nickname,level,createtime,become_distributor_time,upgrade_distributor_time,commission_ok,commission_total,sup_uid,realname,distributor_status')->order('createtime desc')->select();
        }
        else{
            $list = Db::name("bbfx_user")->where($where)->field('id,sup_uid,sup_path,avatar,nickname,level,createtime,become_distributor_time,upgrade_distributor_time,commission_ok,commission_total,sup_uid,realname,distributor_status')->order('createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
        }

        $level1_users = [];
        $level1_uids = [];
        $sup_users = [];
        $commissions = [];
        $commission_totals = [];
        if(!empty($list)){
            if(empty($list)) $list = [];
            $uids = array_column($list,"id");
            $sup_uids = array_column($list,"sup_uid");
            $uwhere = ['uniacid'=>UNIACID,'sup_uid'=>['in',$uids]];
            if($set['fenxiao']['team_tongji'] == 1){
                $uwhere['distributor_status'] = 1;
                $uwhere['is_distributor'] = 1;
            }
            $level1_user_all = Db::name("bbfx_user")->where($uwhere)->field("id,sup_uid")->select();
            if(!empty($level1_user_all)){
                foreach ($level1_user_all as $val){
                    if(empty($level1_users[$val['sup_uid']])){
                        $level1_users[$val['sup_uid']] = 0;
                        $level1_uids[$val['sup_uid']] = [];
                    }
                    $level1_users[$val['sup_uid']]++;
                    $level1_uids[$val['sup_uid']][] = $val['id'];
                }
            }
            $sup_user_all = Db::name("bbfx_user")->where(['id'=>['in',$sup_uids]])->field('id,nickname,realname,avatar')->select();
            if(!empty($sup_user_all)){
                foreach ($sup_user_all as $val){
                    $val['avatar'] = cdnurl($val['avatar']);
                    $sup_users[$val['id']] = $val;
                }
            }
            
            $commission_all = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'money_type'=>['in',[1,3]],'user_id'=>['in',$uids],'type'=>['in',[1,2,3]]])->field("user_id,sum(money) as money")->group("user_id")->select();
            if(!empty($commission_all)){
                foreach ($commission_all as $val){
                    $commissions[$val['user_id']] = $val['money'];
                }
            }
            $cwhere = ['uniacid'=>UNIACID,'type'=>['not in',[20,21]],'money'=>['>',0],'user_id'=>['in',$uids]];
            if($startTime && $endTime){
    	        $cwhere['createtime'] = ['between',[$startTime,$endTime]];
    	    }
            $commission_total_all = Db::name("bbfx_fenxiao_order")->where($cwhere)->field("user_id,sum(money) as money")->group("user_id")->select();
            if(!empty($commission_total_all)){
                foreach ($commission_total_all as $val){
                    $commission_totals[$val['user_id']] = $val['money'];
                }
            }
        }
        
    	$levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
    	foreach($list as $key=>&$val){
    	    
    	    if($_W['fenxiao']['abonus_rule'] == 2){
    	        $abonus_level = "";
                $rule = Db::name("bbfx_fenxiao_abonus_item")->alias("a")->join("bbfx_fenxiao_abonus_rule b","a.rule_id=b.id")->where(['a.uniacid'=>UNIACID,'a.user_id'=>$val['id']])->field("b.*")->order('b.single_purchase_money desc')->select();  
                if(!empty($rule)){
                    $abonus_level = $rule['name'];
                }
                $val['abonus_level'] = $abonus_level;
    	    }
    	    $val['levelname'] = $levels[$val['level']]['title'];
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y.m.d H:i",$val['createtime']);
    	    if(empty($val['become_distributor_time'])){
    	        $val['become_distributor_time'] = $val['upgrade_distributor_time'];
    	    }
    	    $val['become_distributor_time'] = date("Y.m.d H:i",$val['become_distributor_time']);
    	    
    	    $alldown = FenxiaoUser::getAllDown($val['id']);
            
            if($set['fenxiao']['selfbuy_achievement'] == 1){
                $uids = [$val['id']];
            }
            else{
                $uids = [];
            }
            
            if(!empty($alldown['ids'])){
                $uids = array_merge($uids,$alldown['ids']);
                $val['team_user'] = count($alldown['ids']);
            }
            else{
                $val['team_user'] = 0;
            }
    	    
    	    $team_achievement = $this->model->getTeamAchievement($uids,$startTime,$endTime,$val['id']);

            $level1_uid = $level1_uids[$val['id']];
            if(empty($level1_uid)){
                $level1_uid = [-1];
            }
            $level1_achievement = Order::getAchievement(['o.user_id'=>['in',$level1_uid],'o.status'=>['in',[1,2,3]]]);
    	    
    	    $val['level1_achievement'] = $level1_achievement;
    	    $val['team_achievement'] = $team_achievement;
    	    $val['level1_user'] = intval($level1_users[$val['id']]);
    	    
    	    if($val['sup_uid']){
                $sup_user = $sup_users[$val['sup_uid']];
    	        if(!empty($sup_user)){
    	            $val['sup_user'] = $sup_user;
    	        }
    	    }
    	    
    	    $val['commission'] = round($commissions[$val['id']],2);
    	    $val['commission_ok'] = round($val['commission_ok'],2);
    	    $val['commission_total'] = round($commission_totals[$val['id']],2);
    	    
    	    if($export == 1){
    	        $sup_user = "总店";
    	        if(!empty($val['sup_user'])){
    	            $sup_user = "(ID:{$val['sup_uid']})".$val['sup_user']['nickname'];
    	        }
    	        
    	        $export_list[] = array(
    	            $val['id'],
    	            $val['nickname'],
    	            $val['levelname'],
    	            $sup_user,
    	            $val['commission_total'],
    	            $val['commission_ok'],
    	            $val['commission'],
    	            $val['team_achievement'],
    	            $val['level1_user'],
    	            $val['team_user'],
    	            $val['become_distributor_time']
    	        );
    	    }
    	}
    	unset($val);
    	
    	if($export == 1){
    	    $headArr = ["用户ID","用户昵称","分销等级","上级用户","累计佣金","可提现佣金","分销佣金","团队业绩","直推团队","所有团队","成为分销商时间"];
    	    $result = \app\common\model\PhpOffice::excelExport("user-".date("Y-m-d"),$headArr,$export_list,[]);
    	}
    	
        $total = Db::name("bbfx_user")->where($where)->count();
        
    	__success("操作成功",['total'=>$total,'list'=>$list]);
      
    }
    
    public function getTeamAchievement(){
        global $_W;
        $params = $this->param();
        
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        
        $where = array("a.uniacid"=>UNIACID);
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        $status = intval($params['status']);
        $user_id = intval($params['user_id']);
        $level = intval($params['level']);
        $refund_status = intval($params['refund_status']);
        $type = intval($params['type']);
        
        
        $where['a.status'] = ['in',[1,2,3]];
        $where['a.refund_status'] = -1;
        
        if($keyword){
            if($type == 1){
                $where['a.order_no'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $where['b.nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $where['a.delivery_username'] = ['like',"%".$keyword."%"];
            }
            else if($type == 4){
                $where['a.user_id'] = intval($keyword);
            }
        }
        
        $whereTime = [];
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
            $where['a.createtime'] = ['>=',$startTime];
        } 
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
            $whereTime['a.createtime'] = ['<=',$endTime];
        }
        
        if($level == 1){
            $level1_users = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'sup_uid'=>$user_id])->field("id")->select();
    	    $uids = array_column($level1_users, 'id');
        }
        else{
            $alldown = FenxiaoUser::getAllDown($user_id);
            $set = $_W['base'];    
            if($set['fenxiao']['selfbuy_achievement'] == 1){
                $uids = [$user_id];
            }
            else{
                $uids = [];
            }
            if(!empty($alldown['ids'])){
                $uids = array_merge($uids,$alldown['ids']);
            }
        }
        
        $where['a.user_id'] = ['in',$uids];
        
        $list = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->field('a.*,b.avatar,b.nickname')->order('a.createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	
    	foreach($list as $key => &$val){
    	    $val['avatar'] = cdnurl($val['avatar']);
            $order_goods = Db::name("bbfx_order_goods")->where(["uniacid"=>UNIACID,"order_id"=>$val['id']])->select();
    	    $category_name = "";
    	    foreach ($order_goods as $k => &$v){
    	        $goods_info = iunserializer($v['goods_info']);
    	        $goods_info['thumb'] = cdnurl($goods_info['thumb']);
    	        
    	        if($k == 0){
    	            $category_name = Db::name("bbfx_category")->alias("a")->join("bbfx_goods_category b","a.id=b.category_id")->where(['a.uniacid'=>UNIACID,'b.goods_id'=>$goods_info['id']])->value("title");
    	        }
    	        
    	        $v['goods'] = $goods_info;
    	    }
    	    unset($v);
    	    $val['category_name'] = $category_name;
    	    $val['order_goods'] = $order_goods;
    	    
    	    if($val['is_pay'] == 1){
    	        $val['pay_time'] = date("Y-m-d H:i:s",$val['pay_time']);
    	    }
    	    else{
    	        $val['pay_time'] = "";
    	    }
    	    
    	    $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
    	    
    	    $val['typeText'] = Order::getOrderType($val['order_type']);
    	    $val['refund_statusText'] = Order::getOrderRefundStatus($val['refund_status']);
    	    $val['statusText'] = Order::getOrderStatus($val);
            
            $sup_user = Db::name('bbfx_user')->where(['id'=>$val['one_share']])->field("id,nickname,avatar")->find();
    	    if(!empty($sup_user)){
    	        $sup_user['avatar'] = cdnurl($sup_user['avatar']);
    	        $val['sup_user'] = $sup_user;
    	    }
            
    	}
    	unset($val);
    	
      
        $total = Db::name("bbfx_order")->alias("a")->join("bbfx_user b","a.user_id=b.id")->where($where)->where($whereTime)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
    }
    
    public function team(){
        global $_W;
        $params = $this->param();
        
        $pindex = max(1, intval($params["page"]));
        $psize = intval($params["limit"])?intval($params["limit"]):10;
        $level = intval($params['level']);
        $user_id = intval($params['user_id']);
        
        
        $where = array("uniacid"=>UNIACID);
        if($level == 1){
            $where['sup_uid'] = $user_id;
        }
        else{
            $alldown = FenxiaoUser::getAllDown($user_id);
            $uids = $alldown['ids'];
            $where['id'] = ['in',$uids];
        }
        
        $keyword = trim($params['keyword']);
        $startTime = trim($params['startTime']);
        $endTime = trim($params['endTime']);
        
        $type = max(1,intval($params['type']));
        if(!empty($keyword)){
            
            if($type == 1){
                $params['nickname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 2){
                $params['realname'] = ['like',"%".$keyword."%"];
            }
            else if($type == 3){
                $params['mobile'] = $keyword;
            }
            else if($type == 4){
                $params['id'] = intval($keyword);
            }
        }
        
        if($startTime){
            $startTime = strtotime($startTime." 00:00:00");
        }
        
        if($endTime){
            $endTime = strtotime($endTime." 23:59:59");
        }
        
        
        $set = $_W['base'];

        if($set['fenxiao']['team_tongji'] == 1){
            $where['is_distributor'] = 1;
            $where['distributor_status'] = 1;
        }
        
        $list = Db::name("bbfx_user")->where($where)->field('id,sup_uid,sup_path,is_distributor,distributor_status,avatar,nickname,level,createtime,become_distributor_time,upgrade_distributor_time,commission_ok,commission_total,sup_uid,realname')->order('createtime desc')->limit(($pindex - 1) * $psize,$psize)->select();
    	
    	
    	$levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels(1);
    	foreach($list as $key=>&$val){
    	    $val['levelname'] = $levels[$val['level']]['title'];
    	    $val['avatar'] = cdnurl($val['avatar']);
    	    $val['createtime'] = date("Y.m.d H:i",$val['createtime']);
    	    $val['commission_total'] = round($val['commission_total'],2);
    	    $val['commission_ok'] = round($val['commission_ok'],2);
    	    if(empty($val['become_distributor_time'])){
    	        $val['become_distributor_time'] = $val['upgrade_distributor_time'];
    	    }
    	    $val['become_distributor_time'] = date("Y.m.d H:i",$val['become_distributor_time']);
    	    
    	    
    	    $alldown = FenxiaoUser::getAllDown($val['id']);
            if($set['fenxiao']['selfbuy_achievement'] == 1){
                $uids = [$val['id']];
            }
            else{
                $uids = [];
            }
            if(!empty($alldown['ids'])){
                $uids = array_merge($uids,$alldown['ids']);
                $val['team_user'] = count($alldown['ids']);
            }
            else{
                $val['team_user'] = 0;
            }
    	    
    	    $team_achievement = $this->model->getTeamAchievement($uids,$startTime,$endTime,$val['id']);
            $level1_user = Db::name("bbfx_user")->where(['uniacid'=>UNIACID,'sup_uid'=>$val['id']])->count();
    	    $level1_user = intval($level1_user);
    	    
    	    
    	    $val['team_achievement'] = $team_achievement;
    	    $val['level1_user'] = $level1_user;
    	    
    	    if($val['sup_uid']){
    	        $user = Db::name("bbfx_user")->where(['id'=>$val['sup_uid']])->field(['id','avatar','nickname','realname'])->find();
    	        if(!empty($user)){
    	            $user['avatar'] = cdnurl($user['avatar']);
    	            $val['sup_user'] = $user;
    	        }
    	    }
    	    
    	    $commission = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'money_type'=>['in',[1,3]],'user_id'=>$val['id'],'type'=>['in',[1,2,3]]])->sum('money');
    	    $val['commission'] = round($commission,2);
    	    
    	    if($val['is_distributor'] != 1 || $val['distributor_status'] != 1){
    	        $val['levelname'] = "普通用户";
    	        $val['become_distributor_time'] = "";
    	        $val['commission_total'] = 0;
    	        $val['commission'] = 0;
    	        $val['team_user'] = 0;
    	        $val['level1_user'] = 0;
    	        $val['team_achievement'] = 0;
    	    }
    	    
    	    if($set['fenxiao']['is_jicha'] == 1){
    	        $jc_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>4])->sum('money');
    	        $val['jc_reward'] = round($jc_reward,2);
    	    }
    	    
    	    if($set['fenxiao']['is_jiandan'] == 1){
    	        $jd_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>5])->sum('money');
    	        $val['jd_reward'] = round($jd_reward,2);
    	    }
    	    if($set['fenxiao']['is_pingji'] == 1){
    	        $pj_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>6])->sum('money');
    	        $val['pj_reward'] = round($pj_reward,2);
    	    }
    	    if($set['fenxiao']['is_abonus'] == 1){
    	        $ab_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>['in',[7,10]]])->sum('money');
    	        $val['ab_reward'] = round($ab_reward,2);
    	    }
    	    if($set['fenxiao']['is_repurchase_pingji'] == 1){
    	        $repurchase_pingji_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>16])->sum('money');
    	        $val['repurchase_pingji_reward'] = round($repurchase_pingji_reward,2);
    	    }
    	    if($set['double_track']['status'] == 1){
    	        $sgmanagement_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>14])->sum('money');
    	        $val['sgmanagement_reward'] = round($sgmanagement_reward,2);
    	    }
    	    if($set['fenxiao']['is_management'] == 1){
    	        $management_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>15])->sum('money');
    	        $val['management_reward'] = round($management_reward,2);
    	    }
    	    if($set['fenxiao']['is_repurchase'] == 1){
    	        $repurchase_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>17])->sum('money');
    	        $val['repurchase_reward'] = round($repurchase_reward,2);
    	    }
    	    if($set['fenxiao']['is_ladder_abonus'] == 1){
    	        $ladderabonus_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>19])->sum('money');
    	        $val['ladderabonus_reward'] = round($ladderabonus_reward,2);
    	    }
    	    if($set['cloud_warehouse']['status'] == 1){
    	        $cloud_warehouse_fanhuan_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>20])->sum('money');
    	        $val['cloud_warehouse_fanhuan_reward'] = round($cloud_warehouse_fanhuan_reward,2);
    	    }
    	    if($set['cloud_warehouse']['status'] == 1){
    	        $cloud_warehouse_chuhuo_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>21])->sum('money');
    	        $val['cloud_warehouse_chuhuo_reward'] = round($cloud_warehouse_chuhuo_reward,2);
    	    }
    	    
    	    if($set['fenxiao']['is_appoint'] == 1){
    	        $appoint_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>22])->sum('money');
    	        $val['appoint_reward'] = round($appoint_reward,2);
    	    }
    	    
    	    if($set['fenxiao']['is_directpush_achievement'] == 1){
    	        $directpush_achievement_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>23])->sum('money');
    	        $val['directpush_achievement_reward'] = round($directpush_achievement_reward,2);
    	    }
    	    if($set['fenxiao']['is_directpush_jiandan'] == 1){
    	        $directpush_jiandan_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>24])->sum('money');
    	        $val['directpush_jiandan_reward'] = round($directpush_jiandan_reward,2);
    	    }
    	    if($set['fenxiao']['is_store_reward'] == 1){
    	        $store_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>25])->sum('money');
    	        $val['store_reward'] = round($store_reward,2);
    	    }
    	    if($set['fenxiao']['is_dealer_reward'] == 1){
    	        $dealer_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>26])->sum('money');
    	        $val['dealer_reward'] = round($dealer_reward,2);
    	    }
    	    if($set['fenxiao']['is_below'] == 1){
    	        $below_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>27])->sum('money');
    	        $val['below_reward'] = round($below_reward,2);
    	    }
    	    if($set['fenxiao']['is_team_building'] == 1){
    	        $team_building_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>28])->sum('money');
    	        $val['team_building_reward'] = round($team_building_reward,2);
    	    }
    	    if($set['directpush_team']['status'] == 1){
    	        $directpush_team_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>29])->sum('money');
    	        $val['directpush_team_reward'] = round($directpush_team_reward,2);
    	    }
    	    if($set['sabonus']['status'] == 1){
    	        $sabonus_reward = Db::name("bbfx_fenxiao_order")->where(['uniacid'=>UNIACID,'status'=>1,'user_id'=>$val['id'],'type'=>30])->sum('money');
    	        $val['sabonus_reward'] = round($sabonus_reward,2);
    	    }
    	      
    	}
    	unset($val);
    	
    	$total = Db::name("bbfx_user")->where($where)->count();
    	
    	__success("操作成功",['total'=>$total,'list'=>$list]);
      
    }
    
    public function setSupuser(){
        $params = $this->param();
        
        $id = intval($params['id']);
        $sup_uid = intval($params['sup_uid']);
        $level = intval($params['level']);
        
        $user = UserMode::getInfo($id);
        $sup_user = UserMode::getInfo($sup_uid);
        if(empty($user)){
            __error("用户信息错误");
        }
        if(empty($sup_user) && $sup_uid > 0){
            __error("推荐人信息错误");
        }
        if($user['distributor_status'] != 1 || $user['is_distributor'] != 1){
            __error("不是分销商");
        }
        
        
        $data = ['sup_uid'=>$sup_uid,'level'=>$level];
        
        if($user['sup_uid'] != $sup_uid){
            
            if(!empty($sup_user)){
                
                $isSupUser = UserMode::isSupUser($sup_user['id'],$user['id']);
                if(empty($isSupUser)){
                    __error("推荐关系存在死循环，请重新选择推荐人");
                }
                if($sup_user['distributor_status'] != 1 || $sup_user['is_distributor'] != 1){
                    __error("推荐人不是分销商");
                }
                $sup_path = $sup_user['sup_path']."-".$id;
            }
            else{
                $sup_path = "0-".$id;
            }
            
            $data['sup_path'] = $sup_path;
        }
        
        $res = Db::name("bbfx_user")->where(['id'=>$id])->update($data);
        if($res){
            
            \app\common\model\bbfxshop\FenxiaoUpgrade::addUpgradeRecord(1,$user['id'],$data['level'],$user['level'],$user['sup_uid']);
            
            if($user['sup_uid'] != $sup_uid && !empty($sup_path)){
                UserMode::initSupPath($user['id'],$sup_path);
            }
            $data['id'] = $id;
            \app\admin\model\AdminLog::record("","",$data,"bbfx_user");
            
            __success("操作成功");
        }
        else{
            __error("操作失败");
        }
    }
    
    public function getUserSet(){
        $params = $this->param();
        
        $id = intval($params['id']);
        
        $ids = [$id];
        
        $alldown = FenxiaoUser::getAllDown($id);
        if(!empty($alldown['ids'])){
            $ids = array_merge($ids,$alldown['ids']);
        }
        
        $sup_user = Db::name("bbfx_user")->where(['is_distributor'=>1,'distributor_status'=>1,'status'=>1,'id'=>['not in',$ids]])->field(['id','avatar','nickname'])->select();
        if(empty($sup_user)){
            $sup_user = [];
        }
        
        $levels = \app\common\model\bbfxshop\FenxiaoLevel::getLevels();
        
        __success("操作成功",['sup_user'=>$sup_user,'levels'=>$levels]);
    }
    
    public function getSupuser(){
        $params = $this->param();
        
        $id = intval($params['id']);
        
        $ids = [$id];
        
        $alldown = FenxiaoUser::getAllDown($id);
        if(!empty($alldown['ids'])){
            $ids = array_merge($ids,$alldown['ids']);
        }
        
        $list = Db::name("bbfx_user")->where(['is_distributor'=>1,'distributor_status'=>1,'status'=>1,'id'=>['not in',$ids]])->field(['id','avatar','nickname'])->select();
        if(!empty($list)){
            __success("操作成功",$list);
        }
        else{
            __error("未查询到用户");
        }
    }
    
    public function delete(){
        $this->commonDelete('bbfx_fenxiao_user');
    }
    
}