<?php
/**
 * 会员管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */

namespace Admin\Controller;
class MemberController extends BaseController{
    public function _initialize()
    {
        parent::_initialize();
        $this->admin_info=session('admin_info');
        $map=array();
        $map['uid']=$this->admin_info['id'];
        $this->auth_group_id=M("AuthGroupAccess")->where($map)->getField('group_id');
        if($this->auth_group_id==2 && ACTION_NAME!="index"){
            $this->redirect('Admin/Member/index');
        }
        $this->assign('auth_group_id',$this->auth_group_id);
        $constellationData = array('白羊座'=>'白羊座','金牛座'=>'金牛座','双子座'=>'双子座','巨蟹座'=>'巨蟹座','狮子座'=>'狮子座','处女座'=>'处女座','天枰座'=>'天枰座','射手座'=>'射手座','摩羯座'=>'摩羯座','水瓶座'=>'水瓶座','双鱼座'=>'双鱼座','天蝎座'=>'天蝎座');
        $this->assign('constellationData',$constellationData);
    }
    public function index(){
        $type = I('get.type');
        $postdata=I('param.');
        $keyword = I('keyword');
        $map=array();
        if(!empty($keyword)){
    	  $whereor['id']=array('like','%'.$keyword.'%');
    	  $whereor['username']=array('like','%'.$keyword.'%');
    	  $whereor['nickname']=array('like','%'.$keyword.'%');
    	  $whereor['real_name']=array('like','%'.$keyword.'%');
    	  $whereor['card_sn']=array('like','%'.$keyword.'%');
    	  $whereor['_logic'] = 'or';
    	  $map['_complex'] = $whereor;
    	  $seotitle=$keyword.'_';
        }
        if(!empty($postdata['mobile']))$map['mobile'] = array('like','%'.$postdata['mobile'].'%');
        if(!empty($postdata['rank_id'])){
           $map['rank_id']=$postdata['rank_id'];
        }
        if($postdata['type']){ $type = $postdata['type'];}
        if($type == 1){
            $map['is_follow'] =0;
        }else{
    	  if(!empty($postdata['reg_from']))$map['reg_time'][]=array('EGT',strtotime($postdata['reg_from']));
    	  if(!empty($postdata['reg_to']))$map['reg_time'][]=array('elt',strtotime($postdata['reg_to']));
        }

        //仓库管理员
        if($this->auth_group_id==2){
            $map['user_shop']=$this->admin_info['shop_id'];
        }
		$list = $this->lists('Member',$map);
		//--xyy begin 2018.10.26
		// if($list){
		// 	foreach ($list as $key => $value) {
		// 		$map=array();
		// 		$map['uid']=$value['id'];
		// 		$customer_info=M('MemberCustomer')->where($map)->find();
		// 		if($customer_info){
		// 			$list[$key]['customer_id']=$customer_info['id'];
		// 		}
		// 	}
		// }
		//--xyy end
        $this->assign('list', $list);$this->assign($postdata);$this->assign($type);
        $this->getGroup(1);
        $this->display();
    }
    public function fans(){
        $postdata=I('param.');
        $keyword = I('keyword');
        $map=array();
        $map['status']=1;
        if(!empty($keyword)){
	  $whereor['wxid']=array('like','%'.$keyword.'%');
            $whereor['username']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
        }
        if(!empty($postdata['reg_from']))$map['reg_time'][]=array('EGT',strtotime($postdata['reg_from']));
        if(!empty($postdata['reg_to']))$map['reg_time'][]=array('elt',strtotime($postdata['reg_to']));
        //仓库管理员
        if($this->auth_group_id==2){
            $map['user_shop']=$this->admin_info['shop_id'];
        }
        // $map['wxid'] = array('neq','');
        $map['is_follow']=1;
        $list = $this->lists('Member',$map);
        $this->assign('list', $list);$this->assign($postdata);
        $this->display();
    }
//添加会员
    public function add(){
        if (IS_POST) {
            $member_mod = M('Member');
            $postdata=I('post.');

            if (!isset($postdata['username']) || ($postdata['username'] == '')) {
                $this->error('用户名不能为空');
            }
            if ($postdata['password'] != $postdata['repassword']) {
                $this->error('两次输入的密码不相同');
            }
	  if($postdata['card_sn']){
	      $cardmap['card_sn'] =  $postdata['card_sn'];
	      $cardcot = $member_mod->where($cardmap)->count();
	      if ($cardcot) {
		$this->error('会员卡号' . $postdata['card_sn'] . '已经存在');
	      }
	      $postdata['card_time'] =  NOW_TIME;
	      $postdata['card_status'] =  1;
	  }else{
	      unset($postdata['card_sn']);
	      unset($postdata['card_time']);
	  }

	    $where['username']=$postdata['username'];
            $result = $member_mod->where($where)->count();
            if ($result) {
                $this->error('会员' . $postdata['username'] . '已经存在');
            }
            unset($postdata['repassword']);
            $postdata['salt'] = randStr();
            $postdata['password'] = creatpwd($_POST['password'], 'HANCHAO'.$postdata['salt']);
            $postdata['paypassword'] = creatpwd($_POST['paypassword'], 'HANCHAO'.$postdata['salt']);
            $postdata['card_paypass'] = creatpwd('123456', 'HANCHAO'.$postdata['salt']);
            $postdata['reg_time'] = $postdata['last_login'] = NOW_TIME;
            $postdata['reg_ip'] = $postdata['last_ip'] = get_client_ip(1);
			$postdata['rank_id']=$postdata['rank_id'];
            $member_mod->create($postdata);
            $result = $member_mod->add();
            unset($postdata);
            if ($result) {
                $this->success(L('DO_OK'), '', '', 'add');
            } else {
                $this->error(L('DO_ERROR'));
            }
        } else {
			$daogou_arr = M('ShopsRoleAccount')->where('role_id=2')->getField('account_id',true);
			if($daogou_arr){
				foreach ($daogou_arr as $v) {
					$newdaogou_arr[$v] = idtoname($v,'ShopsAccount','name','id',false);
				}$daogou_arr=$newdaogou_arr;
			}
			$this->assign('daogou_arr', $daogou_arr);
            $this->getGroup(1);
			$this->getShops(1);
            $this->display('edit');
        }
    }
//编辑会员
    public function edit(){
        $id = I('id');
        $member_mod = D('Member');
        if (IS_POST) {
            $postdata=I('post.');
            if(!empty($postdata['username'])){                    
                $map=array();
                $map['id']=array('neq',$id);
                $map['username']=$postdata['username'];
                $count = $member_mod->where($map)->count();
                if ($count > 0) {
                    $this->error('用户名已经存在！');
                }
            }else{
                unset($postdata['username']);
            }
            $adminsalt = $member_mod->where("id='" . $id . "'")->getField('salt');
            if ($postdata['password']) {
                if ($postdata['password'] != $postdata['repassword']) {
                    $this->error('两次输入的密码不相同');
                }
                $postdata['password'] = creatpwd($postdata['password'],'HANCHAO'.$adminsalt);
            } else {
                unset($postdata['password']);
            }
			if($postdata['card_sn']){
				$cardmap['card_sn'] =  $postdata['card_sn'];
				$cardmap['id'] =  array('neq',$id);
				$cardcot = $member_mod->where($cardmap)->count();
				if ($cardcot) {
					$this->error('会员卡号' . $postdata['card_sn'] . '已经存在');
				}
				$postdata['card_time'] =  NOW_TIME;
			}else{
				unset($postdata['card_sn']);
			}
            if ($postdata['paypassword']) {
                if(!preg_match("/^\d{6}$/",$postdata['paypassword'])){
                    $this->error('支付密码必须为六位数字');
                }
                $postdata['paypassword'] = creatpwd($postdata['paypassword'],'HANCHAO'.$adminsalt);
            } else {
                unset($postdata['paypassword']);
            }
            unset($postdata['repassword']);

            $affiliate = unserialize(C('AFFILIATE'));
            $is_weidian = $affiliate['config']['is_weidian'];
            $is_weidian_level = $affiliate['config']['is_weidian_level']; 
            $is_weidian_level_sort = idtoname($is_weidian_level,'MemberRank','sort');//系统限定推广等级级别
            $member_rank_sort = idtoname($postdata['rank_id'],'MemberRank','sort');
            if($member_rank_sort>=$is_weidian_level_sort){
                $postdata['is_littleshop']=1;
                $map = array();
                $map['uid']=$id;
                $little_count = M('LittleShop')->where($map)->count();
                if($little_count==0){
                    $little_shop['uid']=$id;
                    $little_shop['name']=$postdata['username'].'的小店';
                    $little_shop['addtime']=NOW_TIME;
                    $little_shop['status']=1;
                    M('LittleShop')->add($little_shop);
                }
            }

            if (false === $member_mod->create($postdata)) {
                $this->error($member_mod->getError());
            }
            $result = $member_mod->save();
            unset($postdata);
            if (false !== $result) {
                $this->success(L('DO_OK'), '', '', 'edit');
            } else {
                $this->error(L('DO_ERROR'));
            }
        } else {
            if (isset($id)) {
                $id = isset($id) && intval($id) ? intval($id) : $this->error('参数错误');
            }
            if(!$id)$this->error('参数错误');
            $info = $member_mod->field(true)->find($id);
			$daogou_arr = M('ShopsRoleAccount')->where('role_id=2')->getField('account_id',true);
			if($daogou_arr){
				foreach ($daogou_arr as $v) {
					$acc_name = idtoname($v,'ShopsAccount','name','id',false);
					if($acc_name){
						$newdaogou_arr[$v] = $acc_name;
					}
				}$daogou_arr=$newdaogou_arr;
			}
			$this->assign('daogou_arr', $daogou_arr);
            $this->assign($info);
            $this->getGroup(1);
            $this->getShops(1);
            $this->display();
        }
    }
	//删除会员
	public function _before_delete(){
		$id=I('id');
		if(isset($id)&&is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,1);
				if(!$result['status'])unset($id[$k]);
			}
			if(empty($id)){$this->error('会员下有未完成的订单或已绑定商铺');exit;}
		}else{
			$result=check_delete($id,1);
			if(!$result['status']){$this->error($result['info']);exit;}
		}
		$this->id=$id;
	}
	public function view(){
		$id = I('id');
		$rank_info=ex_ranks($id);
		$member_mod = D('Member');
		$info = $member_mod->field(true)->find($id);
		$this->assign($info);
		$this->assign('rank_info',$rank_info);
		$this->getGroup(1);
		$this->display();
	}
	public function export(){
		$postdata=I('param.');
		if($postdata){
			$name = CONTROLLER_NAME;
			$map=array();
			if($postdata['keyword']){
				$whereor['id']=array('like','%'.$postdata['keyword'].'%');
				$whereor['username']=array('like','%'.$postdata['keyword'].'%');
				$whereor['mobile']=array('like','%'.$postdata['keyword'].'%');
				$whereor['_logic'] = 'or';
				$map['_complex'] = $whereor;
				$seotitle=$keyword.'_';
			}
			if($postdata['mobile'])$map['mobile']=$postdata['mobile'];
			if($postdata['rank_id'])$map['rank_id']=$postdata['rank_id'];
			if($postdata['reg_from'])$map['reg_time'][]=array('EGT',strtotime($postdata['reg_from']));
			if($postdata['reg_to'])$map['reg_time'][]=array('elt',strtotime($postdata['reg_to']));
			$result=M('Member')->where($map)->field('password,salt',true)->order('id desc')->select();
			$title=array('序号','用户名','等级','性别','生日','余额','积分','盈利账户','累计消费','姓名','昵称','手机','会员卡号','联系地址','注册时间','最后登录','推荐人');
			foreach($result as $k => $v){
				$data[$k][]=$v['id'];
				$data[$k][]=show_user_name($v['id']);
				$data[$k][]=idtoname($v['rank_id'],'MemberRank');
				if($v['sex']==1){$data[$k][]="男";}elseif($v['sex']==2){$data[$k][]="女";}else{$data[$k][]="保密";}
				// $data[$k][]=idtoname($v['sex'],'Type');
				$data[$k][]=$v['birthday'];
				$data[$k][]=$v['money'];
				$data[$k][]=$v['usepoints'];
				$data[$k][]=$v['comm_money'];
				$data[$k][]=$v['points'];
				$data[$k][]=$v['real_name'];
				$data[$k][]=$v['nickname'];
				$data[$k][]=$v['mobile'];
				$data[$k][]=format_xml_num($v['card_sn']);
				// $data[$k][]=$v['address'];
				$province = $v['province']?idtoname($v['province'],'Area'):'';
				$city_id = $v['city_id']?idtoname($v['city_id'],'Area'):'';
				$district = $v['district']?idtoname($v['district'],'Area'):'';
				$data[$k][]=$province.$city_id.$district;
				$data[$k][]=time_format($v['reg_time']);
				$data[$k][]=time_format($v['last_login']);
				$data[$k][]=$v['parent_id']?idtoname($v['parent_id'],'Member','username'):'';
			}
			export_xls($title,$data,'utf8');
			unset($title,$data);exit;
		}
	}
    /* 得到所属组 */
    private function getGroup($type = ''){
        $groupData = M('MemberRank')->where('status=1')->field(true)->order('sort,id desc')->select();
        if ($type == 1) {
            foreach ($groupData as $v) {
                $newgroupData[$v['id']] = $v['name'];
            }$groupData=$newgroupData;
        }
        $this->assign('groupData', $groupData);
    }
	/* 得到注册仓库 */
    private function getShops($type = ''){
        $shopsData = M('Shops')->where('status=1')->field('id,name')->select();
		if ($type == 1) {
			foreach ($shopsData as $v) {
                $newshopsData[$v['id']] = $v['name'];
            }$newshopsData['0'] = '平台';$shopsData=$newshopsData;
		}
        $this->assign('shopsData', $shopsData);
    }
    public function extension_list(){
        $is_auth=check_use_auth("NationalCustomers");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }
        $map = array();
        $postdata=I('param.');
        $pid = $postdata['pid'];
        $sid = $postdata['sid'];
        $parent_id = $postdata['parent_id'];
        if (!empty($pid)) {
            if (is_numeric($pid)) {
                $where_m['id|username'] = array(intval($pid), array('like', '%' . $pid . '%'), '_multi' => true);
            } else if (!empty($pid)) {
                $where_m['username'] = array('like', '%' . (string)$pid . '%');
            }
            $m_list = M('Member')->where($where_m)->field('id')->select();
            if (!empty($m_list)) {
                foreach ($m_list as $k => $v) {
                    $me_list[] = $v['id'];
                }
                $map['parent_id'] = array(array('in', $me_list));
            }
        }elseif(!empty($parent_id)){
            $where_m['id'] = $parent_id;
            $m_list = M('Member')->where($where_m)->field('id')->select();
            if (!empty($m_list)) {
                foreach ($m_list as $k => $v) {
                    $me_list[] = $v['id'];
                }
                $map['parent_id'] = array(array('in', $me_list));
            }else{
				$this->error('该会员id不存在！');exit;
			}
        }else{
            $map['parent_id']=array('gt',0);
        }
        if (!empty($sid)) {
            if (is_numeric($sid)) {
                $where_u['id|username'] = array(intval($sid), array('like', '%' . $sid . '%'), '_multi' => true);
            } else if (!empty($sid)) {
                $where_u['username'] = array('like', '%' . (string)$sid . '%');
            }
            $user_list = M('Member')->where($where_u)->field('id')->select();
            if (!empty($user_list)) {
                foreach ($user_list as $k => $v) {
                    $u_list[] = $v['id'];
                }
                $map['id'] = array(array('in', $u_list));
            }
        }
        $list = $this->lists('Member', $map);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }
	public function do_import(){
		$filename = $_FILES['file']['tmp_name'];
		if (empty ($filename)) {
			$this->error('请选择要导入的CSV文件！');exit;
		}
		if(!str_exists($_FILES['file']['name'],'.csv')){
			$this->error('导入的文件格式不正确！');exit;
		}
		$handle = fopen($filename, 'r');
		$result = $this->input_csv($handle); //解析csv
		$len_result = count($result);
		if($len_result==0){
			$this->error('没有任何数据！');exit;
		}

		$rank_list = M('MemberRank')->field('id,name')->cache(true)->select();
		$rank_list_arr = array();
		foreach($rank_list as $k=>$v){
			$rank_list_arr[$v['name']] = $v['id'];
		}
		$sex_arr = array('保密'=>0,'男'=>'1','女'=>'2');

		for ($i = 1; $i < $len_result; $i++) { //循环获取各字段值
			
			if(!$result[$i][9]) continue;
			else{
				$map = array();$map['mobile'] = $result[$i][9];
				$count = M('Member')->where($map)->count();
				if($count) continue;
			}
			$data_values = array();
			$data_values['username'] = iconv('gb2312', 'utf-8', $result[$i][0]); //中文转码

			$rank_id = $rank_list_arr[iconv('gb2312', 'utf-8', $result[$i][1])];
			$data_values['rank_id'] = $rank_id ? $rank_id : 1;
			$sex_id = $sex_arr[iconv('gb2312', 'utf-8', $result[$i][2])];
			$data_values['sex'] = $sex_id ? $sex_id : 0;
			$data_values['birthday'] = $result[$i][3];
			$data_values['money'] = $result[$i][4];
			$data_values['usepoints'] = $result[$i][5];
			$data_values['points'] = $result[$i][6];
			$data_values['real_name'] = iconv('gb2312', 'utf-8', $result[$i][7]);
			$data_values['nickname'] = iconv('gb2312', 'utf-8', $result[$i][8]);
			$data_values['mobile'] = $result[$i][9];
			$data_values['card_sn'] = str_replace("'",'',$result[$i][10]);
			$data_values['province'] = $result[$i][11]?idtoname(iconv('gb2312', 'utf-8', $result[$i][11]),'Area','id','name',false):0;

            //$map=array();
            //$map['status']=1;
            ////$map['name']=array('like',iconv('gb2312', 'utf-8', $result[$i][12]));
			$data_values['city_id'] = $city_id?$city_id:0;
			$data_values['district'] = $result[$i][13]?idtoname(iconv('gb2312', 'utf-8', $result[$i][13]),'Area','id','name',false):0;
			$data_values['reg_time'] = $result[$i][14]?strtotime($result[$i][14]):NOW_TIME;
			$data_values['last_login'] = $result[$i][15]?strtotime($result[$i][15]):NOW_TIME;
			$parent_id = 0;
			if(!empty($result[$i][16]) && $result[$i][16] != $result[$i][9]){
				$map = array();$map['mobile'] = $result[$i][16];$map['is_tmp'] = 0;
				$parent_id = M('Member')->where($map)->getField('id');
			}
			$data_values['parent_id'] = $parent_id;
			if($data_values['mobile']){
				$data_values['is_tmp'] = 0;
			}else{
				$data_values['is_tmp'] = 1;
			}
			$data_values['status'] = 1;
			$query = M('Member')->add($data_values);
		}
		fclose($handle); //关闭指针
		if($query){
			$this->success('导入成功！');
		}else{
			$this->error('导入失败！');
		}
	}
	public function input_csv($handle) {
		$out = array ();
		$n = 0;
		while ($data = fgetcsv($handle, 10000)) {
			$num = count($data);
			for ($i = 0; $i < $num; $i++) {
				$out[$n][$i] = $data[$i];
			}
			$n++;
		}
		return $out;
	}
	public function file_down(){
		file_down(ROOT_PATH."/uploads/file/mm.csv",'Member导入格式文档.csv');
	}
    //积分清零设置
    public function clearpoints(){
        $map=$where=$data=$data2=array();$mod=M('cron');
        $map['classname']='IntegralReset';//设置
        $where['classname']='IntegralWarn';//提醒
        if(IS_POST){
            $postdata=I('post.');
            if($postdata['status']==1){
               if(empty($postdata['cleardate']) || !str_exists($postdata['cleardate'],'-')){
                    $this->error('清零日不能为空或格式不正确');return;
               }
               $cleartime=date('Y').'-'.$postdata['cleardate'];
               $data['start_time']=NOW_TIME;
               $data['next_time']=strtotime($cleartime);
               $data['status']=1;
               if(!empty($postdata['commondate']) && str_exists($postdata['commondate'],'-')){
                   $commondate=date('Y').'-'.$postdata['commondate'];
                   $data2['start_time']=NOW_TIME;
                   $data2['next_time']=strtotime($commondate);
                   $data2['remark']=$postdata['points'];
                   $data2['status']=1;
               }else{
                $data2['status']=0;
               }
            }else{
                $data['status']=$data2['status']=0;
            }
            $mod->where($map)->save($data);
            $mod->where($where)->save($data2);
            $this->success('设置成功');return;
        }else{
            $set=$mod->where($map)->field(true)->find();
            $common=$mod->where($where)->field(true)->find();
            $info=array();
            $info['status']=intval($set['status']);
            $info['cleardate']=time_format($set['next_time'],'m-d');
            $info['points']=intval($common['remark']);
            if($common['status']){
                $info['commondate']=time_format($common['next_time'],'m-d');
            }else{
                $info['commondate']='';
            }
            $this->assign($info);
            $this->display();
        }
    }
    public function huaxiang(){
    	$uid = I("uid");
    	$member_mod = D('Member');
    	$info = $member_mod->field(true)->find($uid);
    	$where = $map = array();
    	$where['name'] = 'ATTRIBUTE';
    	$have = M("Config")->where($where)->field("id,name,value")->find();
    	$attr_list = json_decode($have['value'],true);
    	$map['uid'] = $uid;
    	foreach ($attr_list as $key => $value) {
	      $map['aid'] = $value['id'];
	      $attr_list[$key]['value'] = M("MemberAttribute")->where($map)->getField("content");
	      if($value['type'] == 'date' && $attr_list[$key]['value']){
		      $attr_list[$key]['value'] = date("Y-m-d",$attr_list[$key]['value']);
	      }
	      if(($value['type'] == 'radio') && $value['content']){
		      $attr_list[$key]['data'] = explode(",",$value['content']);
	      }
	      if($value['type'] == 'checkbox' && $value['content']){
		      $attr_list[$key]['data'] = explode(",",$attr_list[$key]['value']);
	      }
	      if($value['type'] == 'checkbox' && $attr_list[$key]['value']){
		      $attr_list[$key]['value'] = trim($attr_list[$key]['value'],',');
	      }
    	}unset($key,$value);
    	$this->assign("attr_list",$attr_list);
    	$this->assign("info",$info);

    	$con_where = $con_data = $data = array();
	$con_where['name'] = 'MEMBERATTRIBUTE';
	$con_have = M("Config")->where($con_where)->field("id,name,value")->find();
	if($con_have){
	    $con_data = unserialize($con_have['value']);
	    $data[1] = $con_data['real_name'];
	    $data[1]['name'] = "真实姓名";
	    $data[1]['field'] = "real_name";
	    $data[1]['type'] = "text";

	    $data[2] = $con_data['birthday'];
	    $data[2]['name'] = "生日";
	    $data[2]['field'] = "birthday";
	    $data[2]['type'] = "date";

	    $data[3] = $con_data['sex'];
	    $data[3]['name'] = "性别";
	    $data[3]['field'] = "sex";
	    $data[3]['type'] = "radio";

	    $data[4] = $con_data['idcard'];
	    $data[4]['name'] = "身份证号";
	    $data[4]['field'] = "idcard";
	    $data[4]['type'] = "text";

	    $data[5] = $con_data['address'];
	    $data[5]['name'] = "地区";
	    $data[5]['field'] = "address";
	    $data[5]['type'] = "radio";
	    $this->assign("con_data",$data);
	}

    	// 会员 行为
    	$this->action($uid);
    	// 会员信息
    	$this->cunsume($uid,$info['reg_time']);
        	$map = array();$map['id'] = $uid;
	  $label_ids = M('Member')->where($map)->getField('label_ids');
	  $label_ids_arr = array_filter(explode(',',$label_ids));
	  $this->assign('label_ids_arr',$label_ids_arr);

	  $this->assign('uid',$uid);
	  $this->label_list();
//	    上次购买信息
	$this->last_buy($uid);
	$this->display();
    }
