<?php
/**
 * @author xiaogg QQ:756663992
 * @copyright 2014
 */
namespace Admin\Controller;
class BonuController extends BaseController {
	//查看红包类型
    public function promot_index(){
		$map['send_type']=5;
		$map['bonu_type'] = 1;
        // $postdata = I('post.');
        // $s_id_map=D('Shops')->get_shop_ids($postdata);
        // if ($s_id_map) {
        //     $map['shop_id'] = $s_id_map;
        // }
		$info=$this->lists('Bonu',$map);
		$this->assign('list',$info);
		$this->display();
    }
	
	
	public function insert(){
		$postdata=I('post.');
        if(empty($postdata['type_value'])&&$postdata['type']!=3)$this->error('请选择类型值！');
		$num=C('WIN_BONUS_NUM');
		//echo $send_type;
		$arr['type_name'] = $postdata['type_name'];
		$arr['type_money'] = $postdata['type_money'];
		$arr['min_goods_amount'] = $postdata['min_goods_amount'];
		if($postdata['type'] != 3){
			$arr['every_num'] = $postdata['every_num'];
			$arr['odds'] = $postdata['every_num']/$num*100;
			$arr['send_type'] = 4;
			$arr['use_start_date'] = strtotime($postdata['use_start_date']);
			$arr['use_end_date'] = strtotime($postdata['use_end_date']);
			$url=U(CONTROLLER_NAME.'/wx_bonu');
		}else{
			if($postdata['type_value']){
				$promot_info=M('PromotAct')->where('id='.$postdata['type_value'])->field('start_time,end_time')->find();
				$arr['use_start_date'] = $promot_info['start_time'];
				$arr['use_end_date'] = $promot_info['end_time'];
			}else{
				$arr['use_start_date'] = strtotime($postdata['use_start_date']);
				$arr['use_end_date'] = strtotime($postdata['use_end_date']);
			}
			$arr['send_type'] = 5;
			$url=U(CONTROLLER_NAME.'/promot_index');
		}
		$arr['type'] = $postdata['type'];
		$arr['type_value'] = $postdata['type_value'];
		$goods = M('Bonu')->add($arr);
		if($goods!==false){
			$this->success('添加成功！',$url);
		} else {
			$this->error('添加失败！',$url);
		}
	}
	//查看
	 public function view(){
	    $id = I('id');
		$model = D('Bonu');
		$info = $model->field(true)->find($id);
		$this->assign($info);
		$this->getcateTree($info['cat_id']);
		$this->display();
  }
	//删除微信红包
	public function delete(){
		$postdate=I('param.');
		$map['id']=array('in',$postdate['id']);
		// $id  = I('get.id');
		$deletes = M('Bonu')->where($map)->delete();
		if($deletes){
			$this->success('删除成功！');
	 	} else {
			$this->error('删除失败！');
	 	}
	}
	//删除已发放的红包
	public function delete_user(){
		$para  = I('param.');
		$where['id']=array('in',$para['id']);
		$deletes=M('MemberBonus')->where($where)->delete();
		if($deletes){
			$this->success('删除成功！');
	 	} else {
			$this->error('删除失败！');
	 	}
	}
	//编辑
	public function edit(){
		$id=I('get.id');
		$edit = M('Bonu');
		$edits = $edit->where('id='.$id)->field(true)->find();
		if(!$edits['type'])$edits['type']=1;
		if($edits['type'] == 3){$edits['is_promot']=1;}
		$num=C('WIN_BONUS_NUM');
		$this->assign('num', $num);
		$this->assign('id', $id);
        $this->assign($edits);
		if($edits['type'] == 1){
			$this->getcateTree($edits['type_value']);
		}else{
			$this->getcateTree();
		}
        $this->display();
	}
	//编辑
	public function _before_add(){
		$this->getcateTree();
		$is_promot=I('style');
		if(isset($is_promot)){
			$this->assign('is_promot', $is_promot);
		}else{
			$this->assign('is_promot', 0);
		}
		$this->assign('style', 1);
		//print_r($type);
	}
	//用户发放处理
	 public function send_user(){
		 $url = U('Admin/Bonu/index_user');
		$postdata=I('post.');
         		if(empty($postdata['cat_id']) && empty($postdata['brand_id']))$this->error('请选择类型值！',$url);
		$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['type'] = $postdata['type'];
		if(!empty($postdata['cat_id'])){
			$arr['type_value']=$postdata['cat_id'];
		}else{
			$arr['type_value'] = $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_name'] = $postdata['type_name'];
				$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['type'] = $postdata['type'];
				if(!empty($postdata['cat_id'])){
					$arra['type_value']=$postdata['cat_id'];
				}else{
					$arra['type_value'] = $postdata['brand_id'];	
				}
				$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_name'] = $postdata['type_name'];
			                    	$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['type'] = $postdata['type'];
                    				if(!empty($postdata['cat_id'])){
						$arra['type_value']=$postdata['cat_id'];
					}else{
						$arra['type_value'] = $postdata['brand_id'];	
					}
                    				$sql_f = M('MemberBonus')->add($arra);
				}
		}
		if($sql_f){
			$this->success('发放成功！',$url);
	 	} else {
			$this->error('发放失败！',$url);
	 	}
	}
	//用户红包
	public function index_user(){
		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->display();
	}
	public function push_bonu(){
		$map['user_id']=array(array('GT','0'));
		$map['used_time']=0;
		if(I('name')){
			$bo=I('name');
			if(is_numeric($bo)){
			$where_u['id|type_name']=   array(intval($bo),array('like','%'.$bo.'%'),'_multi'=>true);
			}else if($bo){
			$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(array('in',$b_list));
			}
		}
		if(I('member')){
			$user=I('member');
			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'];
				}
				$map['user_id']=array(array('in',$u_list));
			}
		}
		if(I('is_tixing')==1){$map['is_tixing']=1;}elseif(I('is_tixing')==2){$map['is_tixing']=0;}
		$date =strtotime("-7day");
		$whereand[]['end_time']=array('EGT',$date);
        $whereand[]['end_time']=array('ELT',NOW_TIME);
		$whereand['_logic'] = 'and';
		$map['_complex'] = $whereand;
		//print_r($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.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['to']=$push_info['mobile'];
				$sms=sendbytheme($data,'BONU_PUSH');
			}elseif(!$push_info['mobile']){
				$this->error('该用户没有绑定手机号！',U('Admin/Bonu/push_bonu'));
			}
			if($sms){
				$tixing['is_tixing']=1;
				$is_tixing=M('MemberBonus')->where('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.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['to']=$push_info['mobile'];
					$sms=sendbytheme($data,'BONU_PUSH');
				}elseif(!$push_info['mobile']){
					$this->error($push_info['username']."用户没有绑定手机号！",U('Admin/Bonu/push_bonu'));
				}
				if($sms){
					$tixing['is_tixing']=1;
					$is_tixing[$i]=M('MemberBonus')->where('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_index_add(){
		$rank = M('member_rank')->where('status=1')->field('id,name')->select();
        $ranks='';
		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['type_value']);
		$this->display();
	}
    //线下发放处理
    public function send_oline(){
        $postdata = I('post.');
        if(empty($postdata['cat_id']) && empty($postdata['brand_id']))$this->error('请选择类型值！');
        $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['type'] = $postdata['type'];
        if(!empty($postdata['cat_id'])){
            $arr['type_value'] = $postdata['cat_id'];
        }else{
            $arr['type_value'] = $postdata['brand_id'];
        }
        $bonus_sum = !empty($_POST['bonus_sum'])     ? $_POST['bonus_sum']     : 1;
        if(!$bonus_sum)$this->error('请添加数量！');
        //随机生成红包序列号
        $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++){
            $arr['bonus_name'] = $postdata['type_name'];
            $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['type'] = $postdata['type'];
            if(!empty($postdata['cat_id'])){
                $arr['type_value'] = $postdata['cat_id'];
            }else{
                $arr['type_value'] = $postdata['brand_id'];
            }
            $arr['start_time'] = $use_start_date;
            $arr['end_time'] = $use_end_date;
            //print_r($arr);exit;
            $sql = $info->add($arr);
        }
        if($sql!==false){
            $url = U('Admin/Bonu/down_index');
            $this->success('发放成功！',$url);
        } else {
            $this->error('发放失败！');
        }
    }
	//线下红包
	public function down_index(){
        $postdata = I('post.');
        $s_id_map=D('Shops')->get_shop_ids($postdata);
        if ($s_id_map) {
            $where['shop_id'] = $s_id_map;
        }
		$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();
				$info[$k]['order_sn']=$order['order_sn'];
			}else{
				$info[$k]['order_sn']=0;
			}
		}

		$this->assign('info',$info);
		$this->display();
	}
	//生成线下红包的页面
	public function down_index_add(){
		$bonu=M('Bonu')->where('id=4')->find();
		$this->getcateTree($bonu['cat_id']);
		$this->assign('edit',$bonu);
		$this->display();
	}
	//微信红包
	public function wx_bonu(){
		$map['send_type']=4;
		$info=$this->lists('Bonu',$map);
		$this->assign('list',$info);
		$this->display();
	}
	//查看微信红包
	public function wx_bonu_view(){
		$name = M('MemberBonus');
        $postdata = I('param.');
       if(isset($postdata['keyword'])){
           $order['order_sn']=$postdata['keyword'];
            $map['order_id']=M("OrderInfo")->where($order)->getField('id');
       }
        if(isset($postdata['user'])){
            $whereor['id']=array('like','%'.$postdata['user'].'%');
            $whereor['username']=array('like','%'.$postdata['user'].'%');
            $whereor['mobile']=array('like','%'.$postdata['user'].'%');
            $whereor['_logic'] = 'or';
            $member['_complex'] = $whereor;
            $map['order_id']=M("Member")->where($member)->getField('id');
        }
        $map['bonus_type_id']=4;
		$map['id']=$postdata['id'];
		$info = $name->where($map)->field(true)->select();
		$this->assign('list',$info);
        $this->assign($postdata);
		$this->display();
	}
	//修改红包信息
	public function update(){
		$postdata=I('post.');
        if(empty($postdata['type_value']))$this->error('请选择类型值！');
		$num=C('WIN_BONUS_NUM');
		//echo $send_type;
		$arr['type_name'] = $postdata['type_name'];
		$arr['type_money'] = $postdata['type_money'];
		$arr['min_goods_amount'] = $postdata['min_goods_amount'];
		if($postdata['type'] != 3){
			$arr['every_num'] = $postdata['every_num'];
			$arr['odds'] = $postdata['every_num']/$num*100;
			$arr['send_type'] = 4;
			$arr['use_start_date'] = strtotime($postdata['use_start_date']);
			$arr['use_end_date'] = strtotime($postdata['use_end_date']);
			$url=U(CONTROLLER_NAME.'/wx_bonu');
		}else{
			$promot_info=M('PromotAct')->where('id='.$postdata['type_value'])->field('start_time,end_time')->find();
			$arr['use_start_date'] = $promot_info['start_time'];
			$arr['use_end_date'] = $promot_info['end_time'];
			$arr['send_type'] = 5;
			$url=U(CONTROLLER_NAME.'/promot_index');
		}
		$arr['type'] = $postdata['type'];
		$arr['type_value'] = $postdata['type_value'];
		$wh_b['id']=$postdata['id'];
		$goods = M('Bonu')->where($wh_b)->save($arr);
		if($goods!==false){
			$this->success('编辑成功！',$url);
		} else {
			$this->error('编辑失败！',$url);
		}
	}
	private function getcateTree($pid = '',$assign='') {
		$GoodsCategory = getcache('GoodsCategory');
		$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);
		$wh['status']=1;
		$brand=M('Brand')->where($wh)->field('id,brand_name')->select();
		$this->assign('brand_list',$brand);
		$wh_promot['is_group']=0;
		$promot=M('PromotAct')->where($wh_promot)->field('id,act_name')->select();
		$this->assign('promot_list',$promot);
	}
	//会员搜索
	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();
        $result='';
		foreach($list as $value){
			$result.="<option value='".$value['id']."'>".$value['username']."</option>";
		}
		echo $result;exit;
	}
	//仓库代金券
	public function shop_bonu(){
		$postdata = I('param.');
        if ($postdata['keyword']) {
            $map['type_name'] = $postdata['keyword'];
        }
		
		$map['bonu_type'] = 2;
		$info=$this->lists('Bonu',$map);
		$this->assign('list',$info);
    	$this->assign('postdata', $postdata);
    	$this->display();
	}
	public function shop_add(){
		$shopsData = getShops();
		$this->assign('shopsData',$shopsData);
		$this->display('shop_edit');
	}
	public function shop_edit(){
		$id=I('param.id');
    	$this->assign('id', $id);
		
		$edits = M('Bonu')->where('id='.$id)->field(true)->find();
		
		if($edits['shop_id']){
			$shopids = array_filter(explode(',', $edits['shop_id']));
			foreach($shopids as $k=>$v){
				$edits['shop_arr'][$v] = idtoname($v,'Shops','name');
			}
			$edits['shop_check'] = implode(',',array_keys($edits['shop_arr']));
		}
		// print_r($edits);exit;
    	$this->assign($edits);
		
		$shopsData = getShops();
		$this->assign('shopsData',$shopsData);
		$this->display();
	}
	//创建新代金券
	public function shop_insert(){
		$postdata=I('param.');
		$postdata['use_start_date'] = strtotime($postdata['use_start_date']);
		$postdata['use_end_date'] = strtotime($postdata['use_end_date']);
		$postdata['add_time'] = NOW_TIME;
		if($postdata['is_show'] == 0){
			$postdata['shop_id'] = 0;
		}else{
			if($postdata['shop_ids'])$postdata['shop_id'] = ','.implode(',',$postdata['shop_ids']).',';
		}
		$postdata['bonu_type'] = 2;
		$postdata['type'] = 0;
		$postdata['type_value'] = 0;
		unset($postdata['is_show']);

		// 添加代金券
		$add_coupon = M('Bonu')->add($postdata);
		if($add_coupon){
			$url = U('Admin/Bonu/shop_bonu');
			$this->success('添加成功！',$url);
		}else{
			$url = U('Admin/Bonu/shop_add');
			$this->error('添加失败！',$url);
		}
	}
	//修改代金券信息
	public function shop_update(){
		$postdata=I('param.');//id
		$id = $postdata['id'];
		unset($postdata['id']);
		
		if($postdata['shop_ids'])$postdata['shop_id'] = ','.implode(',',$postdata['shop_ids']).',';
		$postdata['use_start_date'] = strtotime($postdata['use_start_date']);
		$postdata['use_end_date'] = strtotime($postdata['use_end_date']);
		$postdata['bonu_type'] = 2;
		$postdata['type'] = 0;
		$postdata['type_value'] = 0;
		
		$map['id'] = $id;
		$result = M('Bonu')->where($map)->save($postdata);
		$url = U(CONTROLLER_NAME.'/shop_bonu');
		if($result == 1){
			$this->success('编辑成功！',$url);
		}else{
			$this->error('没有编辑任何项！',$url);
		}
	}
}
?>