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

namespace Admin\Controller;
class MemberMarketingController extends BaseController{
	
	public function _initialize()
    {
        parent::_initialize();
    }
	public function index(){
		$postdata=I('param.');
        $keyword = $postdata['keyword'];
        $map=array();
		if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['festival_name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
		}
		if($postdata['send_member'] > 0){
			$map['send_birthday'] = $postdata['send_member'];
		}elseif($postdata['send_member'] < 0){
			$map['send_member'] = -$postdata['send_member'];
		}
		if(!empty($postdata['reg_from']))$map['send_time'][]=array('EGT',strtotime($postdata['reg_from']));
		if(!empty($postdata['reg_to']))$map['send_time'][]=array('elt',strtotime($postdata['reg_to']));
		$list = $this->lists('MemberCare',$map);
//		 print_r($list);exit;
        $this->assign('list', $list);$this->assign($postdata);
		$this->display('care');
	}
	public function careadd(){
		//节日
        D("Admin/Shops")->save_member_config();
		$num['zong'] = M('Member')->count();
		$num['member'] = M('Member')->where('is_tmp = 0')->count();
		$num['fans'] = M('Member')->where('is_tmp = 1')->count();
        $attr_info=json_decode(C("ATTRIBUTE"),true);
        $must_attr_info=unserialize(C("MEMBERATTRIBUTE"));
        foreach($attr_info as $key=>$val){
            if(($val['type']=='radio' || $val['type']=='checkbox') && $val['content']){
                $arr=explode(',',$val['content']);
                foreach($arr as $k=>$val){
                    $attr_info[$key]['content_arr'][$val]=$val;
                }
            }
        }
        $map=array();
        $map['pid']=40;
        $type_info=M("Type")->where($map)->field(true)->select();
		$String = array('0'=>'[关怀名称]','1'=>'[会员名称]','2'=>'[优惠券名称]','3'=>'[积分数量]');
		$this->assign('String',$String);
		$this->assign('num',$num);
		$this->assign('attr_info',$attr_info);
		$this->assign('must_attr_info',$must_attr_info);
		$this->assign('type_info',$type_info);
		$this->getGroup(1);
		$this->display('care_edit');
	}
	public function look(){
		$id = I('param.id');
		$info = M('MemberCare')->find($id);
		if($info['festival_time'])$info['festival_time'] = time_format($info['festival_time']);
		$info['send_time'] = time_format($info['send_time']);
        if($info['uid']){
            $uid=explode(',',$info['uid']);
            $count=count($uid);
        }
		$this->assign($info);
		$this->assign('number',$count);
		$this->display('look');
	}
    public function care_insert(){
        $return = array('status'=>3,'msg'=>'');
        $postdata = I('param.');
        if(empty($postdata['wx_message']) && empty($postdata['sms_message'])){
            $return['msg'] = '请选择通知类型';
            $this->ajaxReturn($return);
        }
        if(empty($postdata['festival_name'])){
            $return['msg'] = '请填写名称';
            $this->ajaxReturn($return);
        }
        if($postdata['sms_message'] == 1){
            $map = array();$map['name'] = 'FIXED_SIGNATURE';
            $fixed_signature = M('Config')->where($map)->getField('value');
            if(empty($fixed_signature)){
                $return['msg'] = '若要发送短信，请先前往首页商家设置->系统设置->商家配置处设定固定签名。';
                $this->ajaxReturn($return);
            }
        }
        if($postdata['send_type'] == 1){
            if(!floatval($postdata['points'])){
                $return['msg'] = '请填写正确的积分';
                $this->ajaxReturn($return);
            }unset($postdata['coupons_id']);
        }
        if($postdata['send_type'] == 2){
            if(!$postdata['coupons_id']){
                $return['msg'] = '请选择优惠券';
                $this->ajaxReturn($return);
            }unset($postdata['points']);
            /*if($postdata['send_member'] == 1){
                $m_where['wxid']=array('eq','');
            }elseif($postdata['send_member'] == 2){
                $m_where['wxid']=array('neq','');
            }
            if($postdata['rank_limit'] != 0){
                $m_where['rank_id']=array('eq',$postdata['rank_limit']);
            }
            $m_count = M('Member')->where($m_where)->count();
            $quantity = idtoname($postdata['coupons_id'],'Coupons','quantity','id',false);
            if($quantity<$m_count){
                $return['msg'] = '优惠券数量不足';
                $this->ajaxReturn($return);
            }*/
        }
        //搜索会员
       $map=array();
        if(!empty($postdata['real_name'])){
            $map['real_name']=$postdata['real_name'];
        }
        if(!empty($postdata['sex'])){
            $map['sex']=$postdata['sex'];
        }
        if(!empty($postdata['idcard'])){
            $map['idcard']=$postdata['idcard'];
        }
        if($postdata['send_member']==1){
            $map['mobile']=array('neq','');
        }elseif($postdata['send_member']==2){
            $map['mobile']=array('eq','');
        }
        if(!empty($postdata['province'])){
            $map['province']=$postdata['province'];
        } if(!empty($postdata['city_id'])){
            $map['city_id']=$postdata['city_id'];
        } if(!empty($postdata['district'])){
            $map['district']=$postdata['district'];
        }
        if(!empty($postdata['birthdays_starttime']))$map['birthday'][]=array('EGT',$postdata['birthdays_starttime']);
        if(!empty($postdata['birthdays_endtime']))$map['birthday'][]=array('elt',$postdata['birthdays_endtime']);
        if(!empty($postdata['lables'])){
            $map['labels']=array('like','%,'.$postdata['lables'].',%');
        }
        if(!empty($postdata['begin_usepoints'])){
            $map['usepoints'][]=array('EGT',$postdata['begin_usepoints']);
        }
        if(!empty($postdata['end_usepoints'])){
            $map['usepoints'][]=array('elt',$postdata['end_usepoints']);
        }
        if(!empty($postdata['begin_money'])){
            $map['money'][]=array('EGT',$postdata['begin_money']);
        }
        if(!empty($postdata['end_money'])){
            $map['money'][]=array('elt',$postdata['end_money']);
        }
        if(!empty($postdata['begin_reg_time'])){
            $map['reg_time'][]=array('EGT',$postdata['begin_reg_time']);
        }
        if(!empty($postdata['end_reg_time'])){
            $map['reg_time'][]=array('elt',$postdata['end_reg_time']);
        }
        if(!empty($postdata['rank_limit'])){
            $map['rank_id']=$postdata['rank_limit'];
        }
        if($map) {
            $uid = M("Member")->where($map)->getField('id', true);
        }
        if($postdata['begin_consume_time'] && $postdata['end_consume_time']){//上次消费时间
            $map = array();
            $map['addtime'] = array(array('gt',strtotime($postdata['begin_consume_time'])),array('lt',strtotime($postdata['end_consume_time'])));
            $uids = M('OrderInfo')->where($map)->group('uid')->getField('uid',true);
        }
        if($uid && $uids){
            $first_uids=array_intersect($uid, $uids);
        }elseif(empty($uid) && $uids){
            $first_uids=$uids;
        }elseif(empty($uids) && $uid){
            $first_uids=$uid;
        }
        // 会员筛选
        $guids = array();
        if($postdata['act_rang_ext']){
            $ordergoods = M('OrderGoods')->alias('og')->where('og.goods_id='.$postdata['act_rang_ext'])->field('oi.uid')->JOIN('LEFT JOIN __ORDER_INFO__ oi ON oi.id=og.order_id')->distinct('oi.uid')->select();
            foreach ($ordergoods as $k => $v) {
                $guids[] = $v['uid'];
            }
        }
        if($first_uids && $guids){
            $total_ids=array_intersect($first_uids,$guids);
        }elseif(empty($guids) && $first_uids){
            $total_ids=$first_uids;
        }elseif(empty($first_uids) && $guids){
            $total_ids=$first_uids;
        }
        //属性筛选
        $map=array();
        $attruid=$checkattruid=array();
        if($postdata){
            foreach($postdata as $key=>$val){
                if(str_exists($key,'attr') && $val){
                    $attr_id=explode('_',$key);
                    $map=array();
                    $map['_string'].= "content='".$val."' and aid=".$attr_id[1];
                    $attruid[$key]=M("MemberAttribute")->where($map)->getField('uid',true);
                }
                if(str_exists($key,'checkbox') && $val){
                    $attr_id=explode('_',$key);
                    foreach($val as $k=>$v){
                        $map=array();
                        $map['_string'].= "content like '%,".$v.",%' and aid=".$attr_id[1];
                        $checkattruid[$key][]=M("MemberAttribute")->where($map)->getField('uid',true);
                    }
                }
                if(str_exists($key,'starttime') && $val){
                    $attr_id=explode('_',$key);
                    $map=array();
                    $endtime=$postdata['endtime_'.$attr_id[1]];
                    $map['content']= array(array('gt',strtotime($val)),array('lt',strtotime($endtime)));
                    $checkattruid[$key][]=M("MemberAttribute")->where($map)->getField('uid',true);
                }
            }
            //降级
            $attr_bute_uids=array();
            foreach($attruid as $key=>$val){//单选框得到的一位数组会员id
                if($val) {
                    foreach ($val as $k => $v) {
                        if($v) {
                            $attr_bute_uids[] = $v;
                        }
                    }
                }
            }
            foreach($checkattruid as $key=>$val){//多选框得到的一位数组的会员id
                if($val){
                    foreach ($val as $k => $v) {
                        if($v) {
                            foreach($v as $kk=>$vv)
                            $check_attr_bute_uids[] = $vv;
                        }
                    }
                }
            }
            if($attr_bute_uids && $check_attr_bute_uids){
                $intersection = array_intersect($attr_bute_uids, $check_attr_bute_uids);
            }elseif(empty($attr_bute_uids) && $check_attr_bute_uids){
                $intersection = $check_attr_bute_uids;
            }elseif(empty($check_attr_bute_uids) && $attr_bute_uids){
                $intersection = $attr_bute_uids;
            }
        }
        $member_ids=array();
        if(!empty($total_ids) && !empty($intersection)){
            $member_ids=array_intersect($intersection,$total_ids);
        }
        if(empty($total_ids) && !empty($intersection)){
            $member_ids=$intersection;
        }
        if(!empty($total_ids) && empty($intersection)){
            $member_ids=$total_ids;
        }
        $member_ids=array_unique($member_ids);
        $member_ids=implode(',',$member_ids);
        if(empty($member_ids)){
            $return['msg']="没有要发送的会员";
            $this->ajaxReturn($return);
        }
        $data=array();
        $data['uid']=$member_ids;
        if($postdata['points'])$data['points'] = $postdata['points'];
        if($postdata['coupons_id'])$data['coupons_id'] = $postdata['coupons_id'];
        $data['festival_time'] = strtotime($postdata['festival_time']);
        $data['rank_limit'] = $postdata['rank_limit'];
        $data['send_member'] = $postdata['send_member'];
        $data['type']=$postdata['type'];
        $data['send_time']=$postdata['send_time'];
        $data['festival_name'] = $postdata['festival_name'];
        $data['send_type'] = $postdata['send_type'];
        if($postdata['wx_message'])$data['wx_message'] = $postdata['wx_message'];
        if($postdata['sms_message'])$data['sms_message'] = $postdata['sms_message'];
        if(!$postdata['content']){$postdata['content']='有任何疑问，请致电客服。';}$data['content'] = $postdata['content'];
        $res = M('MemberCare')->add($data);
        if($res){
            $return['status'] = 1;
            $return['msg'] = '保存成功';
            $return['url'] = U('MemberMarketing/get_member_care',array('id'=>$res));
        }else{
            $return['msg'] = '保存失败';
        }

        $this->ajaxReturn($return);
    }
    public function get_member_care(){
        $param=I('param.');
        if(empty($param['id']))return false;
        $map=array();
        $map['id']=$param['id'];
        $member_ids=M("MemberCare")->where($map)->getField('uid');
        if($member_ids){
            $map=array();
            $map['id']=array('in',$member_ids);
            $member_info=M("Member")->where($map)->field('id,username,nickname,mobile,real_name')->select();
            $have_count=M("Member")->where($map)->count();
            if($member_info){
                foreach($member_info as $key=>$val){
                    if($val['username']){
                        $member_info[$key]['name']=$val['username'];
                    }elseif($val['nickname']){
                        $member_info[$key]['name']=$val['nickname'];
                    }elseif($val['real_name']){
                        $member_info[$key]['name']=$val['real_name'];
                    }else{
                        $member_info[$key]['name']=$val['mobile'];
                    }
                }
            }
            $this->assign('member_info',$member_info);
        }
        $have_data=$member_info;
        $this->assign('have_data',$have_data);
        $this->assign('have_count',$have_count);
        $this->assign('id',$param['id']);
        $this->display();
    }
    public function search(){
        $param=I('param.');
        if(empty($param['keyword']))return false;
        $keyword=$param['keyword'];
        $mmap=$map=array();
        /*$mmap['id']=$param['id'];
        $member_ids=M("MemberCare")->where($mmap)->getField('uid');
        if($member_ids){
            $member_idarray=explode(',',$member_ids);
            $map['id']=array('notin',$member_idarray);
        }*/
        //$map=array('notin',$member_info);
        $whereor=array();
        $whereor['id']=array('like','%'.$keyword.'%');
        $whereor['username']=array('like','%'.$keyword.'%');
        $whereor['nickname']=array('like','%'.$keyword.'%');
        $whereor['real_name']=array('like','%'.$keyword.'%');
        $whereor['mobile']=array('like','%'.$keyword.'%');
        $whereor['_logic'] = 'or';
        $map['_complex'] = $whereor;
        $data = M("Member")->where($map)->field("id,username,nickname,mobile,real_name")->select();
        if($data){
            // $data=array_unique($data);
            foreach($data as $key=>$val){
                if($val['username']){
                    $data[$key]['name']=$val['username'];
                }elseif($val['nickname']){
                    $data[$key]['name']=$val['nickname'];
                }elseif($val['real_name']){
                    $data[$key]['name']=$val['real_name'];
                }else{
                    $data[$key]['name']=$val['mobile'];
                }
            }
        }
        $return['count'] = count($data);
        $return['list'] = $data;
        $this->ajaxReturn($return);
    }
    public function save_member_care(){
        $param=I('param.');
        if(empty($param['id']))return false;
        $map=$data=array();
        $map['id']=$param['id'];
        if($param['check_ids']) {
            $uid = implode(',', $param['check_ids']);
        }
        $data['uid']=$uid;
        $data['update_time']=NOW_TIME;
        $res=M("MemberCare")->where($map)->save($data);
        if($res){
            $return['status'] = 1;
            $return['msg'] = '保存成功';
            $return['url'] = U('MemberMarketing/look',array('id'=>$param['id']));
        }else{
            $return['status'] = 3;
            $return['msg'] = '保存失败';
        }
        $this->ajaxReturn($return);
    }
	public function send(){
		$id = I('param.id');
		$page = I('param.page');
		$send_time = I('param.send_time');
		$type = I('param.type');
        $data=array();
        $data['send_time']=$send_time;
        $data['type']=$type;
		$res = send_care($id,$page,10,$data);
		$this->ajaxReturn($res);
	}
	public function many_points(){
		$postdata=I('param.');
        $keyword = $postdata['keyword'];
        $map=array();
		if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
		}
		$map['consumption_type'] = array('in','1,3');
		$list = $this->lists('ManypointsRule',$map);
        $this->assign('list', $list);$this->assign($postdata);
		$this->display();
	}
	public function many_points_consume(){
		$postdata=I('param.');
        $keyword = $postdata['keyword'];
        $map=array();
		if(!empty($keyword)){
			$whereor['id']=array('like','%'.$keyword.'%');
            $whereor['name']=array('like','%'.$keyword.'%');
            $whereor['_logic'] = 'or';
            $map['_complex'] = $whereor;
            $seotitle=$keyword.'_';
		}
		$map['consumption_type'] =2;
		$list = $this->lists('ManypointsRule',$map);
        $this->assign('list', $list);$this->assign($postdata);
		$this->display();
	}
	public function pointsadd(){
		$num['zong'] = M('Member')->count();
		$this->assign('num',$num);
		$this->getGroup(1);
		$this->display('many_points_edit');
	}
	public function pointsadd_consume(){
		$num['zong'] = M('Member')->count();
		$this->assign('num',$num);
		$this->getGroup(1);
		$this->display('many_points_edit_consume');
	}
	public function add(){
		$postdata = I('param.');
		$model = D('ManypointsRule');
		if (!isset($postdata['name']) || ($postdata['name'] == '')) {
                $this->error('名称不能为空');
        }
		$count = $model->where("name='" . $postdata['name'] . "'")->count();
		if ($count > 0) {
			$this->error('该名称已经存在！');
		}
		if(!$postdata['give_type']){
			$this->error('请选择特权限制！');
		}
		if($postdata['consume']){
			$postdata['consumption_type'] = 2;//判断是否为消费有礼
		}else{
			$postdata['consumption_type'] = 1;
		}
		if($postdata['give_type'] == 1){
			$postdata['coupons_id'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_one'];
			$postdata['give_num'] = $postdata['give_num_one'];
		}
		if($postdata['give_type'] == 2){
			$postdata['coupons_id'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_two'];
			$postdata['give_num'] = $postdata['give_num_two'];
		}
		if($postdata['give_type'] == 3){
			$postdata['give_num'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_three'];
		}
		$postdata['add_time'] = NOW_TIME;
		$postdata['status'] = 1;
		$model->create($postdata);
        $result = $model->add();
		if ($result) {
			if($postdata['consume']){
				$this->success(L('DO_OK'),U('MemberMarketing/many_points_consume'));
			}else{
				$this->success(L('DO_OK'),U('MemberMarketing/many_points'));
			}
		} else {
			$this->error(L('DO_ERROR'));
		}
	}
	public function pointsedit_consume(){
		$id = I('id');
        $model = D('ManypointsRule');
		if (isset($id)) {
			$id = isset($id) && intval($id) ? intval($id) : $this->error('参数错误');
		}
		if(!$id)$this->error('参数错误');
		$info = $model->field(true)->find($id);
		if($info['give_type']==2)$info['money_limit_two']=$info['money_limit'];$info['give_num_two']=$info['give_num'];
		if($info['give_type']==3)$info['money_limit_three']=$info['money_limit'];
		$this->assign($info);
		$num['zong'] = M('Member')->count();
		$this->assign('num',$num);
		$this->getGroup(1);
		$this->display('many_points_edit_consume');
	}
	public function pointsedit(){
		$id = I('id');
        $model = D('ManypointsRule');
		if (isset($id)) {
		$id = isset($id) && intval($id) ? intval($id) : $this->error('参数错误');
		}
		if(!$id)$this->error('参数错误');
		$info = $model->field(true)->find($id);
		if($info['give_type']==1){
			$info['money_limit_one']=$info['money_limit'];
			$info['give_num_one']=$info['give_num'];
		}
		if($info['give_type']==2){
			$info['money_limit_two']=$info['money_limit'];
			$info['give_num_two']=$info['give_num'];
		}
		if($info['give_type']==3)$info['money_limit_three']=$info['money_limit'];
		$this->assign($info);
		$num['zong'] = M('Member')->count();
		$this->assign('num',$num);
		$this->getGroup(1);
		$this->display('many_points_edit');
		
	}
	public function point_update(){
		$id = I('id');
        $model = D('ManypointsRule');
		$postdata = I('param.');
		$count = $model->where("id!=" . $id . " and name='" . $postdata['name'] . "'")->count();
		if ($count > 0) {
			$this->error('该名称已经存在！');
		}
		if($postdata['consume']){
			$postdata['consumption_type'] = 2;//判断是否为消费有礼
		}else{
			$postdata['consumption_type'] = 1;
			if($postdata['give_type'] == 1){
				$postdata['consumption_type'] = 3;
			}
		}
		if($postdata['give_type'] == 1){
			$postdata['coupons_id'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_one'];
			$postdata['give_num'] = $postdata['give_num_one'];
		}
		if($postdata['give_type'] == 2){
			$postdata['coupons_id'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_two'];
			$postdata['give_num'] = $postdata['give_num_two'];
		}
		if($postdata['give_type'] == 3){
			$postdata['give_num'] = 0;
			$postdata['money_limit'] = $postdata['money_limit_three'];
		}
		if (false === $model->create($postdata)) {
			$this->error($model->getError());
		}
		$result = $model->save();
		if (false !== $result) {
			if($postdata['consume']){
				$this->success(L('DO_OK'),U('MemberMarketing/many_points_consume'));
			}else{
				$this->success(L('DO_OK'),U('MemberMarketing/many_points'));
			}
		} else {
			$this->error(L('DO_ERROR'));
		}
	}
	public function delete(){//公共删除
		$mod=D('ManypointsRule');
		$id=$this->id?$this->id:I('id');
		if (isset($id) && is_array($id)) {
			$ids = implode(',', $id);
			$result=$mod->delete($ids);
		} else {
			$id = intval($id);
			$result=$mod->delete($id);
		}
		if($result!==false){
		  if(in_array('ManypointsRule',$this->cache_model)){savecache('ManypointsRule');}
			$this->success(L('DO_OK'));
		}else{$this->error(L('DO_ERROR'));}
	}
	/* 得到所属组 */
    private function getGroup($type = ''){
        $groupData = M('MemberRank')->where('status=1')->field(true)->order('sort,id desc')->select();
        if ($type == 1) {
            foreach ($groupData as $v) {
				$map['rank_id'] = $v['id'];
				$num = M('Member')->where($map)->count();
                $newgroupData[$v['id']] = $v['name']."(".$num.")";
            }$groupData=$newgroupData;
			
			//生日
			$arr = array('0'=>'01','1'=>'02','2'=>'03','3'=>'04','4'=>'05','5'=>'06','6'=>'07','7'=>'08','8'=>'09','9'=>'10','10'=>'11','11'=>'12');
			foreach($arr as $k=>$v){
				$maps['birthday'] = array('like','%-'.$v.'-%');
				$nums[$v] = M('Member')->where($maps)->count();
				$n = intval($v);
				$birthdays[$n] = $v.'月份生日的会员('.$nums[$v].')';
			}
			$c_map = array();
			$c_map['coupons_type'] = 1;
			// $c_map['status'] = 0;
			$c_map['buy_type'] = 0;
			$c_map['status'] = 1;
			$c_map['quantity'] = array('GT',0);
			//优惠券
			$coupons = M('Coupons')->where($c_map)->field(true)->select();
			foreach ($coupons as $v) {
                $newcoupons[$v['id']] = $v['title']."(".$v['quantity'].")";
            }$coupons=$newcoupons;
        }
        $this->assign('groupData', $groupData);
        $this->assign('coupons', $coupons);
        $this->assign('birthdays', $birthdays);
    }
	public function chongzhi_set(){
		$shezhi = C('FIXED_RECHARGE_OPEN');
		$map=array();
		$map['name']='FIXED_RECHARGE_OPEN';
		$info=M('Config')->where($map)->find();
		$this->assign($info);
		$this->display();
	}
	public function chongzhi_update(){
		$post=I('param.');
		$map=array();
		if(!$post['name']){
			$this->error('参数错误');
		}
		$map['name']=$post['name'];
		$data=array();
		$data['value']=$post['value'];
		$res = M('Config')->where($map)->save($data);
		if ($res !== false) {
			$this->success('设置成功',U('MemberMarketing/many_points'));
		}else{
			$this->error('请重新设置',U('MemberMarketing/many_points'));
		}
	}
    public function text_c(){
        $c=send_care(11);
        print_r($c);exit;
    }

}
?>