<?php
/**
 * @author xiaogg QQ:756663992
 * @copyright 2017
 */
namespace Admin\Controller;
class WxCouponController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
        $is_auth=check_use_auth("WeChatMarket");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }
    }
	public function index(){
	    $postdata = I('post.');
    	$map=array();	
    	if($postdata['keyword'])$map['title'] = array('like','%'.$postdata['keyword'].'%');
    	if($postdata['reg_from'] && !$postdata['reg_to'])$map['add_time'] = array(array('gt',strtotime($postdata['reg_from'])));
    	if($postdata['reg_to'] && !$postdata['reg_from'])$map['add_time'] = array(array('lt',strtotime($postdata['reg_to'])));
    	if($postdata['reg_from'] && $postdata['reg_to'])$map['add_time'] = array(array('gt',strtotime($postdata['reg_from'])),array('lt',strtotime($postdata['reg_to'])));
		if($postdata['is_check']){$map['is_check']=$postdata['is_check'];}
        	$map['coupons_type'] = 1;
//		$map['status'] = 1;
		$info=$this->lists('Coupons',$map);
		$coupon_record = $this->coupon_record();
		foreach ($info as $k => $v) {
			$info[$k]['coupon_get'] = $coupon_record[$v['id']]['coupon_get'];
			$info[$k]['coupon_past'] = $coupon_record[$v['id']]['coupon_past'];
			$info[$k]['coupon_make'] = $coupon_record[$v['id']]['coupon_make'];
			$info[$k]['coupon_use'] = $coupon_record[$v['id']]['coupon_use'];
		}
        $is_check_bonu=C("IS_CHECK_BONU");
        $this->assign('is_check_bonu',$is_check_bonu);
    	$this->assign('info', $info);
    	$this->assign('postdata', $postdata);
    	$this->display();
	}
	//发放代金券
	public function coupon_send(){
        $where = array();
        $where['status'] = 1;
        $where['is_type'] = 1;
        $this->suppliers = M('Suppliers')->where($where)->field('id,name')->select();
        $this->assign('suppliers',$this->suppliers);
		$this->getcateTree();
		$this->display();
	}
	//编辑代金券
	public function coupon_edit(){
        $where = array();
        $where['status'] = 1;
        $where['is_type'] = 1;
        $this->suppliers = M('Suppliers')->where($where)->field('id,name')->select();
        $this->assign('suppliers',$this->suppliers);
		$id  = I('get.id');$info='';
		$info=M('Bonu')->field(true)->find($id);
		$goods_ids=array_filter(explode(',',rtrim($info['goods_ids'],',')));
		// var_dump($goods_ids)
		foreach($goods_ids as $k=>$v){
			$goods_list.="<option value='".$v."'>".idtoname($v,'Goods','goods_name','id',false)."</option>";
		}
		$this->assign('select_link_goods',$goods_list);
		$this->getcateTree();
		$this->assign('edit',$info);
		$this -> assign('id',  $id);
		$this->display();
	}
	//代金券发放处理
	public function send_bonu(){
		$url = U('Admin/Bonu/index');
		$postdata=I('post.');
		if(empty($postdata['type_name']) || empty($postdata['type_money']) || empty($postdata['min_goods_amount'])){
			$this->error('必填项不要为空',U('Admin/Bonu/bonu_send'));
		}
		if($postdata['use_start_date'] && $postdata['use_end_date']){
			$use_start_date = strtotime($postdata['use_start_date']);
			$use_end_date = strtotime($postdata['use_end_date']);
			$arr['use_start_date'] = $use_start_date;
			$arr['use_end_date'] = $use_end_date;
		}
		$arr['type_name'] = $postdata['type_name'];
		$arr['type_money'] = $postdata['type_money'];
		$arr['min_goods_amount'] = $postdata['min_goods_amount'];
		if($postdata['suppliers_id']==0){
			$arr['catid'] = $postdata['type']==3?$postdata['catid']:0;
		}else{
			$arr['cat_id'] = $postdata['type']==3?$postdata['cat_id']:0;
		}
		
		$arr['brand_id'] = $postdata['type']==2?$postdata['brand_id']:0;	
		$arr['suppliers_id']=$postdata['suppliers_id'];
		$arr['addtime'] = NOW_TIME;
		$arr['status']=0;
		$sql_f = M('Bonu')->add($arr);
		if($sql_f){
			$this->success('添加成功！',$url);
	 	}else{
			$this->error('添加失败！',$url);
	 	}
	}
	//删除代金券
	public function delete_bonu(){
		$id  = I('id');	
		if(isset($id) && is_array($id)){
			$ids = implode(',',$id);
			$map_b = array();
			$map_b['id'] = array('in',$ids);
			$deletes=M('Bonu')->where($map_b)->delete();
		}else{
			$id = intval($id);
			$deletes=M('Bonu')->where('id='.$id)->delete();
		}
		$url=U('Admin/Bonu/index');
		if($deletes){
			$this->success('删除成功！',$url);
	 	} else {
			$this->error('删除失败！',$url);
	 	}		
	}
	//卡券核销
	public function coupon_off(){

		$this->display();
	}
	/* 得到节点树 */
	private function getcateTree($pid = '',$assign='',$brandid='') {
		$GoodsCategory = getcache('PurchaseCategory');
	   $Tree = new \Common\Vendor\Tree();
       $select_categorys='';
       $treemini=$Tree->treemini($GoodsCategory);
       $select_categorys.= $Tree->treeminioption($treemini,$pid);
	   if($assign)return $select_categorys;
       else $this->assign('select_categorys',$select_categorys);
	   //品牌
	   $brand=M('Brand')->where('status=1')->field('id,brand_name')->select();
	   foreach($brand as $k=>$v){
		   if($brandid == $v['id']){
			   $brand_op.="<option selected='selected' value='".$v['id']."'>".$v['brand_name']."</option>";
			}else{
				$brand_op.="<option value='".$v['id']."'>".$v['brand_name']."</option>";
			}
	 	}
		$this->assign('select_brand',$brand_op); 
	}
    //创建新卡券
    public function insert(){
        $postdata=I('post.');

        $postdata['brand_name'] = C('WEB_SITE_NAME');
        $postdata['logo_url'] = C('WEB_SMALL_LOGO');
        if(empty($postdata['logo_url']))$postdata['logo_url']= C('WEB_SITE_LOGO');
        if($postdata['is_show'] == 0){
	        $postdata['location_id_list'] = 0;
        }else{
	        if($postdata['location_id_list'])$postdata['location_id_list'] = implode(',',$postdata['location_id_list']);
        }
        if(!$postdata['use_limit'] || $postdata['use_limit'] <= 0){
	        $postdata['use_limit'] = 50;
        }
        if(!$postdata['get_limit'] || $postdata['get_limit'] <= 0){
	        $postdata['get_limit'] = 50;
        }
        $urls = U('Admin/wx_coupon/add');
        if(!$postdata['logo_url']){
	        $post_status = 1;
	        $msg = '商户LOGO不能为空!';
        }
        if($postdata['rank_id'] == '选择类型'){
	        $post_status = 1;
	        $msg = '请选择卡券类型!';
        }
        if($postdata['rank_id'] == 'GENERAL_COUPON' && !$postdata['default_detail']){
	        $post_status = 1;
	        $msg = '优惠详情不能为空!';
        }elseif($postdata['rank_id'] == 'DISCOUNT' && !$postdata['discount']){
	        $post_status = 1;
	        $msg = '折扣额度不能为空!';
        }elseif($postdata['rank_id'] == 'GIFT'  &&!$postdata['gift']){
	        $post_status = 1;
	        $msg = '礼品名称不能为空!';
        }elseif($postdata['rank_id'] == 'CASH' && !$postdata['reduce_cost']){
	        $post_status = 1;
	        $msg = '减免金额不能为空!';
        }elseif($postdata['rank_id'] == 'GROUPON' && !$postdata['deal_detail']){
	        $post_status = 1;
	        $msg = '团购详情不能为空!';
        }
        if($post_status == 1){
	        echo "<script language=\"javascript\">alert('$msg');location.href = 'javascript:history.back()'</script>";
	        exit();
        }
        if($postdata['is_show'] == 1){
	    $map = array();
	    $map['poi_id'] = array('in',$postdata['location_id_list']);
	    $arr = M('Shops')->where($map)->getField('id',true);
	    $postdata['is_show'] =$arr? ','.implode(',',$arr).',':'';
        }
        $Weixin = new \Common\Vendor\WeixinCoupon();
        // 添加优惠券
        $add_coupon = $Weixin->add_coupon($postdata);
        if($add_coupon['status'] == 1){
	  $url = U('Admin/wx_coupon/index');
	  $this->success('添加成功！',$url);
        }else{
	  $url = U('Admin/wx_coupon/insert');
	  $this->error('添加失败！',$url);
        }
    }
    // 二维码
    public function get_code(){
        $get=I('get.');
        $get['card_id'] = idtoname($get['id'],'Coupons','card_id');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $get_code = $Weixin->get_code($get);
        if($get_code['status'] == 1){
	  $result['status'] = 1;
	  $result['url'] = $get_code['show_qrcode_url'];
        }
        $this->ajaxReturn($result);
    }
    // 修改库存
    public function modifystock(){
        $get=I('get.');
        $get['card_id'] = idtoname($get['id'],'Coupons','card_id');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $modifystock = $Weixin->modifystock($get);
        // print_r($modifystock);exit();
        if($modifystock['status'] == 1){
	  $result['status'] = '1';
	  $result['shu'] = $modifystock['shu'];
	  $result['id'] = $modifystock['id'];
        }else{
	  $result['status'] = '0';
        }
        $this->ajaxReturn($result);
    }
