<?php
/**
 * 微信优惠券
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <1070309178@qq.com>
 */

namespace Common\Vendor;
class WeixinCoupon{

	/**
	 * 获取保存的accesstoken
	 */
	private function getToken() {
		static $stoken = null;
        $accesstoken='';
        if(C('BOUND_STATUS')==2){//扫码授权
            $wx = new \Common\Vendor\Weixinopen;
            $accesstoken=$wx->get_access_token(C('appid'));
        }else{
			$stoken = S('WX_S_TOKEN');
			if (is_array($stoken)) {
				$nowtime = time();
				// 判断缓存里面的TOKEN保存了多久
				$difftime = $nowtime - $stoken ['tokentime'];
				// TOKEN有效时间7200 判断超过7000就重新获取;
				if ($difftime > 7000) {
					// 去微信获取最新ACCESS_TOKEN
					$accesstoken = $this->getAcessToken();
					$stoken ['tokentime'] = time();
					$stoken ['token'] = $accesstoken;
					// 放进缓存
					S('WX_S_TOKEN', $stoken);
				} else {
					$accesstoken = $stoken ['token'];
				}
			} else {
				// 去微信获取最新ACCESS_TOKEN
				$accesstoken = $this->getAcessToken();
				$stoken ['tokentime'] = time();
				$stoken ['token'] = $accesstoken;
				S('WX_S_TOKEN', $stoken); // 放进缓存
			}
		}
		return $accesstoken;
	}
	/**
	 * 重新从微信获取accesstoken
	 */
	private function getAcessToken() {		
	   $wx = new \Common\Vendor\Jssdk();
       return $wx->getAccessToken();
	}