/**
*会员属性
*显示该字段选项
*/
    public function search_attr(){
    	$postdata = I("param.");
    	$return = array('status'=>0,'msg'=>'');
    	if(empty($postdata['id'])){
    		$return['msg'] = "参数错误";
    		$this->ajaxReturn($return);
    	}
    	$member_mod = D('Member');
    	$info = $member_mod->field(true)->find($postdata['uid']);
    	$where = $map = $info = array();
    	$where['name'] = 'ATTRIBUTE';
    	$have = M("Config")->where($where)->field("id,name,value")->find();
    	$list = json_decode($have['value'],true);
    	$map['uid'] = $postdata['uid'];
    	$map['aid'] = $postdata['id'];
    	$content = M("MemberAttribute")->where($map)->getField("content");
    	$content = explode(",",$content);
    	$text = explode(",",$list[$postdata['id']]['content']);
    	if($text){
    		foreach ($text as $key => $value) {
    			if($value){
    				$info[$key]['name'] = $value;
	    			$info[$key]['is_show'] = 0;
    			}
	    	}unset($key,$value);
	    	foreach ($content as $key => $value) {
	    		if($value){
		    		$k = array_search($value, $text);
		    		if(in_array($value, $text)){
		    			$info[$k]['is_show'] = 1;
		    		}else{
		    			$info[$k]['is_show'] = 0;
		    		}
		    	}
	    	}unset($key,$value);
    	}
    	$return['status'] = 1;
    	$return['data'] = $info;
    	$return['count'] = count($info);
    	$this->ajaxReturn($return);
    }