//    查看
//    public function view(){
//        $id = I('id');
//        $model = D('Bonu');
//        $info = $model->field(true)->find($id);
//        $this->assign('reg_name',$reg);
//        $this->assign($info);
//        $this->assign('rank_info',$rank_info);
//        $this->getcateTree($info['cat_id']);
//        $this->display();
//    }
    //删除微信代金券
    public function delete(){
        $id  = I('get.id');
        $url = U('Admin/wx_coupon/index');
        $card_id = M('Coupons')->where('id='.$id)->field('card_id')->find();

        $Weixin = new \Common\Vendor\WeixinCoupon();
        $del_coupon = $Weixin->del_coupon($card_id['card_id']);
        $deletes = M('Coupons')->where('id='.$id)->order('id desc')->delete();
        if($deletes && $del_coupon['errmsg'] == 'ok'){
	  $this->success('删除成功！',$url);
        }elseif($deletes){
	  $this->success('删除成功！',$url);
        }else {
	  $this->error('删除失败！',$url);
        }
    }
    //删除线下代金券
    public function delete_down(){
        $para  = I('get.');
        $id=$para['bonus_id'];
        $deletes=M('MemberBonus')->where('bonus_id='.$id)->delete();
        $url=U('Admin/Bonu/down_index');
        if($deletes){
	        $this->success('删除成功！',$url);
        } else {
	        $this->error('删除失败！',$url);
        }
    }
    //删除用户代金券
    public function delete_user(){
        $para  = I('bonus_id');
        if(isset($para) && is_array($para)){
	  $ids = implode(',',$para);
	  $map_b = array();
	  $map_b['bonus_id'] = array('in',$ids);
	  $deletes=M('MemberBonus')->where($map_b)->delete();
        }else{
	  $id = intval($para);
	  $deletes=M('MemberBonus')->where('bonus_id='.$id)->delete();
        }
        $url=U('Admin/Bonu/bonus_list');
        if($deletes){
	  $this->success('删除成功！',$url);
        } else {
	  $this->error('删除失败！',$url);
        }
    }
    //编辑微信代金券
    public function edit(){
        $id=I('id');
        $is_check_bonu=C("IS_CHECK_BONU");
        $this->assign('is_check_bonu',$is_check_bonu);
        $map = array();$map['id'] = $id;
        $edits = M('Coupons')->where($map)->field(true)->find();
        if($edits['card_id']){
	    $card_id = 1;
        }else{
	    $card_id = 0;
        }
        if($edits['location_id_list']){
	  $where_shop['poi_id'] = array('in',$edits['location_id_list']);
	  $shop = M('Shops')->where($where_shop)->field('name')->select();
	  $this->assign('shop',$shop);
        }
        $check_info=array(1=>"审核",2=>'拒绝',3=>'待审核');
        $list = M('PromotExt')->where('act_id=' . $id)->select();
        $rang_list = '';
        foreach ($list as $k => $v) {
	  $rang_list .= "<div class='ml10'><label class='checkbox-inline'><input type='checkbox' checked='checked' name='act_rang_ext[]' value='" . $v['style_ext_id'] . "' />" . idtoname($v['style_ext_id'], 'Goods', 'goods_name', 'id', false) . "【". idtoname($v['style_ext_id'], 'Goods', 'goods_sn', 'id', false) ."】</label></div>";

        }

        $this->assign('range_list', $rang_list);
        $this->assign('check_info',$check_info);
        $this->assign('card_id',$card_id);
        $this->assign('edit', $edits);
        $this->getcateTree();
        $this->display('update');		
    }
	//添加微信代金券
	public function _before_add(){
		$where['status'] = 1;
		$where['poi_id'] = array('neq','0');
		$shopsData = M('Shops')->where($where)->field('id,poi_id,name')->select();
        $this->assign('shopsData', $shopsData);
		$this->getcateTree();	
	}
	//用户发放处理
	 public function send_user(){
		 $url = U('Admin/Bonu/index_user');
		$postdata=I('post.');
		$use_start_date = strtotime($postdata['use_start_date']);
		$use_end_date = strtotime($postdata['use_end_date']);
		$arr['type_name'] = $postdata['type_name'];
		$arr['type_money'] = $postdata['type_money'];
		$arr['min_goods_amount'] = $postdata['min_goods_amount'];
		$arr['cat_id'] = $postdata['cat_id'];
		$arr['use_start_date'] = $use_start_date;
		$arr['use_end_date'] = $use_end_date;
		$arr['cat_id'] = $postdata['cat_id'];
		$arr['brand_id'] = $postdata['brand_id'];	
		$goods = M('Bonu')->where('id=1')->save($arr);
		 if($postdata['ra_bonus']){
		 	$rank_user = M('member')->where('rank_id='.$postdata['ra_bonus'])->field('id')->select();
			foreach($rank_user as $value){
				$arra['bonus_type_id'] = 1;
				$arra['user_id'] = $value['id'];
				$arra['send_time'] = NOW_TIME;
				$arra['money'] = $postdata['type_money'];
				$arra['min_goods_money'] = $postdata['min_goods_amount'];
				$arra['start_time'] = $use_start_date;
				$arra['end_time'] = $use_end_date;
				$arra['cat_id'] =$postdata['type']==3?$postdata['cat_id']:0;
				$arra['brand_id'] = $postdata['type']==2?$postdata['brand_id']:0;
				$arra['bonu_name']=$postdata['type_name'];
				$sql_f = M('MemberBonus')->add($arra);		
			}
		 } else {
			 $user_array = $postdata['rank_select_right'];
			 if(!$user_array)$this->error('请选择会员！',$url);
				 foreach($user_array as $key=>$val){
						$arra['bonus_type_id'] = 1;
						$arra['user_id'] = $val;
						$arra['send_time'] = NOW_TIME;
						$arra['money'] = $postdata['type_money'];
						$arra['min_goods_money'] = $postdata['min_goods_amount'];
						$arra['start_time'] = $use_start_date;
						$arra['end_time'] = $use_end_date;	
						$arra['cat_id'] = $postdata['type']==3?$postdata['cat_id']:0;
						$arra['brand_id'] = $postdata['type']==2?$postdata['brand_id']:0;
						$arra['bonu_name']=$postdata['type_name'];
						$sql_f = M('member_bonus')->add($arra);	 
				}
		}
		if($sql_f){
			$this->success('发放成功！',$url);
	 	} else {
			$this->error('发放失败！',$url);
	 	}
	}
	//线下发放处理
	public function send_oline(){
		$postdata = I('post.');
		$use_start_date = strtotime($postdata['use_start_date']);
		$use_end_date = strtotime($postdata['use_end_date']);
		$arr['type_name'] = $postdata['type_name'];
		$arr['type_money'] = $postdata['type_money'];
		$arr['min_goods_amount'] = $postdata['min_goods_amount'];
		$arr['use_start_date'] = $use_start_date;
		$arr['use_end_date'] = $use_end_date;
		$arr['cat_id'] = $postdata['cat_id'];
		$arr['brand_id'] = $postdata['brand_id'];
		$goods = M('Bonu')->where('id=4')->save($arr);
		$bonus_sum = !empty($_POST['bonus_sum'])     ? $_POST['bonus_sum']     : 1;
		if(!$bonus_sum)$this->error('请添加数量！',$url);
		//随机生成代金券序列号
		$info = M('member_bonus');
		$infos = $info->field(max('bonus_sn'))->find();
		$num = $infos[0];
		$num = $num ? floor($num / 10000) : 100000;	
		for ($i = 0, $j = 0; $i < $bonus_sum; $i++){
			$bonus_sn = ($num + $i) . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
			$arr['bonus_type_id'] = 4;
			$arr['bonus_sn']=$bonus_sn;
			$arr['send_time']=NOW_TIME;
			$arr['money'] = $postdata['type_money'];
			$arr['min_goods_money'] = $postdata['min_goods_amount'];
			$arr['cat_id'] = $postdata['cat_id'];
			$arr['brand_id'] = $postdata['brand_id'];
			$arr['start_time'] = $use_start_date;
			$arr['end_time'] = $use_end_date;
			$arr['bonu_name'] = $postdata['type_name'];	
			//print_r($arr);exit;
			$sql = $info->add($arr);
		}
		if($sql!==false){
			$url = U('Admin/Bonu/down_index');
			$this->success('发放成功！',$url);
		} else {
			$this->error('发放失败！',$url);
		} 
	}
	//用户代金券
	public function index_user(){
		$big_menu = array('发放用户代金券' => U('user_send'));
        $this->assign('big_menu', $big_menu);
		if(I('order')){
			$where['order_id']=I('order');
		}
		if(I('user')){
			$user=I('user');
			if(is_numeric($user)){
			$where_u['id|username']=   array(intval($user),array('like','%'.$user.'%'),'_multi'=>true);
			}else if($user){
			$where_u['username']    =   array('like', '%'.(string)$user.'%');
        	}
			$user_list=M('Member')->where($where_u)->field('id')->select();
			if($user_list){
				foreach($user_list as $k=>$v){
					$u_list[]=$v['id'];
				}
				$where['user_id']=array(array('in',$u_list));
			}
		}
		if(I('use')==1){
			$where['used_time']=array(array('neq',''));
		}elseif(I('use')==2){
			$where['used_time']=array(array('eq',''));
		}		
		$where['bonus_type_id']=1;
		$info=$this->lists('MemberBonus',$where);
		foreach($info as $k=>$v){
			if($v['order_id']){
				$order=M('OrderInfo')->where('id='.$v['order_id'])->field('order_sn')->find();
				$user_info[$k]['order_sn']=$order['order_sn'];
			}else{
				$user_info[$k]['order_sn']=0;
			}
		}	
		$this->assign('info',$info);
		$this->assign('type_id',$id);
		$this->display();
	}
	//代金券到期提醒页面
	public function push_bonu(){
		$map['user_id']=array('GT','0');
		$map['used_time']=0;
		//$map['is_tixing']=0;
		if(I('name')){
			$bo=trim(I('name'));
			if(is_numeric($bo)){
				$where_b['id']=$bo;
			}else{
				$where_b['type_name']=array('like', '%'.(string)$bo.'%');
        	}
			$bo_list=M('Bonu')->where($where_b)->field('id')->select();
			if($bo_list){
				foreach($bo_list as $k=>$v){
					$b_list[]=$v['id'];
				}
				$map['bonus_type_id']=array('in',$b_list);
			}
		}
		if(I('member')){
			$user=trim(I('member'));
			if(is_numeric($user)){
				$where_u['id|username']=array((int)$user,array('like','%'.$user.'%'),'_multi'=>true);
			}else{
				$where_u['username']=array('like', '%'.(string)$user.'%');
        	}
			$user_list=M('Member')->where($where_u)->field('id')->select();
			if($user_list){
				foreach($user_list as $k=>$v){
					$u_list[]=$v['id'];
				}
				$map['user_id']=array('in',$u_list);
			}
		}
		if(I('is_tixing')==1){$map['is_tixing']=1;}elseif(I('is_tixing')==2){$map['is_tixing']=0;}
		$date =strtotime("+1week");
		$whereand[]['end_time']=array('ELT',$date);
        $whereand[]['end_time']=array('EGT',NOW_TIME);
		$whereand['_logic'] = 'and';
		$map['_complex'] = $whereand;
		// dump($map);
		$list=$this->lists('MemberBonus',$map);
		$this->assign('list',$list);
		$this->display();
	}
	//代金券到期提醒
	public function tixing(){
		$only=I('get.id');
		if($only){
			$push_info=M('MemberBonus')->alias('mb')->where('mb.bonus_id='.$only)->field('mb.*,m.mobile,m.username')->JOIN('LEFT JOIN __MEMBER__ m ON m.id=mb.user_id')->find();
			if($push_info['mobile']){
				$data=array();
				$data['to']=$push_info['mobile'];
				$sms=sendbytheme($data,'BONU_PUSH');
			}else{
				$this->error('该用户没有绑定手机号！',U('Admin/Bonu/push_bonu'));
			}
			if($sms){
				$tixing['is_tixing']=1;
				$is_tixing=M('MemberBonus')->where('bonus_id='.$only)->save($tixing);
				$this->success('提醒成功！',U('Admin/Bonu/push_bonu'));
			}else{
				$this->error('提醒失败！',U('Admin/Bonu/push_bonu'));
			}
		}
		$info=I('post.');
		if($info){
			$i=0;
			foreach($info['id'] as $k=>$v){
				$push_info=M('MemberBonus')->alias('mb')->where('mb.bonus_id='.$v)->field('mb.*,m.mobile,m.username')->JOIN('LEFT JOIN __MEMBER__ m ON m.id=mb.user_id')->find();
				if($push_info['mobile']){
					$data=array();
					$data['to']=$push_info['mobile'];
					$sms=sendbytheme($data,'BONU_PUSH');
				}else{
					$this->error($push_info['username']."用户没有绑定手机号！",U('Admin/Bonu/push_bonu'));
				}
				if($sms){
					$tixing['is_tixing']=1;
					$is_tixing[$i]=M('MemberBonus')->where('bonus_id='.$v)->save($tixing);
				}
				$i++;
			}
			if($is_tixing){
				$this->success('提醒成功！',U('Admin/Bonu/push_bonu'));
			}else{
				$this->error('提醒失败！',U('Admin/Bonu/push_bonu'));
			}
		}
	}
	//发放用户代金券的页面
	public function user_send(){
		$rank = M('member_rank')->where('status=1')->field('id,name')->select();
		foreach($rank as $value){
			$ranks .="<option value='".$value['id']."'>".$value['name']."</option>";
		}
		$this->assign('rank_list',$ranks);
		$bonu=M('Bonu')->where('id=1')->find();
		$this->assign('edit',$bonu);
		$this->getcateTree($bonu['cat_id']);
		$this->display();
	}
	//线下代金券
	public function down_index(){
		$big_menu = array('生成线下代金券' => U('down_send'));
        $this->assign('big_menu', $big_menu);
		if(I('order')){
			$where['order_id']=I('order');
		}
		if(I('user')){
			$user=I('user');
			if(is_numeric($user)){
			$where_u['id|username']=   array(intval($user),array('like','%'.$user.'%'),'_multi'=>true);
			}else if($user){
			$where_u['username']    =   array('like', '%'.(string)$user.'%');
        	}
			$user_list=M('Member')->where($where_u)->field('id')->select();
			if($user_list){
				foreach($user_list as $k=>$v){
					$u_list[]=$v['id'];
				}
				$where['user_id']=array(array('in',$u_list));
			}
		}
		if(I('use')==1){
			$where['used_time']=array(array('neq',''));
		}elseif(I('use')==2){
			$where['used_time']=array(array('eq',''));
		}		
		$where['bonus_type_id']=4;
		$info=$this->lists('MemberBonus',$where);
		foreach($info as $k=>$v){
			if($v['order_id']){
				$order=M('OrderInfo')->where('id='.$v['order_id'])->field('order_sn')->find();
				$user_info[$k]['order_sn']=$order['order_sn'];
			}else{
				$user_info[$k]['order_sn']=0;
			}
		}
			
		$this->assign('info',$info);
		$this->assign('type_id',$id);
		$this->display();
	}
	//生成线下代金券的页面
	public function down_send(){
		$bonu=M('Bonu')->where('id=4')->find();
		$this->getcateTree($bonu['cat_id']);
		$this->assign('edit',$bonu);
		$this->display();
	}
	//微信代金券
	public function wx_bonu(){
		$big_menu = array('添加微信代金券' => U('add'),'活动设置'=>geturl('set_act'));
        $this->assign('big_menu', $big_menu);
		$name = M('Bonu');
		$info = $name->where('send_type=4')->field(true)->order('id desc')->select();
		$this->assign('list',$info);	
		$this->display();
	}
	//查看微信代金券
	public function wx_bonu_view(){
		$id=I('get.id');
		$name = M('MemberBonus');
		$info = $name->where("bonus_type_id=".$id)->field(true)->select();
		$this->assign('info',$info);	
		$this->display();
	}
	//修改代金券信息
    public function update(){
        $postdata=I('post.');
        $Weixin = new \Common\Vendor\WeixinCoupon();
        $map = array();
        $map['id'] = $postdata['id'];
        $coupon = M('Coupons')->where($map)->field(true)->find();
        if($coupon['card_id']){
	  $postdata['card_id']=$coupon['card_id'];
	  $card = $Weixin->update_coupon($postdata["rank_id"],$postdata,$coupon['card_id']);
        }else{
	  $coupon['act_rang_ext'] = $postdata['act_rang_ext'];
	  $coupon['logo_url'] = $postdata['logo_url'];
	  $coupon['notice'] = $postdata['notice'];
	  $coupon['description'] = $postdata['description'];
	  $coupon['is_type'] = $postdata['is_type'];
	  $coupon['color'] = $postdata['color'];
	  $coupon['service_phone'] = $postdata['service_phone'];
	  $coupon['is_check'] = $postdata['is_check'];
	  $coupon['begin_timestamp']=time_format($coupon['begin_timestamp']);
	  $coupon['end_timestamp']=time_format($coupon['end_timestamp']);
	  $coupon['is_check']=$postdata['is_check'];
	  $card = $Weixin->add_coupon($coupon);
        }
        $url = U(CONTROLLER_NAME.'/index');
        if($card['status'] == 1){
	  $this->success('编辑成功！',$url);
        }else{
	  $this->error('编辑失败！',$url);
        }
    }
	//会员搜索
	public function searchusers(){
		$c = I('get.');
		if(!empty($c['keyword'])){
			$user=$c['keyword'];
			if(is_numeric($user)){
				$map['id|mobile']=   array(intval($user),array('like','%'.$user.'%'),'_multi'=>true);
			}else if($user){
				$map['username']    =   array('like', '%'.(string)$user.'%');
        	}
		}	
		$list =  M('member')->where($map)->field('id,username')->select();
		foreach($list as $value){
			$result.="<option value='".$value['id']."'>".$value['username']."</option>";
		}
		echo $result;exit;
	}
	//加入会员
	public function jia_right(){
		$c = I('get.');
		$user_arr = explode(',',$c['left']);		
		array_pop($user_arr);
		$counts = count($user_arr);
		for($i=0;$i<$counts;$i++){			
			$user = M('member')->where('id='.$user_arr[$i])->field('id,username')->find();			
			$result.="<option value='".$user['id']."' selected='selected'>".$user['username']."</option>";
		}
		echo $result;exit;
	}	
	//注册代金券
	public function register_bonu(){
		if(IS_POST){
			$postdata = I('post.');
			$arr['type_name'] = $postdata['type_name'];
			$arr['type_money'] = $postdata['type_money'];
			$arr['min_goods_amount'] = $postdata['min_goods_amount'];
			$arr['use_start_date'] = 0;
			$arr['use_end_date'] = $postdata['use_end_date'];
			$rez=M('Bonu')->where('send_type=5')->find();
			if ($rez) {
				$goods = M('Bonu')->where('send_type=5')->save($arr);
			}else{
				$arr['send_type']=5;
				$goods = M('Bonu')->add($arr);
			}
			
			if ($goods!==false) {
				$this->success('操作成功');
			}else{
				$this->error('操作失败');
			}
		}else{
			$bonu=M('Bonu')->where('send_type=5')->find();
			$this->assign('edit',$bonu);
			$this->display();
		}
		
	}
	//活动设置
	public function set_act(){
		if (IS_POST) {
			$postdata=I('post.');
			$map['name']='WX_BOUNS_BG';
			$map['status']=1;
			$data['value']='pc_bg:'.$postdata['pc_bg'].',m_bg:'.$postdata['m_bg'].',name:'.$postdata['name'];
			$rez=M('Config')->where($map)->save($data);
			if ($rez!==false) {
				$this->success('设置成功');
			}else{
				$this->error('设置失败');
			}
		}else{
			$act_set=C('WX_BOUNS_BG');
			$this->assign('list',strtoarray($act_set));
			$this->display();
		}
		
	}
	//关联商品搜索 
	public function searchgoods(){
		$c = I('get.');
		$return['status'] = 0;
		if(empty($c['supplier_id'])){
			$return['data'] = "请按供货商搜索";
			$this->ajaxReturn($return);
		}else{
			$map['supplier_id'] = $c['supplier_id'];
		}
		if(!empty($c['keyword']))$map['goods_name'] = array('like','%'.$c['keyword'].'%');
		$map['shangjia'] = 0;
		$map['status'] = 1;
		$map['shang_status'] = 1;
		$goods = M('Goods');
		$list=$goods->where($map)->field('id,goods_name')->select();
		$result='';
		foreach($list as $v){
          $result.="<option value='".$v['id']."'>".$v['goods_name']."</option>";
		}
		$return['status'] = 1;
		$return['data'] = $result;
		$this->ajaxReturn($return);
	}

	// 微信发放优惠券
	public function grant_coupons(){
		$post = I('post.');
		if(!$post['id']){
			$this->error('选择优惠券',U('Admin/WxCoupon/grant_index',array('id'=>$post['id'])));
			exit;
		}
		$map = array();
		$map['id'] = array('in',$post['m_id']);
		$member = M('Member')->where($map)->field('id,wxid')->select();	
		$map = array();
		$map['id'] = array('in',$post['id']);
		$coupons = M('Coupons')->where($map)->find();
		if(!$coupons['card_id']){
			$this->error('该优惠券未同步微信卡券，请重新添加。',U('Admin/WxCoupon/grant_index',array('id'=>$post['id'])));
			exit;
		}
		if(count($member) > $coupons['quantity']){
			$this->error('库存不足',U('Admin/WxCoupon/grant_index',array('id'=>$post['id'])));
		}else{
	        $add_data['coupons_id'] = $coupons['id'];
	        $add_data['card_id'] = $coupons['card_id'];
	        $add_data['rank_id'] = $coupons['rank_id'];
	        $add_data['discount'] = $coupons['discount'];
	        $add_data['reduce_cost'] = $coupons['reduce_cost'];
	        $add_data['least_cost'] = $coupons['least_cost'];
	        $add_data['begin_timestamp'] = $coupons['begin_timestamp'];
	        $add_data['end_timestamp'] = $coupons['end_timestamp'];
	        $add_data['add_time'] = time();
			foreach ($member as $k => $v) {
				$add_data['uid'] = $v['id'];
				$add_data['code'] = base_order().$v['id'];
				$get_w['coupons_id'] = $post['id'];
				$get_w['uid'] = $v['id'];
				$get_w['status'] = 0;
				$add = M('CouponsGet')->add($add_data);					
				if($add)M('Coupons')->where('id='.$post['id'])->setDec('quantity',1);
				if($v['wxid'])$wxid[] = $v['wxid'];
			}
			if(count($wxid) >1 ){					
				$Weixin = new \Common\Vendor\WeixinCoupon();
        		$wxcard = $Weixin->wxcard($wxid,$add_data['card_id']);
			}else{
				$wxids[] = $wxid['0'];
				$wxids[] = $wxid['0'];
				$Weixin = new \Common\Vendor\WeixinCoupon();
        		$wxcard = $Weixin->wxcard($wxids,$add_data['card_id']);
			}
			if($wxcard['errcode'] == 45065){
				$this->success('该优惠券已发放，不可重复发放',U('Admin/WxCoupon/grant_index'));exit;
			}
			if($add && $wxcard['errcode'] == 0){
				$this->success('发放优惠券成功,微信发券成功',U('Admin/WxCoupon/grant_index'));
			}else if($add && !$wxcard['errcode'] == 0){
				$this->success('发放优惠券成功,微信发券失败',U('Admin/WxCoupon/grant_index'));
			}else{
				$this->error('发放优惠券失败',U('Admin/WxCoupon/grant_index'));
			}
		}
	}
	// 微信发券列表
	public function grant_index(){
        $postdata=I('param.');
		$this->getcateTree();
        if($postdata){
        	if(!$postdata['coupons'])$this->error('请选择优惠券');
	        // 会员筛选
	        $uids = 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) {
					$uids[] = $v['uid'];
				}
	        }        
	        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($uids){
//	            $uid = implode(',',array_unique($uids));
	            $map['id']=array('in',$uids);
	        }
			$map = array();
	        $map['status']=array('GT',0);
			//$map['is_tmp'] = 0;
	        if(!empty($postdata['rank_id'])){
	           $map['rank_id']=$postdata['rank_id'];
	        }
	        if($postdata['mobile']){
	            $map['mobile']=$postdata['mobile'];
	        }
	        if($postdata['begin_usepoints'] || $postdata['end_usepoints']){
	            $map['usepoints'] = array(array('gt',$postdata['begin_usepoints']),array('lt',$postdata['end_usepoints']));
	        }
	        if($postdata['begin_money'] || $postdata['end_money']){
	            $map['money'] = array(array('gt',$postdata['begin_money']),array('lt',$postdata['end_money']));
	        }
	        if($postdata['begin_reg_time'] && $postdata['end_reg_time']){
	            $map['card_time'] = array(array('gt',strtotime($postdata['begin_reg_time'])),array('lt',strtotime($postdata['end_reg_time'])));
	        }
	        $data = M('Member')->where($map)->field('id')->select();

	        // 优惠券列表
	        $map = array();
	        $map['id'] = $postdata['coupons'];
	        $coupons = M('Coupons')->where($map)->field('id,title,quantity,brand_name')->find();
			$this->assign($coupons);

	        foreach ($data as $k => $v) {
	            $uidarr[] = $v['id'];
	        }
	        if(!$uidarr)$this->error('该等级暂无会员！');
	        $uidarr = implode(',',$uidarr);
	        
	        $this->assign('count',count($data));
	        $this->assign('m_id',$uidarr);
        	$this->display('grant_coupon');
        }else{
			$this->getGroup(1);
			
	        // 优惠券列表
	        $map = array();
	        $map['status'] = 1;
	        $map['coupons_type'] = 1;
	        $coupon = M('Coupons')->where($map)->field('id,title')->order('sort,id desc')->select();
	        foreach ($coupon as $k => $v) {
	           $coupons[$v['id']] = $v['title'];
	        }
			$this->assign('coupons',$coupons);
        	$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);
    }

    public function statistics(){
        $postdata=I('param.');
        /*会员日增长量统计开始*/
        /*获取当月时间数组开始*/
        $day_arr = array();
        if(empty($postdata['date_from']) || empty($postdata['date_to'])){
	    $j = date(j); //获取当前月份天数
	    $start_time = NOW_TIME;  //获取本月第一天时间戳
	    for($i=0;$i<$j;$i++){
		    $day_arr[date('Y-m-d',$start_time-$i*86400)] = date('Y-m-d',$start_time-$i*86400); //每隔一天赋值给数组
	    }
        }else{
	    $j = (strtotime($postdata['date_to']) - strtotime($postdata['date_from']))/86400;
	    $start_time = strtotime($postdata['date_to']);
	    for($i=0;$i<=$j;$i++){
		    $day_arr[date('Y-m-d',$start_time-$i*86400)] = date('Y-m-d',$start_time-$i*86400); //每隔一天赋值给数组
	    }
        }
        if(empty($postdata['date_to'])){
            $date_tostr=NOW_TIME;
            $postdata['date_to']=time_format($date_tostr,'Y-m-d');
        }
        if(empty($postdata['date_from'])) $postdata['date_from']=time_format(strtotime('-'.($j-1).' day',$date_tostr),'Y-m-d');
		//领券数
        $map=array();
        $map['add_time'][]=array('EGT',strtotime($postdata['date_from']));
        $map['add_time'][]=array('elt',strtotime($postdata['date_to']));
        $map['coupons_type'] = 1;
        $info['lingqu'] = M('CouponsGet')->where($map)->field('count(*) as num,add_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%Y年%m月%d天')")->select();
		//核销数
		$map=array();
        $map['create_time'][]=array('EGT',strtotime($postdata['date_from']));
        $map['create_time'][]=array('elt',strtotime($postdata['date_to']));
        $info['hexiao'] = M('CouponsDonation')->where($map)->field('count(*) as num,create_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y年%m月%d天')")->select();
        //转赠数
        $map=array();
        $map['add_time'][]=array('EGT',strtotime($postdata['date_from']));
        $map['add_time'][]=array('elt',strtotime($postdata['date_to']));
        $map['send_id'][] = array('neq','0');
        $info['zhuanzeng'] = M('CouponsDonation')->where($map)->field('count(*) as num,add_time as mon')->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%Y年%m月%d天')")->select();
        //每个折线的图标代表什么
        $name = array("领券数","核销数","转赠数");
        if($info){
	    foreach($info as $key => $value){
		if(!empty($value)){
		      foreach($value as $k=>$v){
			  $file[$key][date('Y-m-d',$v['mon'])]=$v['num'];
			  $file_time[$key][]=date('Y-m-d',$v['mon']);
		      }
		}else{
		      $file[$key][date('Y-m-d',strtotime($postdata['date_from']))] =0;
		      $file_time[$key][]=date('Y-m-d',strtotime($postdata['date_from']));
		}
	    }unset($value,$key,$k,$v);
        }
        foreach($day_arr as $k => $v){
	  foreach($file_time as $ke=>$ve){
	      if(!in_array($v,$ve)){
		  $file[$ke][$v]=0;
	      }
	  }
        }
        unset($value,$key,$k,$v);
        ksort($file['lingqu']);
        ksort($file['hexiao']);
        ksort($file['zhuanzeng']);
        //得到折线图
        $cz_count = array(
            "legend"=>array('data'=>array($name[0],$name[1],$name[2])),
            "xaxis"=>array("type"=>"category","data"=>array_keys($file['lingqu'])),
            "series"=>array(
	      0=>array("name"=>$name[0],"type"=>"line","stack"=>$name[0],'itemStyle'=>array(),"data"=>array_values($file['lingqu'])),
                1=>array("name"=>$name[1],"type"=>"line","stack"=>$name[1],"data"=>array_values($file['hexiao'])),
                2=>array("name"=>$name[2],"type"=>"line","stack"=>$name[2],"data"=>array_values($file['zhuanzeng'])),
            ),
        );
        $ec = new \Common\Vendor\Echarts();
        $this->assign('Area_count',$ec->show('Area_count',$cz_count,'line','卡券统计'));
        $this->display();
    }
	public function status(){//公共状态
		$mod = D('Coupons');
		$id     = intval(I('id'));
		$type   = trim(I('type'));
		$values = $mod->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=$mod->where('id='.$id)->save($data);
		if(in_array(CONTROLLER_NAME,$this->cache_model)){savecache(CONTROLLER_NAME);}
		$this->ajaxReturn($data[$type]);
	}
    // 优惠券	总领取	总转赠	已过期	已使用  统计
    public function coupon_record(){
        $map = array();
        $map['status'] = 1;
        $coupon = M('Coupons')->where($map)->field('id')->select();
        foreach ($coupon as $k => $v) {
	  $map = array();
	  $map['coupons_id'] = $v['id'];
	    //总领取
	  $data = M('CouponsGet')->where($map)->field('count(id) as coupon_get')->find();
	  $return[$v['id']]['coupon_get'] = $data['coupon_get'];
	    //已过期
	  $map['end_timestamp'] = array(array('lt',NOW_TIME));
	  $data = M('CouponsGet')->where($map)->field('count(id) as coupon_past')->find();
	  $return[$v['id']]['coupon_past'] = $data['coupon_past'];
	    //总转赠
	  $map = array();
	  $map['coupons_id'] = $v['id'];
	  $data = M('CouponsDonation')->where($map)->field('count(id) as coupon_make')->find();
	  $return[$v['id']]['coupon_make'] = $data['coupon_make'];
	    //已使用
	  $map = array();
	  $map['coupons_id'] = $v['id'];
	  $map['status'] = 1;
	  $data = M('CouponsGet')->where($map)->field('count(id) as coupon_use')->find();
	  $return[$v['id']]['coupon_use'] = $data['coupon_use'];
        }
        return $return;
    }
}
?>