<?php
namespace weixin;
use think\facade\Cache;
/**
* 微信直播
*/
class WechatLive{

	public $config;
	public function __construct($config=[]) {   
        $this->config = (object)$config;
    }
    //创建房间
    public function createRoom($room=[]){
    	$token=self::getAcccessToken();
    	if($token['code']!=0){
    		return '已过期';
    	}
    	$url="https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token=".$token['data'];
    	$room=[
    		  "name"=>"测试直播房间55",  // 房间名字
		      "coverImg"=>"YL7UmRtOVDupvLt23dvvF4x9Q8hiCh0VWMPvq8okprzoADVb-l7TNDBM0fQVGozp",   // 通过 uploadfile 上传，填写 mediaID
		      "startTime"=>time()+(60*20),   // 开始时间
		      "endTime"=>time()+(60*60) , // 结束时间
		      "anchorName"=>"隔壁老张",  // 主播昵称
		      "anchorWechat"=>"panfh88888",  // 主播微信号
		      "shareImg"=>"YL7UmRtOVDupvLt23dvvF4x9Q8hiCh0VWMPvq8okprzoADVb-l7TNDBM0fQVGozp" ,  //通过 uploadfile 上传，填写 mediaID
		      "type"=>0 , // 直播类型，1 推流 0 手机直播
		      "screenType"=>0,  // 1：横屏 0：竖屏
		      "closeLike"=>0 , // 是否 关闭点赞 1 关闭
		      "closeGoods"=>0, // 是否 关闭商品货架，1：关闭
		      "closeComment"=>0 // 是否开启评论，1：关闭
    	];
    	$res=self::setHttpRequest($url,$room);
    }
    public function roomList(){
    	$token=self::getAcccessToken();
    	if($token['code']!=0){
    		return '已过期';
    	}
    	$url="https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=".$token['data'];
    	$requst=[
		    "start"=>0, // 起始拉取房间，start = 0 表示从第 1 个房间开始拉取
		    "limit"=>10 // 每次拉取的个数上限，不要设置过大，建议 100 以内
		];
    	$res=self::setHttpRequest($url,$requst);
    	if($res->errcode==0){
    		return ['code'=>0,'msg'=>'获取成功','data'=>object_to_array($res->room_info)];
    	}else{
    		return ['code'=>1,'msg'=>$res->errmsg,'data'=>$res->errcode];
    	}

    }

    public function uploaImage(){
    	$data=self::getAcccessToken();
    	$url="http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={$data}&type=image";

	   // $res=self::setHttpRequest($url,['media'=>'']);
    	p($data);
    }
	public function getAcccessToken(){
	    $access_token=Cache::get('access_token_'.$this->config->appid);
	    if ($access_token) {
	        return ['code'=>0,'msg'=>'','data'=>$access_token];
	    }
	    $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->config->appid}&secret={$this->config->app_secret}";
	    $res=self::setHttpRequest($url);
	    if(isset($res->access_token)){
	      Cache::set('access_token_'.$this->config->appid,$res->access_token,3600);
	      return ['code'=>0,'msg'=>'','data'=>$res->access_token];
	    }else{
	      return ['code'=>$res->errcode,'data'=>'','msg'=>$res->errmsg];
	    }
	}  
	public  function setHttpRequest($url,$params=array(),$headers='',$method="POST") {
		$params=json_encode($params);
        set_time_limit(0);
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        if($headers!=""){
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        }else {
            curl_setopt($ci, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
        }
        switch (strtoupper($method)){
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'PUT':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'PATCH':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'PATCH');
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            default:
                curl_setopt($ci, CURLOPT_HTTPGET, TRUE);
                break;
        }
        $response = curl_exec($ci);
        $httpCode = curl_getinfo($ci);
        curl_close($ci);
        return json_decode($response);
    }


}
/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
 
    return $obj;
}