/**
*会员属性
*添加会员属性
*/
    public function add_member_attribute(){
    	$postdata = I("param.");
    	$return = array('status'=>0,'msg'=>'');
    	if(empty($postdata['uid'])){
    		$return['msg'] = "参数错误";
    		$this->ajaxReturn($return);
    	}
    	$where = $data = $map = array();
    	$map['name'] = 'ATTRIBUTE';
    	$c_have = M("Config")->where($map)->getField("value");
    	$c_list = json_decode($c_have,true);
    	
    	$where['uid'] = $postdata['uid'];
    	foreach ($postdata['name'] as $key => $value) {
    		if($value){
    			$where['aid'] = $key;
    			$where['uid'] = $postdata['uid'];
	    		$have = M("MemberAttribute")->where($where)->count();
	    		// $value = ltrim($value, ",");
	    		if($c_list[$key]['type'] == 'date'){
	    			$value = strtotime($value);
	    		}
	    		if($have){
	    			$save_data = array();
	    			$save_data['content'] = $value;
	    			M("MemberAttribute")->where($where)->save($save_data);
	    		}else{
	    			$add_data = array();
	    			$add_data['uid'] = $postdata['uid'];
	    			$add_data['aid'] = $key;
	    			$add_data['content'] = $value;
	    			M("MemberAttribute")->add($add_data);
	    		}
	    		if($c_list[$key]['type'] == 'date'){
	    			$value = date('Y-m-d',$value);
	    		}
	    		if($c_list[$key]['type'] == 'checkbox'){
	    			$value = trim($value, ",");
	    		}
	    		$data[] = array('id'=>$key,'name'=>$value);
    		}
    	}unset($key,$value);
    	$postdata['id'] = $postdata['uid'];
    	unset($postdata['name']);unset($postdata['uid']);
    	$member_mod = D("Member");
    	$member_mod->create($postdata);
        $member_mod->save();
        if($postdata['sex'] == 1){$postdata['sex'] = '男';}
        elseif($postdata['sex'] == 2){$postdata['sex'] = '女';}
        elseif($postdata['sex'] == 0){$postdata['sex'] = '未标记';}
        $return['post_data']['real_name'] = empty($postdata['real_name'])?'暂无':$postdata['real_name'];
        $return['post_data']['birthday'] = empty($postdata['birthday'])?'暂无':$postdata['birthday'];
        $return['post_data']['idcard'] = empty($postdata['idcard'])?'暂无':$postdata['idcard'];
        $return['post_data']['sex'] = $postdata['sex'];
        $return['post_data']['address'] = idtoname($postdata['province'],"Area")." ".idtoname($postdata['city_id'],"Area")." ".idtoname($postdata['district'],"Area");
    	$return['status'] = 1;
    	$return['data'] = $data;
    	$this->ajaxReturn($return);
    }
    /**
    *会员属性
	*显示字段
    */
    public function attribute(){
    	$attr_data = require_once ROOT_PATH."/Public/data/attr_data.php";
    	$keyword = I("param.keyword");
    	if($keyword){
    		$data = array();
    		foreach ($attr_data as $key => $value) {
    			foreach ($value['son'] as $k => $v) {
					if(strpos($v['name'],$keyword) !== false ){
						$v['id'] = $k;
						$data[] = $v;
					}
    			}unset($k,$v);
    		}unset($key,$value);
    		$return['count'] = count($data);
    		$return['list'] = $data;
    		$this->ajaxReturn($return);
    	}else{
    		$con_where = $con_data = array();
    		$con_where['name'] = 'MEMBERATTRIBUTE';
    		$con_have = M("Config")->where($con_where)->field("id,name,value")->find();
    		if(!$con_have){
    			$con_data['real_name']['is_member'] = 1;
    			$con_data['real_name']['is_shop'] = 1;
    			$con_data['birthday']['is_member'] = 1;
    			$con_data['birthday']['is_shop'] = 1;
    			$con_data['sex']['is_member'] = 1;
    			$con_data['sex']['is_shop'] = 1;
    			$con_data['idcard']['is_member'] = 1;
    			$con_data['idcard']['is_shop'] = 1;
    			$con_data['address']['is_member'] = 1;
    			$con_data['address']['is_shop'] = 1;
    			$add_data['value'] = serialize($con_data);
	    		$add_data['name'] = 'MEMBERATTRIBUTE';
	    		$add_data['status'] = 1;
	    		$add_data['title'] = "会员注册必填属性";
	    		$res = M("Config")->add($add_data);
    		}
    		$count = 0;
	    	foreach ($attr_data as $key => $value) {
	    		$count += count($value['son']);
	    	}unset($key,$value);
	    	$where['name'] = 'ATTRIBUTE';
	    	$have = M("Config")->where($where)->getField("value");
	    	$have_data = json_decode($have,true);
	    	$this->assign('attr_data',$attr_data);
	    	$this->assign('have_data',$have_data);
	    	$this->assign('count',$count);
	    	$this->assign('have_count',count($have_data));
	    	$this->display();
    	}
    }
    /**
    *	会员属性
	*	提交添加修改的字段
    */
    public function update_attribute(){
    	$postdata = I("param.");
    	$return = array('status'=>0,'msg'=>'');
    	if($postdata['check_ids']){
    		$attr_data = require_once ROOT_PATH."/Public/data/attr_data.php";
    		$where = $data = $have_data = $save_data = $add_data = array();
    		$where['name'] = 'ATTRIBUTE';
    		$have = M("Config")->where($where)->field("id,name,value")->find();
    		if($have){
    			$have_data = json_decode($have['value'],true);
				foreach ($postdata['check_ids'] as $key => $value) {
					if($have_data[$value]){
						$data[$value] = $have_data[$value];
					}else{
						$data[$value]['id'] = $value;
						$data[$value]['pid'] = $postdata['check_pids'][$key];
						$data[$value]['type'] = $attr_data[$postdata['check_pids'][$key]]['son'][$value]['type'];
						$data[$value]['name'] = $attr_data[$postdata['check_pids'][$key]]['son'][$value]['name'];
						$data[$value]['is_member'] = 1;
						$data[$value]['is_shop'] = 1;
						$data[$value]['content'] = '';
					}
				}unset($key,$value);
				$save_data['value'] = json_encode($data);
				$res = M("Config")->where($where)->save($save_data);
    		}else{  //需要添加
    			foreach ($postdata['check_ids'] as $key => $value) {
					$data[$value]['id'] = $value;
					$data[$value]['pid'] = $postdata['check_pids'][$key];
					$data[$value]['type'] = $attr_data[$postdata['check_pids'][$key]]['son'][$value]['type'];
					$data[$value]['name'] = $attr_data[$postdata['check_pids'][$key]]['son'][$value]['name'];
					$data[$value]['is_member'] = 1;
					$data[$value]['is_shop'] = 1;
					$data[$value]['content'] = '';
	    		}unset($key,$value);
	    		$add_data['value'] = json_encode($data);
	    		$add_data['name'] = 'ATTRIBUTE';
	    		$add_data['status'] = 1;
	    		$add_data['title'] = "会员属性";
	    		$res = M("Config")->add($add_data);
    		}
    		if($res){
    			$return['status'] = 1;
    			$return['msg'] = '提交成功!';
    		}else{
    			$return['msg'] = '提交失败!';
    		}
    	}else{
    		$return['msg'] = "请选择要添加的字段";
    	}
    	$this->ajaxReturn($return);
    }
    /**
    *	会员属性
	*	已添加字段列表
    */
    public function attribute_list(){
    	$attr_type = array('radio'=>'单选',"text"=>'文本',"checkbox"=>'多选',"date"=>"时间");
    	$where = array();
    	$where['name'] = 'ATTRIBUTE';
    	$have = M("Config")->where($where)->field("id,name,value")->find();
    	$list = json_decode($have['value'],true);
    	$this->assign("list",$list);
    	$this->assign("attr_type",$attr_type);
    	$con_where = $con_data = $data = array();
		$con_where['name'] = 'MEMBERATTRIBUTE';
		$con_have = M("Config")->where($con_where)->field("id,name,value")->find();
		if($con_have){
			$con_data = unserialize($con_have['value']);
			$data[1] = $con_data['real_name'];
			$data[1]['name'] = "真实姓名";
			$data[1]['field'] = "real_name";
			$data[1]['type'] = "text";

			$data[2] = $con_data['birthday'];
			$data[2]['name'] = "生日";
			$data[2]['field'] = "birthday";
			$data[2]['type'] = "date";

			$data[3] = $con_data['sex'];
			$data[3]['name'] = "性别";
			$data[3]['field'] = "sex";
			$data[3]['type'] = "radio";

			$data[4] = $con_data['idcard'];
			$data[4]['name'] = "身份证号";
			$data[4]['field'] = "idcard";
			$data[4]['type'] = "text";

			$data[5] = $con_data['address'];
			$data[5]['name'] = "地区";
			$data[5]['field'] = "address";
			$data[5]['type'] = "radio";
			$this->assign("data",$data);
		}
    	$this->display();
    }
    /**
    *	会员属性
	*	编辑字段
    */
    public function attribute_add(){
    	$attr_type = array('radio'=>'单选',"text"=>'文本',"checkbox"=>'多选',"date"=>"时间");
    	$postdata = I("param.");
    	$where = array();
    	$where['name'] = 'ATTRIBUTE';
    	$have = M("Config")->where($where)->field("id,name,value")->find();
	    $list = $info = json_decode($have['value'],true);
    	if(empty($postdata['save'])){
	    	$content = $list[$postdata['id']]['content'];
	    	$this->assign("content",$content);
	    	$this->assign($postdata);
	    	$this->assign("attr_type",$attr_type);
	    	$this->display();
    	}else{
    		$content= preg_replace("/(\n)|(\s)|(\t)|(\')|(')|(，)/" ,',' ,$postdata['content']); 
			$data = array_unique(array_filter(explode(",",$content)));
			$list[$postdata['id']]['content'] = implode(",",$data);
			if($info[$postdata['id']]['content'] == $list[$postdata['id']]['content']){
				$this->error("编辑失败,没有做任何修改!");exit;
			}
			$save = array();
			$save['value'] = json_encode($list);
			$res = M("Config")->where($where)->save($save);
			if($res)$this->success('编辑成功');
			else $this->error("编辑失败");
    	}
    }
    /**
    *	会员属性
	*	编辑字段  会员中心  商家中心填写
    */
    public function update_attrstatus(){
    	$postdata = I("param.");
    	$return = array('status'=>0,'msg'=>'');
    	if($postdata['lei'] == 1){
    		$con_where = $con_data = $data = array();
			$con_where['name'] = 'MEMBERATTRIBUTE';
			$con_have = M("Config")->where($con_where)->field("id,name,value")->find();
			$con_data = unserialize($con_have['value']);
			if($postdata['type'] == 'is_member'){
				if($con_data[$postdata['id']]['is_member'] == 0)$is_member = 1;
				else $is_member = 0;
				$return['info'] = $con_data[$postdata['id']]['is_member'] = $is_member;
			}else if($postdata['type'] == 'is_shop'){
		    	if($con_data[$postdata['id']]['is_shop'] == 0)$is_shop = 1;
		    	else $is_shop = 0;
		    	$return['info'] = $con_data[$postdata['id']]['is_shop'] = $is_shop;
		    }
		    $save['value'] = serialize($con_data);
		    $res = M("Config")->where($con_where)->save($save);
    	}else{
    		$where = $save = array();
	    	$where['name'] = 'ATTRIBUTE';
	    	$have = M("Config")->where($where)->field("id,name,value")->find();
		    $list = json_decode($have['value'],true);
		    if($postdata['type'] == 'is_member'){
		    	if($list[$postdata['id']]['is_member'] == 0)$is_member = 1;
		    	else $is_member = 0;
		    	$return['info'] = $list[$postdata['id']]['is_member'] = $is_member;
		    }else if($postdata['type'] == 'is_shop'){
		    	if($list[$postdata['id']]['is_shop'] == 0)$is_shop = 1;
		    	else $is_shop = 0;
		    	$return['info'] = $list[$postdata['id']]['is_shop'] = $is_shop;
		    }
		    $save['value'] = json_encode($list);
		    $res = M("Config")->where($where)->save($save);
    	}
	    if($res)$return['status'] = 1;
	    $this->ajaxReturn($return);
    }
    /**
    *	会员属性
	*	删除启用字段
    */
    public function update_delete(){
    	$postdata = I("param.");
    	$where = array();
    	$where['name'] = 'ATTRIBUTE';
    	$have = M("Config")->where($where)->field("id,name,value")->find();
	    $list = json_decode($have['value'],true);
	    unset($list[$postdata['id']]);
	    $save['value'] = json_encode($list);
	    $res = M("Config")->where($where)->save($save);
	    if($res)$this->success('删除成功');
		else $this->error("删除失败");
    }
	/**
    *	会员画像
    */
	public function member_portrait(){
        $postdata=I('param.');
        $keyword = $postdata['keyword'];
        $map=array();
		if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['username']=array('like','%'.$keyword.'%');
            $whereor['real_name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
		}
        if(!empty($postdata['rank_id'])){
           $map['rank_id']=$postdata['rank_id'];
        }
		if(!empty($postdata['mobile']))$map['mobile'] = array('like','%'.$postdata['mobile'].'%');
		$map['is_tmp'] = 0;
		
		$list = $this->lists('Member',$map);
        $this->assign('list', $list);$this->assign($postdata);
		$this->label_list();
		$this->getGroup(1);
		$this->display();
	}
	public function label_list(){
		$map = array();$map['pid'] = 40;
		$label_list = M('Type')->where($map)->field('id,name')->select();
		$this->assign('label_list',$label_list);
	}
	public function sub_delete(){
		$return = array();$return['status'] = 0;
		$post = I('param.');
		$label_id = $post['label_id'];
		if($label_id){
			$str_label = ','.$label_id.',';
			$ret = M('Member')->execute("update __MEMBER__ set label_ids = replace (`label_ids`,'".$str_label."',',') where label_ids like '%".$str_label."%'");
			$map = array();$map['id'] = $label_id;$map['pid'] = 40;
			$res = M('Type')->where($map)->delete();
			if($res){
				$return['status'] = 1;
			}else{
				$return['msg'] = '删除失败！';
			}
		}else{
			$return['msg'] = '参数错误！';
		}
		$this->ajaxReturn($return);
	}
	/*public function member_label(){
		$uid = I('uid');
		$map = array();$map['id'] = $uid;
		$label_ids = M('Member')->where($map)->getField('label_ids');
		$label_ids_arr = array_filter(explode(',',$label_ids));
		$this->assign('label_ids_arr',$label_ids_arr);
		
		$this->assign('uid',$uid);
		$this->label_list();
    	$this->display();
    }*/
	public function add_label(){
		$return = array();
		$post = I('param.');
		$new_label = $post['new_label'];
		$new_label_arr = array_filter(explode(' ',$new_label));
		if($new_label_arr){
			$save_data = array();
			$ret = 1;$html = '';

			foreach($new_label_arr as $v){
				$save_data['pid'] = 40;
				$save_data['sort'] = 0;
				$save_data['status'] = 1;
				$save_data['name'] = $save_data['temp'] = $v;
				$id = M('Type')->add($save_data);
				if(!$id){$ret = 0;}
				else{
					$html .= '<li onclick="add_member(this,'.$id.')">'.$v.'</li>';
				}
			}
			if($ret){
				$return['status'] = 1;
				$return['html'] = $html;
			}else{
				$return['status'] = 0;
			}
		}
		$this->ajaxReturn($return);
	}
	public function save_labels(){
		$return = array();
		$post = I('param.');
		$map = array();$map['id'] = $post['uid'];
		$label_ids = M('Member')->where($map)->getField('label_ids');
		$new_label_ids = ',';
		$new_ids = $post['label_id'].',';
		if($label_ids){
			if(strpos($label_ids,','.$new_ids) !== false){
				$label_ids = str_replace(','.$new_ids,',',$label_ids);
			}else{
				$label_ids .= $new_ids;
			}
			$new_label_ids = $label_ids;
		}else{
			$new_label_ids .= $new_ids;
		}
		if($new_label_ids){
			$save_label_ids = array();$save_label_ids['label_ids'] = $new_label_ids;
			$ret = M('Member')->where($map)->save($save_label_ids);
			if($ret){
				$return['status'] = 1;
			}else{
				$return['status'] = 0;
			}
		}
		$this->ajaxReturn($return);
	}
	public function action($uid){
		$ec = new \Common\Vendor\Echarts();
		// 商品分类分析
		$result=$this->catelist($uid);
        $catecount = array(
		    'title'=>array(
		        'text'=>'分类统计',
		        'x'=>'center'
		    ),
            "legend"=>array('orient'=>'vertical','left'=>'left','data'=>$result['catename']),
            "series"=>array(
                array("name"=>"分类分析",
                	"type"=>"pie",
                    'radius'=>'50%',
                    "data"=>$result['data'],
                ),
            ),
        );
        $this->assign('cate_count',$ec->pie_show('cate_count', $catecount,'pie',''));
		$now_time=strtotime(date('Y-m-d',NOW_TIME));
		// 消费时段统计
		$end_time=strtotime($now_time)+86399;
		$map=array();
		$map['type'] = array('in','1,6,13,14');
        $map['pay_status'] = 3;
        $map['uid']=$uid;
        $countz = M('OrderInfo')->where($map)->count();
        $count = M('OrderInfo')->where($map)->field("count(id) num,addtime as l_month")->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%k')")->select();
        foreach($count as $value){
            $counts[date('G',$value['l_month'])] = $value['num'];
        }
        $count1=$count2=$count3=$count4=$count5=$count6=0;
        for($i=0;$i<24;$i++){
        	if($counts[$i]){
        		if($i<4 && $i>=0){
	        		$count1+=$counts[$i];
	        	}
	        	if($i<8 && $i>=3){
	        		$count2+=$counts[$i];
	        	}
	        	if($i<12 && $i>=8){
	        		$count3+=$counts[$i];
	        	}
	        	if($i<16 && $i>=12){
	        		$count4+=$counts[$i];
	        	}
	        	if($i<20 && $i>=16){
	        		$count5+=$counts[$i];
	        	}
	        	if($i<24 && $i>=20){
	        		$count6+=$counts[$i];
	        	}
        	}
        	
        }
        if($countz>0){
        	$time=array('00:00-03:59','04:00-07:59','08:00-11:59','12:00-15:59','16:00-19:59','20:00-23:59');
        	$datas=array(
                        array("value"=>$count1,"name"=>"00:00-03:59"),
                        array("value"=>$count2,"name"=>"04:00-07:59"),
                        array("value"=>$count3,"name"=>"08:00-11:59"),
                        array("value"=>$count4,"name"=>"12:00-15:59"),
                        array("value"=>$count5,"name"=>"16:00-19:59"),
                        array("value"=>$count6,"name"=>"20:00-23:59"),
                    );
        	if($count1==0){unset($datas[0]);unset($time[0]);}
        	if($count2==0){unset($datas[1]);unset($time[1]);}if($count3==0){unset($datas[2]);unset($time[2]);}
    		if($count4==0){unset($datas[3]);unset($time[3]);}if($count5==0){unset($datas[4]);unset($time[4]);}if($count6==0){unset($datas[5]);unset($time[5]);}
        	$datas=array_merge($datas);$time=array_merge($time);
        }else{
        	$time=array();
        	$datas=array();
        }
        $pay_style_count = array(
        	'title'=>array(
		        'text'=>'消费时段统计',
		        'x'=>'center'
		    ),
            "legend"=>array('data'=>$time),
            "series"=>array(
                array("name"=>"消费时段统计","type"=>"pie",
                    'radius'=>'50%',
                    "data"=>$datas,
                ),
            ),
        );
        $this->assign('Area_count_pay',$ec->pie_show('Area_count_pay',$pay_style_count,'pie',''));


		$map=array();
		$map['uid']=$uid;
		$map['type'] = array('in','6,13,14');
		$map['pay_status'] = 3;
		$map['status'] = 3;
		$order_ids = M('OrderInfo')->where($map)->getField('id',true);
        // 品牌排行
        if($order_ids){
			$map = array();
			$map['order_id'] = array('in',$order_ids);
        	$goods_ids=M('OrderGoods')->where($map)->getField('goods_id',true);
        	$b_map=array();
        	if($goods_ids){	
	        	$b_map['g.id']=array('in',$goods_ids);
				$b_map['og.order_id'] = array('in',$order_ids);
				$b_map['g.brand_id'] = array('gt',0);
	        	$brand_ids=M('Goods')->alias('g')->JOIN('__ORDER_GOODS__ og on og.goods_id = g.id')->where($b_map)->group('g.brand_id')->field('g.id,g.brand_id,sum(og.goods_number) as num')->order('sum(og.goods_number) desc')->limit(10)->select();
        	}
        }
        $brand_name=$brand_data=array();
        if($brand_ids){
        	foreach ($brand_ids as $kb => $vb) {
        		$bname=idtoname($vb['brand_id'],'Brand','brand_name','id',false);
        		$brand_name[]=$bname;
        		$brand_data[]=array('value'=>intval($vb['num']),'name'=>$bname);
        	}
        }

        $brandcount = array(
		     'title'=>array(
		        'text'=>'品牌排行Top10',
		        'x'=>'center'
		    ),
            "legend"=>array('orient'=>'vertical','left'=>'left','data'=>$brand_name),
            "series"=>array(
                array("name"=>"品牌排行Top10",
                	"type"=>"pie",
                    'radius'=>'50%',
                    "data"=>$brand_data,
                ),
            ),
        );
        $this->assign('brand_count',$ec->pie_show('brand_count', $brandcount,'pie',''));



        // 单品购买排行
        $goods_all=0;
        if(!empty($order_ids)){
	    $map = array();
	    $map['order_id'] = array('in',$order_ids);
	    $goods_all=M('OrderGoods')->where($map)->sum('goods_number');
	    $map['group'] = 'goods_id';
	    $order = 'sum(goods_number) desc';
	    $field = 'sum(goods_number) as num,goods_id,goods_sn,goods_name';
	    $size = '10';
	    $list = page_list('OrderGoods',$map,$order,$field,$size);
        }
        $this->assign($list);
        $this->assign('goodsall',intval($goods_all));
	}
    public function cunsume($uid,$reg_time){
        $map=array();
        $map['type'] = array('in','1,6,13,14');
        $map['pay_status'] = 3;
        $map['uid']=$uid;
        $map['status']=3;
        $order_amount = M('OrderInfo')->where($map)->field("count(id) as num ,sum(order_amount) as money")->find();
        $this->assign('lj_xf',$order_amount['money']?$order_amount['money']:0);//累计消费
        $av_money=floatval($order_amount['money'])/intval($order_amount['num']);
        $this->assign('av_money',round($av_money,2));//平均每单
        //该会员 入驻天数
        $day = intval((NOW_TIME-$reg_time)/24/3600);
        $av_day = number_format($order_amount['money']/$day,2);
        $this->assign('av_day',$av_day);//平均每天消费
        $where=array();
        $where['status']=0;
        $where['uid']=$uid;
        $couponc = M('CouponsGet')->where($where)->count();
        $this->assign('couponc',$couponc);//当前券数
        $where=array();
        $where['status']=1;
        $where['uid']=$uid;
        $coupon = M('CouponsGet')->where($where)->count();
        $this->assign('coupon',$coupon);//共使用券
    }
    public function catelist($uid){
        $return=$cate_count=$data=$og_map=$map=$map_c=$g_map=$catename=array();
        $map_c['status']=1;
        $map_c['pid']=0;
        $carids = M('PurchaseCategory')->where($map_c)->field('id,name')->select();
        unset($map_c['pid']);
        if($carids){
        	$map['type'] = array('in','1,6,13,14');
	        $map['pay_status'] = 3;
	        $map['uid']=$uid;
	        $orderid=M('OrderInfo')->where($map)->getField("id",true);
	        if($orderid){
	            foreach($carids as $k=>$v){
	            	$catename[]=$v['name'];
	                $map_c['pid']=$v['id'];
	                $child_catid = M('PurchaseCategory')->where($map_c)->getField('id',true);
	                if($child_catid){
	                	$child_catid[]=$v['id'];
	                	$g_map['cat_id']=array('in',$child_catid);
	                }else{
	                	$g_map['cat_id']=$v['id'];
	                }
	                $goods_ids = M('Goods')->where($g_map)->getField('id',true);
	                if($goods_ids){
		                $og_map['goods_id']=array('in',$goods_ids);
		                $og_map['order_id']=array('in',$orderid);
		                $goods_num=M('OrderGoods')->where($og_map)->sum('goods_number');
		                $goodsnum[]=intval($goods_num);
	                }else{
	                	$goodsnum[]=0;
	                }
	            }
	        }
        }
        $allnum=array_sum($goodsnum);
        if(count($catename) > 0){
        	foreach ($catename as $key => $value) {
        		$data[]=array("value"=>$goodsnum[$key],"name"=>$value);
        	}
        }
        $return['data']=$data;
		$return['catename']=$catename;
		return $return;
	}
	public function last_buy($uid){
		$map_og=$map=array();
		$map['uid']=$uid;
		$map['type']=array('in','6,13,14');
		$map['status']=array('in','1,2,3,6,8');
		$map['is_delete']=0;
		$order_info=M('OrderInfo')->where($map)->order('id desc')->find();
		$map_og['order_id']=$order_info['id'];
		$order_goods=M('OrderGoods')->where($map_og)->getField('goods_name',true);
		$this->assign($order_info);
		$goods_name=implode(',', $order_goods);
		$this->assign('goods_name',$goods_name);
	}
	public function aa(){
		$postdata['shop_id']=1;
		$res=D('Common/Statistics')->index($postdata);
	}
	/**
     * 搜索会员
     */
    public function search_member()
    {
        $return = array();
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
		$map=array();
		$map['status'] = 1;
        if (is_numeric($keyword)) {
            $map['mobile'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $map['username'] = array('like', '%' . (string)$keyword . '%');
        }
        $brands = M('Member')->where($map)->field('id,username')->order('id asc')->select();
        $options = "<option value=''>请选择</option>";
        foreach ($brands as $k => $v) {
            $options .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
        }
        $return['status'] = 1;
        $return['options'] = $options;
        $this->ajaxReturn($return);
    }
}
?>