	/**
	 * 卡券基本数据
	 * @param  string $data 卡券基本数据
	 */
	private function baseinfo($data){
			$url = $this->uploadimg($data['logo_url']);
			$return_data['logo_url'] = $url;//卡券的logo	
			$return_data['code_type'] = CODE_TYPE_QRCODE;//code码展示类型
			$return_data['brand_name'] = $data['brand_name'];//商户名字
			$return_data['title'] = $data['title'];//券名
			$return_data['sub_title'] = $data['sub_title'] ;//..券名副标题
			$return_data['color'] = $data['color'];//券颜色
			$return_data['notice'] = $data['notice'];//使用提醒
			$return_data['service_phone'] = $data['service_phone'];//客服电话
			$return_data['description'] = $data['description'];//使用说明
			if($data['use_limit']){//使用次数限制  默认50
				$return_data['use_limit'] = $data['use_limit'];
			}else{
				$return_data['use_limit'] = 50;
			}
			if($return_data['get_limit']){//领取次数
				$return_data['get_limit'] = $data['get_limit'];
			}else{
				$return_data['get_limit'] = 50;
			}
			if($data['is_show'] == 1){
				$return_data['location_id_list'] = explode(',',$data['location_id_lists']);//适用门店poiid
			}else{
				$return_data['use_all_locations'] = true;//适用全部门店
			}			
			if($data['can_share'] == 1)$return_data['can_share'] = true;//卡券领取页面是否可分享
			if($data['can_give_friend'] == 1)$return_data['can_give_friend'] = true;//卡券是否可转赠。
			$date_info["type"] = 1;
			if($data['type'] == 1){
				$date_info["type"] = 1;
				$date_info["begin_timestamp"] = is_numeric($data["begin_timestamp"])?$data["begin_timestamp"]: strtotime($data["begin_timestamp"]);
				$date_info["end_timestamp"] =is_numeric($data["end_timestamp"])?$data["end_timestamp"]: strtotime($data["end_timestamp"]); 
                if(empty($date_info['begin_timestamp'])){
                    $date_info['begin_timestamp']=NOW_TIME;
                }
                if(empty($date_info['end_timestamp'])){
                    $date_info['end_timestamp']=NOW_TIME+60*60*24*30;
                }
			}else{
				$date_info["type"] = 2;
				$date_info["fixed_term"] = $data['fixed_term'];
				$date_info["fixed_begin_term"] = $data['fixed_begin_term'];
			}
			$return_data['date_info'] = $date_info;//使用日期 有效期的信息.......
			$skus['quantity'] = $data['quantity'];
			$return_data['sku'] = $skus;//商品信息
			$return_data['url_name_type'] = 1;//商户自定义cell名称
			$return_data['custom_url'] = U('Mobile/Member/index','',true,true);//商户自定义url地址
			$return_data['custom_url_name'] = '会员中心';//商户自定义url地址
			return $return_data;
	}
	private function card($card_type,$base_info,$postdata){
		$card_types = array("GENERAL_COUPON","GROUPON", "DISCOUNT","GIFT", "CASH", "MEMBER_CARD","SCENIC_TICKET", "MOVIE_TICKET" );
		$return_data['card_type'] = $card_type;
		switch ($card_type)
		{
			case $card_types[0]:
				$return_data['general_coupon']["base_info"] = $base_info;
				$return_data['general_coupon']["default_detail"] = $postdata['default_detail'];
				break;
			case $card_types[1]:
				$return_data['groupon']["base_info"] = $base_info;
				$return_data['groupon']["deal_detail"] = $postdata['deal_detail'];
				break;
			case $card_types[2]:
				$return_data['discount']["base_info"] = $base_info;
				$return_data['discount']["discount"] = $postdata['discount'];
				break;
			case $card_types[3]:
				$return_data['gift']["base_info"] = $base_info;
				$return_data['gift']["gift"] = $postdata['gift'];
				break;
			case $card_types[4]:
				$return_data['cash']["base_info"] = $base_info;
				$return_data['cash']["least_cost"] = $postdata['least_cost']*100;
				$return_data['cash']["reduce_cost"] = $postdata['reduce_cost']*100;
				break;
			default:
				exit("CardType Error");
		}
		return $return_data;
	}
	// 添加优惠券
    public function add_coupon($postdata){
        if(empty($postdata['logo_url']))$postdata['logo_url']=C('WEB_SMALL_LOGO');
        if(empty($postdata['logo_url']))$postdata['logo_url']='http://mendian.oss-cn-qingdao.aliyuncs.com/uploads/image/20180317/5aaccc52696c7.png';
	  $postdata['logo_url'] = $postdata['logo_url'];
	  $return['status'] = 0;
	  $postdata['begin_timestamp'] = strtotime($postdata['begin_timestamp']);
	  $postdata['end_timestamp'] = strtotime($postdata['end_timestamp']);
	  $postdata['coupons_type'] = 1;
	  $postdata['add_time'] = NOW_TIME;
	  $postdata['status'] = 1;
	  if($postdata['id']){
	      $map = array();
	      $add_id = $map['id'] = $postdata['id'];
	      M('Coupons')->where($map)->save($postdata);
	      $where_ext = array();
	      $where_ext['act_id'] = $postdata['id'];
	      M('PromotExt')->where($where_ext)->delete();
	      if($postdata['act_rang_ext']){
		foreach ($postdata['act_rang_ext'] as $k => $v) {
		    $add['act_id'] = $postdata['id'];
		    $add['style'] = 6;
		    $add['style_ext_id'] = $v;
		    M('PromotExt')->add($add);
		}
	      }
	  }else{
	      $add_id = M('Coupons')->add($postdata);
	      if($postdata['act_rang_ext']){
		foreach ($postdata['act_rang_ext'] as $k => $v) {
		    $add['act_id'] = $add_id;
		    $add['style'] = 6;
		    $add['style_ext_id'] = $v;
		    M('PromotExt')->add($add);
		}
	      }

	  }
	  if(empty($postdata['is_type'])){
	        $return['status'] = 1;
	        if($postdata['id'] && $add_id){
		  $return['msg'] = '编辑成功';
	        }else{
		  $return['msg'] = '添加成功';
	        }
	        return $return;
	  }

	  $baseinfo = $this->baseinfo($postdata);
	  $card = $this->card($postdata['rank_id'],$baseinfo,$postdata);
	  $access_token = $this->getToken();
	  $url = "https://api.weixin.qq.com/card/create?access_token=".$access_token;
	  $post = array(
	      'card'=>$card
	  );
	  $post = json_encode($post, JSON_UNESCAPED_UNICODE);
	  $datas = curlget($url,  $post,'POST', array("Content-type: text/html; charset=utf-8"), true);
	  $coupon = json_decode($datas,true);
	  if($add_id && $coupon['errmsg'] == 'ok'){
	        $save_data['card_id'] = $coupon['card_id'];
	        if($postdata['id']){
		    $where['id'] = $postdata['id'];
		    M('Coupons')->where($where)->save($save_data);
		    $return['status'] = 1;
		    $return['msg'] = '编辑成功';
	        }else{
		    $where['id'] = $add_id;
		    M('Coupons')->where($where)->save($save_data);
		    $return['status'] = 1;
		    $return['msg'] = '添加成功';
	        }
	  }elseif($add_id){
	        $return['status'] = 1;
	        $return['msg'] = '添加成功';
	  }else{
	        $return['status'] = 3;
	        $return['msg'] = '添加失败';
	  }
	  return $return;
    }

