<?php
namespace slock;
/**
* 新世纪智能门锁
* 对接文档：http://doc.door.openapi.horniot.com/#/xsj/
*/
class Xsj{

	private $yard_sn="102860710203499100";
	private $app_key="4ad5c1c84f895e90afb0321ef2adb319";
    private $api_url="http://openapi.door.vip365.top/";
    private $qy_api_url="https://device.youdiy.cn/index.php";
    public  $domain_urls;
    private $domain;
    public function __construct($config=[]){
           $this->yard_sn=isset($config['xsj_yard_sn'])?$config['xsj_yard_sn']:"";
           $this->app_key=isset($config['xsj_app_key'])?$config['xsj_app_key']:"";
           $this->domain=request()->domain();
           $this->domain=str_replace("http://","", $this->domain);
           $this->domain=str_replace("https://","", $this->domain);
           $this->domain_urls=[
                'chashi.youdiy.cn',
                'xingyungongxiang.youdiy.cn',
                'zuishanshui.youdiy.cn',
                
           ];
    }
    //新接口一键开门
    public function deviceRemote($device_guid="2440679646_",$op=1){
        if(in_array($this->domain,$this->domain_urls)){
            return self::qYdeviceRemote($device_guid);
        }
        $api_url=$this->api_url."open/door/remote-cmd";
        $params['park_sn']=$this->yard_sn;
        $params['timestamp']=time();
        $params['door_guid']=$device_guid;
        $params['cmd_type']=$op;//门禁指令(1：远程开门 2：重启 3：重发密钥 4:清空门禁白名单 5:重置门禁时间)
        $params['sign']=self::createSign($params);
        $res=self::httpRequest($api_url,"POST",$params);
        $res=json_decode($res,1);
        if($res['code']==200){
           return ['code'=>0,'data'=>$res['data'],'msg'=>$res['msg']];
        }else{
           return ['code'=>1,'data'=>[],'msg'=>$res['msg']];
        }
    }
    //新接口二维码开门
    public function deviceQr($device_guid="111,222",$start_time="",$end_time="",$phone="15860162181"){
        if(in_array($this->domain,$this->domain_urls)){
            return self::qYdeviceQr($device_guid,$start_time,$end_time);
        }
        $api_url=$this->api_url."open/qr-code";
        $params['park_sn']=$this->yard_sn;
        $params['timestamp']=time();
        $params['device_guid']=$device_guid;
        $params['phone']=$phone;
        $params['times']=0;
        $params['start_time']=date('Y-m-d H:i:s',$start_time);
        $params['end_time']=date('Y-m-d H:i:s',$end_time);
        $params['long']=0;
        $params['sign']=self::createSign($params);
        $res=self::httpRequest($api_url,"POST",$params);
        $res=json_decode($res,1);       
        if($res['code']==200){
         return ['code'=>0,'data'=>$res['data']['qr_str'],'msg'=>$res['msg']];
        }else{
         return ['code'=>1,'data'=>[],'msg'=>$res['msg']];
        }
    }
    //------------------------------------------------------------------------
    //芊雅一键开门
    public function qYdeviceRemote($device_sn=""){
        $qy_api_url=$this->qy_api_url."/api/device/cmdreport";
        $params['device_sn']=$device_sn;
        $params['xsj_appid']=$this->yard_sn;
        $params['xsj_app_secret']=$this->app_key;
        $res=self::httpRequest($qy_api_url,"POST",$params);
        $res=json_decode($res,1);
        if($res['code']==0){
         return ['code'=>0,'data'=>[],'msg'=>$res['msg']];
        }else{
         return ['code'=>1,'data'=>[],'msg'=>$res['msg']];
        }
    }
    //芊雅一键开门
    public function qYdeviceQr($device_sn="",$start_time="",$end_time=""){
        $qy_api_url=$this->qy_api_url."/api/device/qrcode";
        $params['device_sn']=$device_sn;
        $params['xsj_appid']=$this->yard_sn;
        $params['xsj_app_secret']=$this->app_key;
        $params['start_time']=date('Y-m-d H:i:s',$start_time);
        $params['end_time']=date('Y-m-d H:i:s',$end_time);
        $res=self::httpRequest($qy_api_url,"POST",$params);
        $res=json_decode($res,1);
        if($res['code']==0){
         return ['code'=>0,'data'=>$res['data']['qr_str'],'msg'=>$res['msg']];
        }else{
         return ['code'=>1,'data'=>[],'msg'=>$res['msg']];
        }
    }
    //------------------------------------------------------------------------
     /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function createSign1($params=[]) {
	        if (is_null($this->app_key)) {
	            die('缺少参数key 41004');
	        }
	        //签名步骤一：按字典序排序参数
	        ksort($params);
	        $string = http_build_query($params);
	        //签名步骤二：在string后加入KEY
	        $string1 = $string . "&key=".$this->app_key;
	        //签名步骤三：MD5加密
	        $string = md5($string1);
	        
	        //签名步骤四：所有字符转为大写strtoupper
	        $result = ($string);
	        return $result;
    }
    public function createSign(array $param)
    {
        unset($param['sign'], $param['s']);
        ksort($param);
        $str = '';
        foreach ($param as $key => $val) {
            $str .= "{$key}={$val}&";
        }
        $str .= "key=" . $this->app_key;
        return md5($str);
    }
    /**
	 * 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;
	}

}