<?php
/**
 * 店铺中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author lss <lss@qq.com>
 */

namespace Shop\Controller;
use Think\Controller;
class MemberCardController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
        $shops_info=session('shops_info');
        if(empty($shops_info['id']))$this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
		$this->mendian();
		$constellationData = array('白羊座'=>'白羊座','金牛座'=>'金牛座','双子座'=>'双子座','巨蟹座'=>'巨蟹座','狮子座'=>'狮子座','处女座'=>'处女座','天枰座'=>'天枰座','射手座'=>'射手座','摩羯座'=>'摩羯座','水瓶座'=>'水瓶座','双鱼座'=>'双鱼座','天蝎座'=>'天蝎座');
		$this->assign('constellationData',$constellationData);
    }
   
    public function index(){
    	$auth_code = 'member_list';
		$ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);die;}

		$shops_info=session('shops_info');
        $tabid=I('param.tabid');
		$postdata = I('param.');
		$keyword = $postdata['keyword'];
		$map=$g_map=$where_or=$whereor=array();$shop_id=intval($shops_info['shop_id']);
		if(!empty($keyword)&&$tabid != 'fans'){
            $map['id|real_name|mobile|card_sn']=array('like','%'.$keyword.'%');
		}
		if(!empty($postdata['rank_id'])){$map['rank_id']=$postdata['rank_id'];}
		$map['status']=array(array('GT',0));
        if(empty($tabid)){//会员
            if(!empty($postdata['reg_from']))$map['card_time'][]=array('EGT',strtotime($postdata['reg_from']));
		    if(!empty($postdata['reg_to']))$map['card_time'][]=array('elt',strtotime($postdata['reg_to']));
            $this->getGroup(1);	
            $map['is_tmp']=0;
        }   
		if($tabid == 'member'){//顾客
            //$map['mobile']=array('neq','');
			$map['is_follow']=0;
		}
		if($tabid == 'fans'){//粉丝
			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(!empty($keyword)){
	            unset($map['id|real_name|mobile|card_sn']);
	            $map['wxid|username']=array('like','%'.$keyword.'%');
			}
			$map['wxid']=array('neq','');
			$map['is_follow']=1;
			// 粉丝独立
			$auth_code = 'fans';
			$ret=D('Shop/Shops')->shop_option(MID,$auth_code);
			if($ret['status']==1){
				$map['_string']="user_shop = ".MID;
			}
		}
        $is_share_user=idtoname($shop_id,'Shops','is_share_user');
        if(empty($is_share_user)){//不共享会员
            $c_map=$customer=array();
            $c_map['shop_id'] = $shop_id;
            $customer = M('ShopsCustomer')->cache(true)->where($c_map)->getField('user_id',true);
            if(empty($customer)){//无顾客
                $map['user_shop']=$shop_id;
            }else{
                $where=array();
                $where['user_shop']=$shop_id;
                $where['id']  = array('in',$customer);
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }else{//共享会员
            $smap=array();$cachetime=60*60*24*7;
            $smap['is_share_user']=0;                
            $noshareshopids=M('Shops')->where($smap)->cache(true,$cachetime)->getField('id',true);
            if(!empty($noshareshopids)){
                $map['user_shop'] = array('notin',$noshareshopids);
            }
        }

        if(I('print')){
			$list=M('Member')->where($map)->field(true)->select();
			$this->member_export($list);
		}
		$list = $this->lists('Member',$map);
		//会员隐私
			$ys=idtoname(MID,'Shops','is_hide_phone');
				foreach ($list as $k => $val) {
					$username=show_user_name($val['id']);
					if($ys){
						if(strlen($username)==11){$list[$k]['username_mobile']=str_cutmobile($username);}
						else{$list[$k]['username_mobile']=$username;}
						$list[$k]['mobile']=str_cutmobile($list[$k]['mobile']);
					}else{
						$list[$k]['username_mobile']=$username;
					}
				}

		// 
		$this->assign('list',$list);
		$this->assign($postdata);
		$this->assign('tabid',$tabid);
		$this->assign('title_ass','会员');
		$this->display($tabid);

        
    }
    /**
     * 导出商品
     */
    public function member_export($list)

    {
		$ys=idtoname(MID,'Shops','is_hide_phone');
        $title = array('ID','名称','卡号', '手机号', '等级', '资金', '积分', '开卡时间', '最近登陆');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
			$username=show_user_name($order_info['infos']['uid']);
			if($ys&& strlen($username)==11){
	            $data[$k][] = str_cutmobile($v['username']);
			}else{
	            $data[$k][] = $v['username'];
			}
            $data[$k][] = $v['card_sn'];
            if($ys){
            	$data[$k][] = str_cutmobile($v['mobile']);
            }else{
            	$data[$k][] = $v['mobile'];
            }
            $data[$k][] = idtoname($v['rank_id'], 'MemberRank', 'name');
            $data[$k][] = $v['money'];
            $data[$k][] = $v['usepoints'];
            $data[$k][] = time_format($v['card_time']);
            $data[$k][] = time_format($v['last_login']);

        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;
    }


    //套餐发放
    public function package_send(){
        $postdata = I('param.');
        $where = array();
        $keyword = $postdata['keyword'];
        if(!empty($keyword)){
            $whereor['member_card']=array('like','%'.$keyword.'%');
            $whereor['member_name']=array('like','%'.$keyword.'%');
            $whereor['member_mobile']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $where['_complex'] = $whereor;
		}
        if(!empty($postdata['reg_from']))$where['add_time'][]=array('EGT',strtotime($postdata['reg_from']));
		if(!empty($postdata['reg_to']))$where['add_time'][]=array('elt',strtotime($postdata['reg_to']));
        if(!$postdata['package_id'])$where['package_id'] = array('eq',$postdata['package_id']);
        $where['send_shop'] = MID;
        $list = $this->lists('PackagesendLog',$where);
        $pscount = M('PackagesendLog')->where($where)->count();
        $this->assign('pscount',$pscount);
        $this->assign('list',$list);
		$this->assign($postdata);
        $this->assign('p_log',$p_log);
    	$map = array();
        $map['shop_ids'] = ','.MID.',';
		$map['status'] = 1;
        $map['goods_type'] = 6;
        $map['is_delete'] = 0;
		$packageData = M('Goods')->where($map)->field('id,goods_name,shop_price')->select();
		foreach ($packageData as $v) {
			$newpackageData[$v['id']] = $v['goods_name']."(".$v['shop_price']."元)";
		}$packageData=$newpackageData;
		$this->assign('packageData',$packageData);
		$this->display();
    }
    public function get_pdata(){
    	$id = I('param.id');
		$return['status'] = 0;
		
		if(!$id){
			$return['info'] = '请选择套餐';
			$this->ajaxReturn($return);
		}
		$map['id'] = $id;
		$info = M('Package')->field(true)->where($map)->find();
		if($info){
			$info['service'] = '';
			$info['contain_service'] = json_decode($info['contain_service'],true);
			foreach ($info['contain_service'] as $key => $value) {
				$s_id = idtoname($key,'Goods','shop_id','id',false);
				if($s_id){
					$s_name = idtoname($s_id,'Shops','name','id',false);
				}else{
					$s_name = '全店通用';
				}
				
				$info['service'] .= idtoname($key,'Goods','goods_name','id',false).'('.$value.'次)--'.$s_name.' &nbsp;&nbsp;';
			}
			$return['status'] = 1;
			$return['data'] = $info;
		}else{
			$return['info'] = '操作错误';
		}
		$this->ajaxReturn($return);
    }
	/**
      *店铺开卡
      */
    public function open_card(){
		$tabid=I('param.tabid');
    	if(!empty($tabid)){
			$this->display($tabid);
		}else{
			$map['consumption_type'] = array('in','1,3');
			//时间限制
			$map['status'] = 1;
			$map['begin_time'] = array('LT',NOW_TIME);
	        $map['_string'] = 'end_time >'.NOW_TIME.' or end_time = 0';
			
			$act_list = M('ManypointsRule')->where($map)->field(true)->select();
			foreach($act_list as $k=>$v){
				if($v['consumption_type']!=3){
                    $give_num = $v['give_num'];
                    $act_list[$k]['give_num'] = $give_num;
                }
				if($v['give_type'] == 1){
					$act_list[$k]['give_type']='现金';
				}elseif($v['give_type'] == 2){
					$act_list[$k]['give_type']='倍积分';
				}
			}unset($k,$v);
			//$card_data = M('CardData')->cache(true)->field(true)->getField('option',true);
            //$this->assign('card_data',$card_data);
			$this->assign('act_list',$act_list);
			$this->display();
		}	
    }
	public function member_recharge(){
		$tabid=I('param.tabid');
		$this->assign('title_ass','会员充值');
    	if(!empty($tabid)){
    		$site_id=C('appid');//站点ID  
			$cz_url = U('Mobile/Withdrawals/index',array('site_id'=>$site_id),true,true);
            $cz_img_url = U('Home/Qrcode/index',array('data'=>urlencode($cz_url)),true,true);
        	$this->assign('tg_img_url',$cz_img_url);
			$this->display($tabid);
			// $this->display($tabid);
		}else{
			$map['consumption_type'] = array('in','1,3');
			//时间限制
			$map['status'] = 1;
			$map['begin_time'] = array('LT',NOW_TIME);
			$map['_string'] = 'end_time >'.NOW_TIME.' or end_time = 0';
			
			$act_list = M('ManypointsRule')->where($map)->field(true)->select();
			foreach($act_list as $k=>$v){
				if($v['consumption_type']!=3){
                    $give_num = $v['give_num'];
                    $act_list[$k]['give_num'] = $give_num;
                }
				if($v['give_type'] == 1){
					$act_list[$k]['give_type']='现金';
				}elseif($v['give_type'] == 2){
					$act_list[$k]['give_type']='倍积分';
				}
			}unset($k,$v);
			$this->assign('act_list',$act_list);
			$this->display();
		}	
    }
	/**
      *开卡申请
      */
	public function update_card(){
		 $postdata = I('param.');
         $data = D('Common/Shops')->update_card($postdata);
         $this->ajaxReturn($data);
	}
	/**
      *补卡申请
      */
	public function update_fill(){
		$postdata = I('param.');
        $data = D('Common/Shops')->update_fill($postdata);
		$this->ajaxReturn($data);
	}
	/**
      *会员充值
      */
	public function sub_recharge(){
		$postdata = I('param.');
        $data = D('Common/Shops')->sub_recharge($postdata);
		$this->ajaxReturn($data);
	}
	/**
      *套餐发放
      */
	public function sub_packagesend(){
		$postdata = I('param.');
        $data = D('Common/Shops')->sub_packagesend($postdata);
		$this->ajaxReturn($data);
	}
	//开卡验证会员
	public function is_member(){
		$mobile = I('param.mobile');
		$type = I('param.type');
		$return['status'] = 0;
		if(!$mobile){
			$return['info'] = '请输入手机号';
			$this->ajaxReturn($return);
		}
		if($type == 3 || $type == 5){
			$whereor['mobile']=array('eq',$mobile);
            $whereor['card_sn']=array('eq',$mobile);
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
		}else{
			$map['mobile'] = $mobile;
		}
		
		$info = M('Member')->field(true)->where($map)->find();
		if($info){
			// if($type != 1 && empty($info['card_sn'])){
			// 	$return['info'] = '该会员还未开卡';
			// 	$this->ajaxReturn($return);
			// }
			$o_map['uid'] = $info['id'];
			$o_map['pay_status'] = 3;
			$addtime = time_format(M('OrderInfo')->where($o_map)->getField('addtime'),'Y-m-d');
			$info['reg_time'] = time_format($info['reg_time'],'Y-m-d');
			if($info['sex']==1){$info['sex']='男';}elseif($info['sex']==2){$info['sex']='女';}else{$info['sex']='保密';}
			if($type == 2 || $type == 3){
				// $html = "<div>
				// 	<div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>昵称：".$info['nickname']."</span><span class='mr20'>生日：".$info['birthday']."</span><span class='mr20'>性别：".$info['sex']."</span><span class='mr20'>注册时间：".$info['reg_time']."</span></div></div></div></div><div><div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>积分：".$info['usepoints']."</span><span class='mr20'>余额：".$info['money']."</span><span class='mr20'>上次消费时间：".$addtime."</span><span class='mr20'>会员卡号：".$info['card_sn']."</span></div></div></div></div>";
				$html = "<div>
					<div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>姓名：".$info['real_name']."</span><span class='mr20'>级别：".idtoname($info['rank_id'],'MemberRank')."</span><span class='mr20'>手机：".$info['mobile']."</span><span class='mr20'>账户余额：".$info['money']."</span></div></div></div></div><div><div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>消费积分：".$info['usepoints']."</span></div></div></div></div>";
			}elseif($type == 5){
			     $html = "<span>昵称：".$info['nickname']."</span><span>生日：".$info['birthday']."</span><span>性别：".$info['sex']."</span><span>注册时间：".$info['reg_time']."</span><span>上次消费时间：".$addtime."</span><span>余额：".$info['money']."</span><span>积分：".$info['usepoints']."</span><span>会员卡号：".$info['card_sn']."</span>";
			}else{
				$html = "<div>
					<div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>昵称：".$info['nickname']."</span><span class='mr20'>生日：".$info['birthday']."</span><span class='mr20'>性别：".$info['sex']."</span><span class='mr20'>注册时间：".$info['reg_time']."</span></div></div></div></div><div><div class='clearfix attribute'><div class='f-l'><div class='dis_inlineblock kaika_width'><span class='mr20'>积分：".$info['usepoints']."</span><span class='mr20'>余额：".$info['money']."</span><span class='mr20'>上次消费时间：".$addtime."</span></div></div></div></div>";
			}
			
			$return['status'] = 1;
			$return['data'] = $html;
		}else{
			if($type == 1){
				$return['info'] = '不存在该手机号';
			}else{
				$return['info'] = '不存在该手机号或卡号会员';
			}
			
		}
		$this->ajaxReturn($return);
	}
	public function add(){
		$tabid=I('tabid');
        if (IS_POST) {
            $member_mod = M('Member');
            $postdata=I('post.');
			
            if (!isset($postdata['real_name']) || ($postdata['real_name'] == '')) {
                $this->error('真实姓名不能为空');
            }
            if (!isset($postdata['mobile']) || ($postdata['mobile'] == '')) {
                $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['real_name']=$postdata['real_name'];
            $result = $member_mod->where($where)->count();
            if ($result) {
                $this->error('会员' . $postdata['real_name'] . '已经存在');
            }
            $where_m['mobile']=$postdata['mobile'];
            $result = $member_mod->where($where_m)->count();
            if ($result) {
                $this->error('手机号' . $postdata['mobile'] . '的会员已经存在');
            }
            unset($postdata['repassword']);
            $postdata['salt'] = randStr();
            $postdata['reg_time'] = $postdata['last_login'] = NOW_TIME;
            $postdata['reg_ip'] = $postdata['last_ip'] = get_client_ip(1);
			$postdata['rank_id']=$postdata['rank_id'];
            $result=D('App/Member')->member_add($postdata);
            unset($postdata);
            if ($result['status']) {
                $this->success(L('DO_OK'), U('index'));
            } 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->assign('shop_id',MID);
            $this->assign('tplseo_title','添加新会员_'.$shops_info['name'].'_'.C('WEB_SITE_TITLE'));
            $this->assign('title_ass','会员');
    		if(!empty($tabid)){
    			$site_id=C('appid');//站点ID  
    			$url = U('Mobile/Login/register', array('site_id' => $site_id), true, true);
            	$tg_img_url = U('Home/Qrcode/index', array('data' => urlencode($url)), true, true);
            	$this->assign('tg_img_url',$tg_img_url);
				$this->display($tabid);
			}else{
				$this->display('edit');
			}            
        }
    }
    // 会员编辑查看
	public function edit(){
		$auth_code = 'member_list_edit';
		$ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}

		$id = I('id');
		$this->assign('tabid',I('tabid'));
        $member_mod = M('Member');
        if(I('tabid')){
        	$tabid=I('tabid');
        	if($tabid=='address'){
        		$this->address();
        	}elseif($tabid=='collect'){
        		$this->collect();
        	}else{
        		$this->error('参数错误');
        	}
        	$this->display($tabid);
        	
        }else{
        	if (IS_POST) {

	            $postdata=I('post.');
	            $map=array();
	            $map['id']=array('neq',$id);
	            $map['username']=$postdata['username'];
	            if(strpos('****',$postdata['username'])!==false){
	            	$postdata['username']='';
	            }
	            $count = $member_mod->where($map)->count();
	            if ($count > 0) {
	                $this->error('用户名已经存在！');
	            }
	            $adminsalt = $member_mod->where("username='" . $postdata['username'] . "'")->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']) {
	                $postdata['paypassword'] = creatpwd($postdata['paypassword'],'HANCHAO'.$adminsalt);
	            } else {
	                unset($postdata['paypassword']);
	            }
	            unset($postdata['repassword']);
	            $postdata['id']=$id;
	            if(strpos('***',$postdata['mobile'])!==false){
	            	unset($postdata['mobile']);
	            }
	            $result=D('App/Member')->member_add($postdata);
	            unset($postdata);
	            if ($result['status']&&$result['status']==1) {
	                $this->success(L('DO_OK'), '', '', 'edit');
	            } else {
	            	if($result['msg'])$this->error($result['msg']);
	            	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);
	            //会员隐私
					$ys=idtoname(MID,'Shops','is_hide_phone');
					if($ys){$info['mobile']=str_cutmobile($info['mobile']);}

					$username=show_user_name($id);
					if($ys&& strlen($username)==11){
			            $info['username'] = str_cutmobile($username);
					}else{
						$info['username'] = $username;
					}
					
				// 
				$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('shop_id',MID);
				$this->assign('daogou_arr', $daogou_arr);
				$this->assign('tplseo_title','会员编辑_'.$shops_info['name'].'_'.C('WEB_SITE_TITLE'));
	            $this->assign($info);
	            $this->getGroup(1);
	            $this->getShops(1);
	            // 属性开始


	            // 属性结束
	            $this->display();
	        }
        }
        
	}
	
	/**
	*用户地址
	*/
	public function address(){
		$name = "MemberAddress";
        $map=array();
        $uid=trim(I('param.id'));
        $keyword=trim(I('param.keyword'));
        if($uid)$map['uid']=$uid;
        if($keyword){            
            $whereor['consignee']=array('like','%'.$keyword.'%');
            $whereor['address']=array('like','%'.$keyword.'%');
            $whereor['tel']=array('like','%'.$keyword.'%');
            $whereor['mobile']=array('like','%'.$keyword.'%');
            $whereor['sign_building']=array('like','%'.$keyword.'%');
            $whereor['best_time']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
        }        
        $list = $this->lists($name,$map);
        $this->assign('list', $list);
		$this->assign('id', $uid);
        // $this->display();
	}
	public function delete_address(){
		$id=I('aid');
		if(!$id){$this->error('参数错误');}
		$where=[];
		 if (isset($id) && is_array($id)) {
            $ids = implode(',', $id);
            $where['id']=array('in',$ids);
        } else {
            $where['id']=intval($id);
        }
        
		 $suc=M('MemberAddress')->where($where)->delete();
		if($suc){$this->success(L('DO_OK'));}
		else{$this->error(L('DO_ERROR'));}
	}
	// 删除收藏商品
	public function delete_collect(){
		$cid=I('cid');
		if(!$cid){$this->error('参数错误');}
		$where=[];
		if(is_array($cid)){
			$ids=implode(',',$cid);
			$where['id']=array('in',$ids);
		}else{
			$where['id']=intval($cid);
		}
		$suc=M('GoodsCollect')->where($where)->delete();
		if($suc){$this->success(L('DO_OK'));}
		else{$this->error(L('DO_ERROR'));}
	}
	 /**
     * 收藏的商品列表
     */
    public function collect()
    {
        $uid = I('id');
        $postdata = I('post.');
        $map = array();
        if (!empty($uid)) {
            $map['uid'] = $uid;
            $this->assign('id', I('id'));
        }
        $map['type'] = 0;
        $keyword=!empty($postdata['keyword'])?$postdata['keyword']:'';
        if (is_numeric($keyword)) {
            $goods_map['id|goods_name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $goods_map['goods_name'] = array('like', '%' . (string)$keyword . '%');
        }
        if (!empty($goods_map)) {
            $goodsids = M('Goods')->field('id')->where($goods_map)->select();
            $goods_ids = array();
            foreach ($goodsids as $k => $v) {
                $goods_ids[$k] = $v['id'];
            }
            if (!empty($goods_ids)) {
                $map['goods_id'] = array('in', $goods_ids);
            }
        }
        $collect_goods = $this->lists('GoodsCollect', $map);
        $this->assign('keyword', $keyword);
        $this->assign('collect_goods', $collect_goods);
        // $this->display();
    }
	
	/* 得到所属组 */
    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 huaxiang(){
    	$uid = I("uid");
    	$member_mod = D('Admin/Member');
    	$info = $member_mod->field(true)->find($uid);
    	//会员隐私
			$ys=idtoname(MID,'Shops','is_hide_phone');
			if($ys){
				$info['mobile']=str_cutmobile($info['mobile']);				
			}
		// 


    	$info['IDcard']=$info['idcard'];
    	$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']);
		// 最后一次消费
		$this->last_buy($uid);
		$this->always_addres($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 member_delete(){
    	$id=I('id');
    	if(!$id){$this->error("请选择要删除用户");exit;}
		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;}
		}
		 if (isset($id) && is_array($id)) {
            $ids = implode(',', $id);
            $result=M('Member')->delete($ids);
        } else {
            $id = intval($id);
            $result=M('Member')->delete($id);
        }
        if($result!==false){
            $this->success(L('DO_OK'));
        }else{$this->error(L('DO_ERROR'));}


    }
    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 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']=1;
        $where['uid']=$uid;
        $coupon = M('CouponsGet')->where($where)->count();
        $this->assign('coupon',$coupon);//共使用券
        $where=array();
        $where['status']=0;
        $where['uid']=$uid;
        $couponc = M('CouponsGet')->where($where)->count();
        $this->assign('couponc',$couponc);//当前券数
	}
	// 会员 行为
	// 最后一次购买情况
	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 always_addres($uid){
		$map['uid']=$uid;
		$map['type']=array('in','6,13,14');
		$map['status']=array('in','1,2,3,6,8');
		$map['is_delete']=0;
		$always=M('OrderInfo')->where($map)->field('province,city,district,address')->group('province,city,district,address')->order('count(*) desc')->find();
		$always_addres='';
		if($always){
			if($always['province']){$always_addres.=idtoname($always['province'],"Area");}
			if($always['city']){$always_addres.=idtoname($always['city'],'Area');}
			if($always['district']){$always_addres.=idtoname($always['district'],'Area');}
			$always_addres.=$always['address'];
		}
		$this->assign('always_address',$always_addres);
		return $always_addres;
	}


    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',''));
		// 消费时段统计
		$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),'%G')")->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"),
                    );
        }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 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 add_label(){
		$auth_code = 'member_list_add_label';
		$ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$return['status'] = 0;$return['msg']=$ret['msg'];$this->ajaxReturn($return);}

		$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 = 0;$html = '';
			$is_cf=0;
			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;
				//1108新加去重 去超过10个字的
				$id=0;
				$is_count= M('Type')->where($save_data)->count();
				if($is_count || mb_strlen($v)>10){ 
					$is_cf=1;
				}else{
					$id = M('Type')->add($save_data);
				}

				if(!$id){ }
				else{$ret = 1;$html .= '<li onclick="add_member(this,'.$id.')">'.$v.'</li>';}
			}
			if($ret){
				$return['status'] = 1;
				$return['html'] = $html;
			}else{
				$return['status'] = 0;
				if($is_cf)$return['msg']='重复标签或单个标签超过10个字';
			}
		}
		$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 add_member_attribute(){

    	$postdata = I("param.");
    	$return = array('status'=>0,'msg'=>'');
    	if(empty($postdata['uid'])){
    		$return['msg'] = "参数错误";
    		$this->ajaxReturn($return);
    	}

    	$auth_code = 'member_list_edit';
		$ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {
        	$return['msg'] = $ret['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 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 edit_new(){
    	$uid = I("uid");
    	$member_mod = D('Admin/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']);
		// 最后一次消费
		$this->last_buy($uid);
		$this->always_addres($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();
    }
}
?>