0)
        {
            $pagenum=I('pagenum/s');
        }
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        $mobile = I('mobile') ? trim(I('mobile')) : '';
        $getoldurl = I('oldurl') ? trim(I('oldurl')) : '';
        if ($getoldurl)
        {
            $getoldurl=urldecode(urldecode($getoldurl));
        }
        if ($mobile)
        {
            $mobile=" 上级用户(".$mobile.")";
        }
        $userid = I('userid') ? trim(I('userid')) : '';
        $where=" 1=1  and store_id=".getAdmStoId()."";
        //$where.=" and is_distribut = 1 and  mobile<>''";
        $where.=" and is_distribut = 1 ";
        if($key_word)
        {
            $where.=" and (mobile like '%".$key_word."%' or vipname like '%".$key_word."%')";
        }
        if($userid)
        {
            $where.=" and first_leader=".$userid;
        }
        $model = M('users');
        $count = $model->where($where)->count();
        $Page  = new Page($count,$pagenum);
        $show = $Page->show();
        $list = $model->where($where)
            ->order('user_id desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->field('user_id,vipname,mobile,first_leader')
            ->select();
        $this->assign('mobile',$mobile);
        $this->assign('pager',$Page);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
        $this->assign('getoldurl',$getoldurl);
//        $where = 'is_distribut = 1 and mobile is not null and mobile<>""';
//        $where.=" and store_id=".getAdmStoId()."";
//        if($this->request->param('user_id')) {
//            $where = "user_id = '{$this->request->param('user_id')}'";
//            $where.= " or mobile like '%{$this->request->param('user_id')}%'";
//        }
//
//        $list = M('users')->where($where)->select();
//        $this->assign('list',$list);
        upload_ylp_log('B27分销关系查询/搜索');
        return $this->fetch("",getAdmStoId());
    }
 
    /**
     * 分销商列表
     */
    public function distributor_list(){
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
    	$nickname = I('nickname');
        $mobile = I('mobile');
        $where=" and 1=1";
    	if(!empty($nickname)){
            $where.=" and a.nickname like '%".$nickname."%'";
        }
        if(!empty($mobile)){
            $where.=" and a.mobile like '%".$mobile."%'";
        }
    	$is_setdistri_first=tpCache('distribut.is_setdistri_first',getAdmStoId());
        $this->assign('is_setdistri_first',$is_setdistri_first);
        $strsql='select a.user_id,a.mobile,a.nickname,a.frozen_money,a.distribut_money,a.user_money,
1 as first_leader_num,
IFNULL(b.c,0) as second_leader_num,
IFNULL(c.c,0) as third_leader_num 
from wxd_users a 
LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' group by first_leader ) b on a.user_id=b.first_leader
LEFT JOIN (select second_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' group by second_leader ) c on a.user_id=c.second_leader 
where a.is_distribut=1 and a.store_id='.getAdmStoId().$where.' ORDER BY user_id desc';
        $datalist=Db::query($strsql);
        $count = count($datalist);
        $Page = new Page($count,$pagenum);
        $show = $Page->show();
        //分页实现
        $p=I('p/d',1);
        $fir=($p-1)*$pagenum;$end=$p*$pagenum;
        $lists2=null;
        if($end>$count){$end=$count; }
        for($i=$fir;$i<$end;$i++){ $lists2[]=$datalist[$i];}
    	$this->assign('page',$show);
    	$this->assign('pager',$Page);
    	$this->assign('user_list',$lists2);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
//        upload_ylp_log('分销商列表');
    	return $this->fetch('',getAdmStoId());
    }
  /*分销商数据导出*/
    public function exportreport()
    {
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $where="";
        //$condition['is_distribut']  = 1;
        $nickname = I('nickname');
        $mobile = I('mobile');
        if(!empty($nickname)){
            //$condition['nickname'] = array('like',"%$nickname%");
            $where.=" and nickname like '%".$nickname."%'";
        }
        if(!empty($mobile)){
            //$condition['mobile'] = array('like',"%$mobile%");
            $where.=" and mobile like '%".$mobile."%'";
        }
        //$condition['store_id']=getAdmStoId();
        //$user_list = M('users')->where($condition)->order('distribut_money DESC')->select();
        //$is_setdistri_first=tpCache('distribut.is_setdistri_first',getAdmStoId());
        $strsql='select a.user_id,a.mobile,a.nickname,a.frozen_money,a.distribut_money,a.user_money,a.reg_time,
1 as fisrt_leader,
IFNULL(b.c,0) as second_leader,
IFNULL(c.c,0) as third_leader,
1+IFNULL(b.c,0)+IFNULL(c.c,0) as lower_sum,s1.mobile as mobile1,s1.vipname as vipname1 
from wxd_users a 
LEFT JOIN (select first_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' group by first_leader ) b on a.user_id=b.first_leader
LEFT JOIN (select second_leader,COUNT(1) as c from wxd_users where is_distribut=1 and store_id='.getAdmStoId().' group by second_leader ) c on a.user_id=c.second_leader 
left join wxd_users s1 on a.first_leader=s1.user_id
where a.is_distribut=1 and a.store_id='.getAdmStoId().$where.' ORDER BY a.user_id desc';
//        foreach ($user_list as $k=>$val){
//                $user_list[$k]['fisrt_leader'] = 1;
//                $user_list[$k]['second_leader'] = M('users')->where(array('first_leader'=>$val['user_id']))->where('is_distribut',1)->count();
//                $user_list[$k]['third_leader'] = M('users')->where(array('second_leader'=>$val['user_id']))->where('is_distribut',1)->count();
//                $user_list[$k]['lower_sum'] = $user_list[$k]['fisrt_leader'] +$user_list[$k]['second_leader'] + $user_list[$k]['third_leader'];
//            }
        $user_list=Db::query($strsql);
        $strTable ='
';
        $strTable .= '';
        $strTable .= '| 用户手机';
        $strTable .= ' | 微信昵称';
        $strTable .= ' | 注册时间';
        $strTable .= ' | 可用资金';
        $strTable .= ' | 冻结资金';
        $strTable .= ' | 总分成金额';
        $strTable .= ' | 下线会员总数';
        $strTable .= ' | 上一级手机号';
        $strTable .= ' | 上一级名称';
        $strTable .= ' | 一级会员数';
        $strTable .= ' | 二级会员数';
        $strTable .= ' | 三级会员数';
        $strTable .= ' | 
';
        if(is_array($user_list)){
            foreach($user_list as $k=>$val){
                $strTable .= '';
                $strTable .= '| '.$val['mobile'].'';
                $strTable .= ' | '.$val['nickname'].'';
                $strTable .= ' | '.date('Y-m-d H:i:s',$val['reg_time']).'';
                $strTable .= ' | ¥'.$val['user_money'].'';
                $strTable .= ' | ¥'.$val['frozen_money'].'';
                $strTable .= ' | ¥'.$val['distribut_money'].'';
                $strTable .= ' | '.$val['lower_sum'].'';
                $strTable .= ' | '.$val['mobile1'].'';
                $strTable .= ' | '.$val['vipname1'].'';
                $strTable .= ' | '.$val['fisrt_leader'].'';
                $strTable .= ' | '.$val['second_leader'].'';
                $strTable .= ' | '.$val['third_leader'].'';;
                $strTable .= ' | 
';
            }
        }
        $strTable .='
';
        echo  $strTable;
        unset($user_list);
        downloadExcel($strTable,'distribut');
        exit();
    }
    /*分销商品导出*/
    public function exportgoods()
    {
        $pattern=tpCache('distribut.pattern',getAdmStoId());
        $this->assign('pattern',$pattern);
        $where = ' commission > 0 ';
        if($pattern==1){
            $where = '(fir_rate+sec_rate+thi_rate) > 0';
        }
        $cat_id = I('cat_id/d');
        $bind = array();
        if($cat_id > 0)
        {
            $grandson_ids = getCatGrandson($cat_id);
            $where .= " and a.cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
        }
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if($key_word)
        {
            $where = "$where and (a.goods_name like :key_word1 or a.goods_sn like :key_word2)" ;
            $bind['key_word1'] = "%$key_word%";
            $bind['key_word2'] = "%$key_word%";
        }
        $where.="  and a.store_id=".getAdmStoId()."";
        $brand_id = I('brand_id');
        if($brand_id){
            $where = "$where and a.brand_id = :brand_id";
            $bind['brand_id'] = $brand_id;
        }
        $model = M('Goods');
        $goodsList = $model->alias('a')->join('goods_category b',' a.cat_id=b.id and a.store_id=b.store_id','left')
            ->field('a.*,b.name as cat_name')
            ->where($where)->bind($bind)->order('sales_sum desc')->select();
        $strTable ='';
        $strTable .= '';
        $strTable .= '| 商品名称';
        $strTable .= ' | 销量';
        $strTable .= ' | 分类';
        $strTable .= ' | 价格';
        $strTable .= ' | 库存数量';
        $strTable .= ' | 分成金额';
        $strTable .= ' | 
';
        if(is_array($goodsList)){
            foreach($goodsList as $k=>$val){
                $strTable .= '';
                $strTable .= '| '.$val['goods_name'].'';
                $strTable .= ' | '.$val['sales_sum'].'';
                $strTable .= ' | '.$val['cat_name'].'';
                $strTable .= ' | ¥'.$val['shop_price'].'';
                $strTable .= ' | '.$val['store_count'].'';
                $strTable .= ' | ¥'.($pattern=='1'?$val['fir_rate']+$val['sec_rate']+$val['thi_rate']:$val['commission']).'';
                $strTable .= ' | 
';
            }
        }
        $strTable .='
';
        echo  $strTable;
        unset($goodsList);
        downloadExcel($strTable,'distributgoods');
        exit();
    }
    /**
     * 分销设置
     */
    public function set(){                       
        header("Location:".U('Admin/System/index',array('inc_type'=>'distribut')));
        exit;
    }
    
    public function goods_list(){
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $GoodsLogic = new GoodsLogic();
    	$brandList = $GoodsLogic->getSortBrands();
    	$categoryList = $GoodsLogic->getSortCategory();
    	$this->assign('categoryList',$categoryList);
    	$this->assign('brandList',$brandList);
    	$pattern=tpCache('distribut.pattern',getAdmStoId());
        $this->assign('pattern',$pattern);
    	$where = ' commission > 0 ';
        if($pattern==1){
            $where = '(fir_rate+sec_rate+thi_rate) > 0';
        }
    	$cat_id = I('cat_id/d');
        $bind = array();
    	if($cat_id > 0)
    	{
    		$grandson_ids = getCatGrandson($cat_id);
    		$where .= " and cat_id in(".  implode(',', $grandson_ids).") "; // 初始化搜索条件
    	}
    	$key_word = I('key_word') ? trim(I('key_word')) : '';
    	if($key_word)
    	{
    		$where = "$where and (goods_name like :key_word1 or goods_sn like :key_word2)" ;
            $bind['key_word1'] = "%$key_word%";
            $bind['key_word2'] = "%$key_word%";
    	}
    	$where.="  and store_id=".getAdmStoId()."";
        $brand_id = I('brand_id');
        if($brand_id){
            $where = "$where and brand_id = :brand_id";
            $bind['brand_id'] = $brand_id;
        }
    	$model = M('Goods');
    	$count = $model->where($where)->bind($bind)->count();
    	$Page  = new Page($count,$pagenum);
    	$show = $Page->show();
    	$goodsList = $model->where($where)->bind($bind)->order('sales_sum desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        $catList = M('goods_category')->where("  store_id=".getAdmStoId()."")->select();
        $catList = convert_arr_key($catList, 'id');
        $this->assign('catList',$catList);
        $this->assign('pager',$Page);
    	$this->assign('goodsList',$goodsList);
    	$this->assign('page',$show);
        $this->assign('cat_id',$cat_id);
        $this->assign('brand_id',$brand_id);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
        upload_ylp_log('B24分销商品查询/搜索');
    	return $this->fetch('',getAdmStoId());
    }
 
    
    /**
     * 分成记录
     */
    public function rebate_log()
    {
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $status = I('status');
        $user_id = I('user_id');
        $order_sn = I('order_sn');        
        $start = trim(I('start_time'));
        $end= trim(I('end_time'));
        $where=" a.store_id=".getAdmStoId();
        if(!empty($start)){
            $where.= " and a.create_time >= ".strtotime($start);
		}
        if(!empty($end)){
            $where.=" and a.create_time <= ".strtotime($end);
		}
		
        if($status === '0' || $status > 0){
            $where .= " and a.status = $status ";
		}
        $user_id && $where .= " and b.mobile = $user_id ";
        $order_sn && $where .= " and a.order_sn like '%{$order_sn}%' ";
                
        $count = M("rebate_log")->alias("a")->join("users b","a.user_id=b.user_id",'LEFT')->field("a.*,b.mobile")
               ->where($where)->count();
        $Page  = new Page($count,$pagenum);
        $list = M("rebate_log")->alias("a")->join("users b","a.user_id=b.user_id",'LEFT')->field("a.*,b.mobile")
              ->where($where)->order("a.id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        $liststr = M("rebate_log")->alias("a")->join("users b","a.user_id=b.user_id",'LEFT')->field("a.*,b.mobile")
            ->where($where)->order("a.id desc")->limit($Page->firstRow.','.$Page->listRows)->fetchSql(true)->select();
        mlog($liststr,'rebate_log/'.getAdmStoId());
//        $this->assign('create_time',$create_time);
        $show  = $Page->show();                 
        $this->assign('show',$show);
        $this->assign('page',$show);
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('pagenum',$pagenum);
        $this->assign('oldurl',urlencode(curPageURL()));
        C('TOKEN_ON',false);
        upload_ylp_log('B28分成日志查询/搜索');
        return $this->fetch('',getAdmStoId());
    }
    /**
     * 分成记录数据导出
     */
    public function exportrebate_log()
    {
        $pagenum=20;//每页显示多少条
        if ((int)I('pagenum/s')>0)
        {
            $pagenum=I('pagenum/s');
        }
        $status = I('status');
        $user_id = I('user_id');
        $order_sn = I('order_sn');
        $start = trim(I('start_time'));
        $end= trim(I('end_time'));
        $where=" a.store_id=".getAdmStoId();
        if(!empty($start)){
            $where.= " and a.create_time >= ".strtotime($start);
        }
        if(!empty($end)){
            $where.=" and a.create_time <= ".strtotime($end);
        }
        if($status === '0' || $status > 0){
            $where .= " and a.status = $status ";
        }
        $user_id && $where .= " and b.mobile = $user_id ";
        $order_sn && $where .= " and a.order_sn like '%{$order_sn}%' ";
        $goodsList = M("rebate_log")->alias("a")->join("users b","a.user_id=b.user_id",'LEFT')->field("a.*,b.mobile")
            ->where($where)->order("a.id desc")->select();
        $strTable ='';
        $strTable .= '';
        $strTable .= '| 获佣用户手机';
        $strTable .= ' | 订单编号';
        $strTable .= ' | 获佣金额';
        $strTable .= ' | 获佣用户级别';
        $strTable .= ' | 记录生成时间';
        $strTable .= ' | 状态';
        $strTable .= ' | 
';
        if(is_array($goodsList)){
            foreach($goodsList as $k=>$val){
                $strTable .= '';
                $strTable .= '| '.$val['mobile'].'';
                $strTable .= ' | '.$val['order_sn'].'';
                $strTable .= ' | ¥'.$val['money'].'';
                $strTable .= ' | '.($val['level']=='1'?'一级分销商':$val['level']=='2'?'二级分销商':'三级分销商').'';
                $strTable .= ' | '.date('Y-m-d H:i:s',$val['create_time']).'';
                $strTable .= ' | '.$this->getrebate_status($val['status']).'';
                $strTable .= ' | 
';
            }
        }
        $strTable .='
';
        echo  $strTable;
        unset($goodsList);
        downloadExcel($strTable,'rebate_log');
        exit();
    }
    public function  getrebate_status($status)
    {
        $restr="";
        switch ($status)
        {
            case "0":
                $restr="未付款";
                break;
            case "1":
                $restr="已付款";
                break;
            case "2":
                $restr="等待分成";
                break;
            case "3":
                $restr="已分成";
                break;
            case "4":
                $restr="已取消";
                break;
        }
        return $restr;
    }
    /**
     * 获取某个人下级元素
     */    
    public  function ajax_lower()
    {
        $id = $this->request->param('id');
        $list = M('users')->where(" is_distribut=1 and mobile is not null and mobile<>'' and store_id=".getAdmStoId()." and first_leader =".$id)->select();
        $this->assign('list',$list);
        return $this->fetch('',getAdmStoId());
    }
    
    /**
     * 修改编辑 分成 
     */
    public  function editRebate(){        
        $id = I('id');
        $rebate_log = DB::name('rebate_log')->where('id',$id)->find();
        if (IS_POST) {
            ClearALLCache();
            delFile(TEMP_PATH."/".getAdmStoId());
            $data = I('post.');
            // 如果是确定分成 将金额打入分佣用户余额
            if ($data['status'] == 3 && $rebate_log['status'] != 3) {
                accountLog($data['user_id'], $rebate_log['money'], 0, "订单:{$rebate_log['order_sn']}分佣", $rebate_log['money']);
            }
//            upload_ylp_log('修改分成');
            DB::name('rebate_log')->update($data);
            $this->success("操作成功!!!", U('Admin/Distribut/rebate_log'));
            exit;
        }                      
       
       $user = M('users')->where("user_id = {$rebate_log[user_id]}")->find();       
            
       if($user['nickname'])        
           $rebate_log['user_name'] = $user['nickname'];
       elseif($user['email'])        
           $rebate_log['user_name'] = $user['email'];
       elseif($user['mobile'])        
           $rebate_log['user_name'] = $user['mobile'];            
       
       $this->assign('user',$user);
       $this->assign('rebate_log',$rebate_log);
       return $this->fetch('',getAdmStoId());
    }
    private function initEditor()
    {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath' => 'wechat')));
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath' => 'wechat')));
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath' => 'wechat')));
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath' => 'wechat')));
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath' => 'wechat')));
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath' => 'wechat')));
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath' => 'wechat')));
        $this->assign("URL_Home", "");
    }
}