	// 优惠券列表
	public function list_coupon($data){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/batchget?access_token=".$access_token;
		$post = array(
			"offset" => 0,
  			"count" => 20,
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		// return $post;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
		$coupon = json_decode($datas,true);
		return $coupon;
	}

	// 查看优惠券
	public function get_coupon($card_id){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/get?access_token=".$access_token;
		$post = array(
			"card_id" => $card_id
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		// return $post;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
		$coupon = json_decode($datas,true);
		return $coupon;
	}

	// 删除优惠券
	public function del_coupon($card_id){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/delete?access_token=".$access_token;
		$post = array(
			"card_id" => $card_id
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		// return $post;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
		$coupon = json_decode($datas,true);
		return $coupon;
	}

	// 生成二维码
	public function get_code($data){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/qrcode/create?access_token=".$access_token;
		if($data['is_unique_code'] == 'true'){
			$post = array(
				"action_name" => "QR_CARD",
				"expire_seconds" => 1800,
				"action_info" => array(
					"card" => array(
						"card_id" => $data["card_id"], 
			            "is_unique_code" => true, 
			            "outer_str" => "12b"
					),
				), 
			);
		}else{
			$post = array(
				"action_name" => "QR_CARD",
				"expire_seconds" => 1800,
				"action_info" => array(
					"card" => array(
						"card_id" => $data["card_id"], 
			            "outer_str" => "12b"
					),
				), 
			);
		}
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
		$coupon = json_decode($datas,true);
		$return['status'] = 0;
		if($coupon['errmsg'] == 'ok'){
			$return['status'] = 1;
			$return['show_qrcode_url'] = $coupon['show_qrcode_url'];
		}
		return $return;
	}

    // 修改优惠券
    public function update_coupon($rank_id,$postdata,$card_id){//strtolower($str)
        $return['status'] = 0;
        $save_data["logo_url"] = $postdata['logo_url'];//商户LOGO
        $save_data["notice"] = $postdata["notice"];//使用提醒
        $save_data["service_phone"] = $postdata["service_phone"];//客服电话
        $save_data["description"] = $postdata["description"];//使用说明
        $save_data["color"] = $postdata['color'];//颜色
        $save_data["is_show"] = $postdata['is_show'];//所属门店
        $save_data["location_id_list"] = $postdata['location_id_list'];//微信门店id
        $save_data["code_type"] = CODE_TYPE_QRCODE;//展示类型
        if ($postdata['card_id']) {
	  $save_data["card_id"] = $postdata['card_id'];//购物券id
        }
        $map = array();
        $map['id'] = $postdata['id'];
        M('Coupons')->where($map)->save($postdata);
        $where_ext = array();
        $where_ext['act_id'] = $postdata['id'];
        M('PromotExt')->where($where_ext)->delete();
        if($postdata['act_rang_ext']){
	  foreach ($postdata['act_rang_ext'] as $k => $v) {
	      $add['act_id'] = $postdata['id'];
	      $add['style'] = 6;
	      $add['style_ext_id'] = $v;
	      M('PromotExt')->add($add);
	  }
        }
        $du_id = M('Coupons')->where('id='.$postdata['id'])->save($save_data);
        if($postdata['is_weixin'] == 'false'){$return['status'] = 1;return $return;}
        if ($postdata['card_id']) {
	  $access_token = $this->getToken();
	  $url = "https://api.weixin.qq.com/card/update?access_token=".$access_token;
	  if($postdata['is_show']){
	      $post = array(
		"card_id" => $card_id,
			    strtolower($rank_id) => array(
				    "base_info" => array(
					    "logo_url" => $postdata['logo_url'],//商户LOGO
					    "notice" => $postdata["notice"],//使用提醒
					    "service_phone" => $postdata["service_phone"],//客服电话
					    "description" => $postdata["description"],//使用说明
					    "color" => $postdata['color'],//颜色
					    "location_id_list" => explode(',',$postdata['location_id_lists']),//适用门店poiid
				    )
			    ),
		    );
	  }else{
	      $post = array(
		      "card_id" => $card_id,
		      strtolower($rank_id) => array(
			      "base_info" => array(
				      "logo_url" => $postdata['logo_url'],//商户LOGO
				      "notice" => $postdata["notice"],//使用提醒
				      "service_phone" => $postdata["service_phone"],//客服电话
				      "description" => $postdata["description"],//使用说明
				      "color" => $postdata['color'],//颜色
				      "use_all_locations" => true,//适用全部门店
			      )
		      ),
	      );
	  }
	  $post = json_encode($post,JSON_UNESCAPED_UNICODE);
	  $datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
	  $coupon = json_decode($datas,true);
        }
        if(($du_id || $du_id == 0) && $coupon['errmsg'] == 'ok'){
	        $return['status'] = 1;
        }elseif($du_id){
	        $return['status'] = 3;
        }
        $return['data'] = $du_id;
        return $return;
    }

	// 修改库存
	public function modifystock($data){
		$where['id'] = $data['id'];
		$quantity = M('Coupons')->where($where)->field('quantity')->find();
		$save_data['quantity'] = $quantity['quantity']+$data['shu'];
		$save_id = M('Coupons')->where($where)->save($save_data);
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/card/modifystock?access_token=".$access_token;
		if($data['shu']>0){
			$post = array(
				"card_id" => $data['card_id'],
				"increase_stock_value"=>$data['shu'],
			);
		}else{
			$post = array(
				"card_id" => $data['card_id'],
				"reduce_stock_value"=>abs($data['shu']),
			);
		}
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$datas = curlget($url,$post,'POST',array("Content-type: text/html; charset=utf-8"),true);
		$coupon = json_decode($datas,true);
		// return $coupon;
		$return['status'] = 0;
		if($save_id && $coupon['errmsg'] == 'ok'){
			$return['status'] = 1;
			$return['id'] = $data['id'];
			$return['shu'] = $save_data['quantity'];
		}elseif($save_id){
			$return['status'] = 1;
			$return['id'] = $data['id'];
			$return['shu'] = $save_data['quantity'];
		}
		return $return;
	}
	/**
	 * 微信发放会员卡
	 * @param  string $wxid 微信id
	 * @param  string $card_id 卡券id
	 */
	public function wxcard($wxid,$card_id){
	   if(!is_array($wxid)){
			$wxid=array($wxid,$wxid);
		}
        $clientmsgid=base_order();
		$post = array(
			'touser' => $wxid,
			'wxcard' => array(
				'card_id' => $card_id
			),
            "clientmsgid"=>$clientmsgid,
			'msgtype' => "wxcard",
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$access_token;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html;charset=utf-8"),true);
		$datas = json_decode($datas,true);
		return $datas;
	}
    public function getmsg($msg_id=''){
        $post = array(
			'msg_id' => $msg_id
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		$access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token=".$access_token;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html;charset=utf-8"),true);
		$datas = json_decode($datas,true);
		return $datas;
    }
    public function settest($openids=''){
		$post = array(
			'openid' => $openids
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		// return $post;
		$access_token = $this->getToken();
        $url = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=".$access_token;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html;charset=utf-8"),true);
		$datas = json_decode($datas,true);
		return $datas;
    }
	// 导入code
	public function code($code,$card_id){		
		$post = array(
			'card_id' => $card_id,
			'code' => $code
		);
		$post = json_encode($post, JSON_UNESCAPED_UNICODE);
		// return $post;
		$access_token = $this->getToken();
		$url = "http://api.weixin.qq.com/card/code/deposit?access_token=".$access_token;
		$datas = curlget($url,$post,'POST',array("Content-type: text/html;charset=utf-8"),true);
		$datas = json_decode($datas,true);
		return $datas;
	}

	// openid
	public function openid(){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token;
		$datas = curlget($url,'','POST');
		$datas = json_decode($datas,true);
		return $datas;
	}
	// 用户信息
	public function user_info($openid){
		$access_token = $this->getToken();
		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$openid;
		$datas = curlget($url);
		$datas = json_decode($datas,true);
		return $datas;
	}
	// 获取api_ticket
	private function getJsApiTicket() {
    static $ticket = null;
    $ticket = S('WX_S_TICKET');
    if(is_array($ticket)){
      $nowtime = time();
      // 判断缓存里面的ticket存多久
      $difftime = $nowtime - $ticket ['expires_in'];
      // 有效时间7200 判断超过7000就重新获取;
      if($difftime > 7200){
        // 去微信从新获取
        $accessticket = $this->api_tickets();
        $ticket['expires_in'] = $accessticket['expires_in'];
        $ticket['ticket'] = $accessticket['ticket'];
        // 放入缓存
        S('WX_S_TICKET',$ticket);
      }else{
        $accessticket = $ticket;
      }
    }else{
      // 去微信从新获取
        $accessticket = $this->api_tickets();
        $ticket['expires_in'] = $accessticket['expires_in'];
        $ticket['ticket'] = $accessticket['ticket'];
        // 放入缓存
        S('WX_S_TICKET',$ticket);      
    }
    return $accessticket['ticket'];
  }
  private function api_tickets() {
    $access_token = $this->getToken();
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=wx_card";
    $datas = curlget($url);
    $res = json_decode($datas,true);
    return $res;
  }
  private function createNonceStr($length = 16) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
      $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
  }

  public function token(){
  	$access_token = $this->getToken();
  	return $access_token;
  }
  public function AddCartParam($card_id,$openid){
  	$time_temp = time();
  	$nonce_str = $this->createNonceStr();
  	$ticket = $this->getJsApiTicket();
  	$sign_arr = array();
  	array_push($sign_arr,$ticket);//api_ticket
  	array_push($sign_arr,$nonce_str);
  	array_push($sign_arr,$card_id);//card_id
  	//array_push($sign_arr,$openid);//openid
  	sort($sign_arr,SORT_STRING);
  	$signature = sha1($time_temp.implode($sign_arr));
  	$ext_arr = array(
  		'timestamp' =>$time_temp,
  		// 'openid'    =>$openid,
  		'nonce_str' => $nonce_str,
  		'signature' =>$signature
  	);
  	$gift_temp_re = array(
  		'cardId'    => $card_id,
  		'cardExt'   => $ext_arr
  	);
  	return $gift_temp_re;
  }

  	/**
	 * 查询Code接口
	 * @param  string $code 卡券code
	 */
  	public function cancel($code) {
	    $access_token = $this->getToken();
	    $data = array(
	    	"code"  => $code,
	    	"check_consume" => true,
	    );
	    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
	    // return $data;
	    $url = "https://api.weixin.qq.com/card/code/get?access_token=".$access_token;
	    $datas = curlget($url,$data,'POST',array("Content-type: text/html; charset=utf-8"),true);
	    $res = json_decode($datas,true);
	    return $res;
	}

	/**
	 * 核销接口
	 * @param  string $id 会员领券表id
	 */
	public function query_code($id,$code) {
		if($id){
			$map['id'] = $id;
	        $coupons_get = M('CouponsGet')->where($map)->field('card_id')->find();
	    }
		$cancel = $this->cancel($code);
		$return['status'] = 0;
		if($cancel['user_card_status'] == 'CONSUMED'){
			$return['msg'] = '已核销';
			return $return;
		}elseif($cancel['user_card_status'] == 'EXPIRE'){
			$return['msg'] = '已过期';
			return $return;
		}elseif($cancel['user_card_status'] == 'GIFTING'){
			$return['msg'] = '转赠中';
			return $return;
		}elseif($cancel['user_card_status'] == 'GIFT_TIMEOUT'){
			$return['msg'] = '转赠超时';
			return $return;
		}elseif($cancel['user_card_status'] == 'DELETE'){
			$return['msg'] = '已删除';
			return $return;
		}elseif($cancel['user_card_status'] == 'UNAVAILABLE'){
			$return['msg'] = '已失效';
			return $return;
		}elseif($cancel["errcode"] == 40056){
			$return['msg'] = '卡券未领取加或被转赠领取';
			return $return;
		}
	    $access_token = $this->getToken();
	    if($id){
		    $data = array(
		    	"code"  => $code,
		    	"card_id" => $coupons_get['card_id']
		    );
		}else{
			$data = array(
		    	"code"  => $code
		    );
		}
	    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
	    $url = "https://api.weixin.qq.com/card/code/consume?access_token=".$access_token;
	    $datas = curlget($url,$data,'POST',array("Content-type: text/html; charset=utf-8"),true);
	    $res = json_decode($datas,true);
	    if($res['errcode'] == 0){
	    	$return['status'] = 1;
	    	$return['msg'] = '核销成功';
	    }else{
	    	$return['status'] = 0;
	    	$return['msg'] = '核销失败';
	    }
	    return $return;
	}
	/**
	 * 全民发券立即领取
	 * @param  string $data 活动id 会员id
	 */
	public function get_award($data){
		$map_s['id'] = $data['act_id'];
		$map_s['class'] = 1;
		$coupon_send = M('ReceiptDraw')->where($map_s)->field('event_confine,end_time,aging')->find();
		
		$map_p = array();$map_p['uid'] = $data['uid'];
        $map_p['act_id'] = $data['act_id'];
        $qq_count = M('Participation')->where($map_p)->field(true)->find();
		
		$map_d = array();
		if($coupon_send['event_confine'] == 0){
			$aging = $qq_count['time']+$coupon_send['aging']*60;//时效转换为秒
			$map_m=array();$map_m['id'] = array('gt',0);
			if($data['end_time'] >= $aging){//注册时间
				$map_m['reg_time'] = array(array('gt',$qq_count['time']),array('lt',$aging));
			}else{
				$map_m['reg_time'] = array(array('gt',$qq_count['time']),array('lt',$coupon_send['end_time']));
			}
			$uids = M('Member')->where($map_m)->getField('id',true);
			if($uids){
				$uidss = array_unique($uids);
				$map_d['receive_id']=array('in',$uidss);
			}else{
				$map_d['receive_id']=array('in','');
			}
		}
		$map_d['add_time'] = array(array('gt',$qq_count['time']),array('lt',$coupon_send['end_time']));
		$map_d['send_id'] = $data['uid'];
		$count = M('CouponsDonation')->where($map_d)->group('receive_id')->field('id')->select();
		$count = count($count);
		$where_p['act_id'] = $data['act_id'];
		$where_p['class'] = 1;
		$prize = M('Prize')->where($where_p)->field(true)->select();
		foreach ($prize as $k => $v) {
			if($count >= $v['goods_num']){
				$return['status'] = 1;
				$return['data'] = $v;
				break;
			}
		}
		if(!$return['data']){
			$return['status'] = 0;
			$return['mag'] = '未达到领奖条件！';
		}else{
			if($return['data']['prize_type'] == 1){//礼品
				$save_data = array();
				$save_data['sn_number'] = createOrderNo();
				$save_data['gift_id'] = $return['data']['id'];
				$save_data['gift_type'] = 0;
				$save_data['win_type'] = 4;
				$save_data['user_id'] = $data['uid'];
				$save_data['check_status'] = 0;
				$save_data['gift_number'] = 1;
				$save_data['add_time'] = NOW_TIME;
				M('WinGift')->add($save_data);
				$return['mag'] = '实物奖品，请前往门店领取！';
			}
			if($return['data']['prize_type'] == 2){//现金
				$save_data = array();
				$save_data['sn_number'] = createOrderNo();
				$save_data['gift_id'] = $return['data']['id'];
				$save_data['gift_name'] = '现金';
				$save_data['gift_type'] = 1;
				$save_data['win_type'] = 4;
				$save_data['user_id'] = $data['uid'];
				$save_data['check_status'] = 1;
				$save_data['check_time'] = $save_data['add_time'] = NOW_TIME;
				$save_data['gift_number'] = $return['data']['prize_goods'];
				M('WinGift')->add($save_data);
				
				account_change(MID,$return['data']['prize_goods'],1,15,'全民发券领奖');
				$return['mag'] = $return['data']['prize_goods'].'现金';
			}
			if($return['data']['prize_type'] == 3){//积分
				$save_data = array();
				$save_data['sn_number'] = createOrderNo();
				$save_data['gift_id'] = $return['data']['id'];
				$save_data['gift_name'] = '积分';
				$save_data['gift_type'] = 1;
				$save_data['win_type'] = 4;
				$save_data['user_id'] = $data['uid'];
				$save_data['check_status'] = 1;
				$save_data['check_time'] = $save_data['add_time'] = NOW_TIME;
				$save_data['gift_number'] = $return['data']['prize_goods'];
				M('WinGift')->add($save_data);
				
				account_change(MID,$return['data']['prize_goods'],4,15,'全民发券领奖');
				$return['mag'] = $return['data']['prize_goods'].'积分';
			}
			if($return['data']['prize_type'] == 4){//优惠券
				$c_map = array();$c_map['id'] = $return['data']['prize_goods'];
				$c_map['quantity'] = array('gt',0);$c_map['status'] = 1;
				$coupons = M('Coupons')->where($c_map)->field(true)->find();
				
				if($coupons){
					$save_data = array();
					$save_data['sn_number'] = createOrderNo();
					$save_data['gift_id'] = $return['data']['id'];
					$save_data['gift_type'] = 1;
					$save_data['win_type'] = 4;
					$save_data['user_id'] = $data['uid'];
					$save_data['check_status'] = 0;
					$save_data['gift_number'] = 1;
					$save_data['add_time'] = NOW_TIME;
					$w_id = M('WinGift')->add($save_data);
					$return['mag'] = '优惠券奖品，请及时领取！';
					
					$add_data = array();
					$map=array();$map['id']=$data['uid'];
					$member_info=M("Member")->where($map)->field('mobile,username,nickname')->find();
					$add_data['to']=$member_info['mobile'];
					if($member_info['username']){
						$add_data['user_name']=$member_info['username'];
					}elseif($member_info['nickname']){
						$add_data['user_name']=$member_info['nickname'];
					}else{
						$add_data['user_name']=$member_info['mobile'];
					}
					$add_data['first'] = '全民发券赠券';
					$add_data['goods_name']=$coupons['title'];
					$add_data['send_time'] = date('Y-m-d H:i:s',NOW_TIME);
					$add_data['remark'] = "尊敬的会员，您获得一张卡券，请及时领取";
					$add_data['type'] = 4;
					$add_data['content'] = "请领取卡券";
					$url=U("Mobile/Index/coupons_give",array('id'=>$coupons['id'],'type'=>4,'order_id'=>$w_id),true,true);
					sendbytheme($add_data,"MEMBER_CARE",$url);
				}else{
					$return['status'] = 0;
					$return['mag'] = '优惠券已领完';
				}
			}
		}
		return $return;
	}
	/**
	 * 获取门店信息列表
	 */
	public function get_store_list($code) {
	    $access_token = $this->getToken();
	    $data = array(
	    	"offset"  => 0,
	    	"limit" => 10,
	    );
	    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
	    // return $data;
	    $url = "https://api.weixin.qq.com/wxa/get_store_list?access_token=".$access_token;
	    $datas = curlget($url,$data,'POST',array("Content-type: text/html; charset=utf-8"),true);
	    $res = json_decode($datas,true);
	    return $res;
	}
	/**
	 * 上传图片信息
	 */
	public function uploadimg($wx_url){
		$wx_url = format_url($wx_url,1);
		$yuan_img = file_get_contents($wx_url);// $wx_url前面必须加 http://
		// $yuan_img = file_get_contents($wx_url);
		$linshiimg = ROOT_PATH."/uploads/thumb/".randStr(8,'1234567890').".jpg";//临时图片;
		file_put_contents($linshiimg,$yuan_img);
		$url=format_url($linshiimg,2);
		$data = str_replace("\\","/",$url);
		$access_token = $this->getToken();
		//1.创建一个新cURL资源
		$ch = curl_init();
		//2.设置URL和相应的选项
		$curl = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$access_token;
		$data = array('media'=>'@'.$data); 
		curl_setopt($ch, CURLOPT_URL, $curl);
		//启用时会将头文件的信息作为数据流输出。        
	    curl_setopt($ch, CURLOPT_HEADER, false);
	    //将curl_exec()获取的信息以字符串返回，而不是直接输出。
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);  
	    //FALSE 禁止 cURL 验证对等证书（peer's certificate）。    
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);      
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  //验证主机 
         //发送 POST 请求    
        curl_setopt($ch, CURLOPT_POST, true);     
        //全部数据使用HTTP协议中的 "POST" 操作来发送。          
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //3.抓取URL并把它传递给浏览器    
    	$content = curl_exec($ch); 
    	//4.关闭cURL资源，并且释放系统资源    
    	curl_close($ch); 
    	$res = json_decode($content,true);
    	if($res){
    		unlink($linshiimg);
    	}
    	return $res['url'];

	}
	/**
	 * 创建二维码接口
	 * @param  string $card_id 优惠券id
	 */
	public function create($card_id){
		$card['card']['card_id'] = $card_id;
	    $data = array(
	    	"action_name"  => "QR_CARD",
	    	"action_info" => $card,
	    );
		$access_token = $this->getToken();
	    $data = json_encode($data,JSON_UNESCAPED_UNICODE);
	    $url = "https://api.weixin.qq.com/card/qrcode/create?access_token=".$access_token;
	    $datas = curlget($url,$data,'POST',array("Content-type: text/html; charset=utf-8"),true);
	    $res = json_decode($datas,true);
	    if($res['errcode'] == 0){
	    	$return['status'] = 1;
	    	$return['data'] = $res;
	    }else{
	    	$return['status'] = 2;
	    	$return['msg'] = '生成二维码失败';
	    }
	    return $return;
	}
}
?>