<?php
namespace slock;
use think\facade\Cache;

/**
* 通通锁
* 对接文档：http://doc.door.openapi.horniot.com/#/xsj/
*/
class Ttlock{
	
	public $client_id="3932595c8db9475292e4597a6c04b263";

	public $client_secret="39eccea4df2d223a4c4e3910cfb0cbf5";

	private $api_url="https://api.ttlock.com/";

	public $username="";
	
	public $password="";

	public function __construct($config=[]){
		$this->username=isset($config['tt_lock_username'])?$config['tt_lock_username']:'';
		$this->password=isset($config['tt_lock_password'])?$config['tt_lock_password']:'';
	}
	//获取令牌
	public function getToken(){
		$url=$this->api_url."oauth2/token";
		$params['client_id']=$this->client_id;
		$params['client_secret']=$this->client_secret;
		$params['username']=$this->username;
		$params['password']=$this->password;
		$token=Cache::get('ttlock_'.$this->client_id);
		if($token){
			return ['code'=>0,"data"=>$token];
		}
		$res=self::httpRequest($url,"POST",$params);
		$res=json_decode($res,1);
		if(isset($res['access_token'])){
			Cache::set('ttlock_'.$this->client_id,$res['access_token'],600);
			return ['code'=>0,"data"=>$res['access_token']];
		}else{
			return ['code'=>1,"msg"=>"获取令牌错误"];
		}
	}
	public function unlock($lockId=""){
		$url=$this->api_url."v3/lock/unlock";
		$params['clientId']=$this->client_id;
		$token=self::getToken();
		if($token['code']==1){
			return ['code'=>1,"msg"=>"获取令牌错误"];
		}
		$params['accessToken']=$token['data'];
		$params['lockId']=$lockId;
		$params['date']=time()*1000;
		$res=self::httpRequest($url,"POST",$params);
		$res=json_decode($res,1);
		if($res['errcode']==0){
			return ['code'=>0,"msg"=>"开门成功"];
		}else{
			return ['code'=>1,"msg"=>$res['description']];
		}
	}
	public function keyboardPwdGet($lockId="",$startDate='2022-03-02 00:01',$endDate="2022-03-03 14:00",$name="密码开门",$type=3){
		$url=$this->api_url.'v3/keyboardPwd/get';
		$params['clientId']=$this->client_id;
		$token=self::getToken();
		if($token['code']==1){
			return ['code'=>1,"msg"=>"获取令牌错误"];
		}
		$params['accessToken']=$token['data'];
		$params['lockId']=$lockId;
		$params['keyboardPwdType']=$type;
		$params['keyboardPwdName']=$name;
		$params['startDate']=strtotime($startDate)*1000;
		$params['endDate']=strtotime($endDate)*1000;
		$params['date']=time()*1000;
		$res=self::httpRequest($url,"POST",$params);
		$res=json_decode($res,1);
		if($res['errcode']==0){
			return ['code'=>0,"msg"=>"开门成功",'data'=>$res['data']];
		}else{
			return ['code'=>1,"msg"=>$res['description']];
		}
	}
	/**
	 * CURL请求
	 * @param $url 请求url地址
	 * @param $method 请求方法 get post
	 * @param null $postfields post数据数组
	 * @param array $headers 请求header信息
	 * @param bool|false $debug 调试开启 默认false
	 * @return mixed
	 */
	private function httpRequest($url, $method = "GET", $postfields = null, $headers = array(), $debug = false){
		    $method = strtoupper($method);
		    $ci = curl_init();
		    /* Curl settings */
		    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);//版本
		    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");//在HTTP请求中包含一个"User-Agent: "头的字符串。
		    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
		    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
		    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);//将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
		    switch ($method) {
		        case "POST":
		            curl_setopt($ci, CURLOPT_POST, true);//启用时会发送一个常规的POST请求，类型为：application/x-www-form-urlencoded，就像表单提交的一样。
		            if (!empty($postfields)) {
		                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
		                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
		            }
		            break;
		        default:
		            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
		            break;
		    }
		    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
		    curl_setopt($ci, CURLOPT_URL, $url);//需要获取的URL地址，也可以在curl_init()函数中设置
		    if ($ssl) {
		        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
		        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
		    }
		    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
		    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
		    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
		    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
		    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
		    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
		    $response = curl_exec($ci);
		    $requestinfo = curl_getinfo($ci);
		    curl_close($ci);
		    return $response;
	}
}