<?php
namespace FlyingGeese;
class FlyingGeese{
	public $USER;
	public $UKEY;
	public $SN;
	public $IP='api.feieyun.cn';
	public $PORT='80';
	public $PATH='/Api/Open/';
	public $STIME;
	public $SIG;
	public function __construct($USER,$UKEY,$SN){
		header("Content-type: text/html; charset=utf-8");
		$this->USER=$USER;	//*必填*：飞鹅云后台注册账号
		$this->UKEY=$UKEY;	//*必填*: 飞鹅云注册账号后生成的UKEY
		$this->SN=$SN;	    //*必填*：打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API
		$this->STIME=time();
		$this->SIG=sha1($USER.$UKEY.$this->STIME);
	}
	//wp_print(SN,$orderInfo,1);
	public	function addprinter($snlist){
			
				$content = array(			
					'user'=>$this->USER,
					'stime'=>$this->STIME,
					'sig'=>$this->SIG,
					'apiname'=>'Open_printerAddlist',

				    'printerContent'=>$snlist
				);
				
			$client = new HttpClient($this->IP,$this->PORT);
			if(!$client->post($this->PATH,$content)){
				echo 'error';
			}
			else{
				echo $client->getContent();
			}
			
	}		
	/*
	 *  方法1
		拼凑订单内容时可参考如下格式
		根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式
	*/
	public	function wp_print($title,$table,$orderInfo,$rest){
			$orderInfo=$this->test($title,$table,$orderInfo,$rest,14,7,3,6);
			$content = array(			
					'user'=>$this->USER,
					'stime'=>$this->STIME,
					'sig'=>$this->SIG,
					'apiname'=>'Open_printMsg',
					'sn'=>$this->SN,
					'content'=>$orderInfo,
				    'times'=>1//打印次数
				);

				
			$client = new HttpClient($this->IP,$this->PORT);

			if(!$client->post($this->PATH,$content)){
				return 'error';
			}
			else{
				//服务器返回的JSON字符串，建议要当做日志记录起来
				return $client->getContent();
			}
			
	}
	/*
	 *  方法2
		根据订单索引,去查询订单是否打印成功,订单索引由方法1返回
	*/
	public	function queryOrderState($index){
				$msgInfo = array(
					'user'=>$this->USER,
					'stime'=>$this->STIME,
					'sig'=>$this->SIG,	 
					'apiname'=>'Open_queryOrderState',
					
					'orderid'=>$index
				);
			
			$client = new HttpClient($this->IP,$this->PORT);
			if(!$client->post($this->PATH,$msgInfo)){
				echo 'error';
			}
			else{
				$result = $client->getContent();
				echo $result;
			}
			
	}
	/*
	 *  方法3
		查询指定打印机某天的订单详情
	*/
	public	function queryOrderInfoByDate($printer_sn,$date){
				$msgInfo = array(
					'user'=>$this->USER,
					'stime'=>$this->STIME,
					'sig'=>$this->SIG,			
					'apiname'=>'Open_queryOrderInfoByDate',
					
			        'sn'=>$printer_sn,
					'date'=>$date
				);
			
			$client = new HttpClient($this->IP,$this->PORT);
			if(!$client->post($this->PATH,$msgInfo)){ 
				echo 'error';
			}
			else{
				$result = $client->getContent();
				echo $result;
			}
			
		}
	/*
	 *  方法4
		查询打印机的状态
	*/
	public function queryPrinterStatus($printer_sn){
				
			    $msgInfo = array(
			    	'user'=>$this->USER,
					'stime'=>$this->STIME,
					'sig'=>$this->SIG,	
					'apiname'=>'Open_queryPrinterStatus',
					
			        'sn'=>$printer_sn
				);
			
			$client = new HttpClient($this->IP,$this->PORT);
			if(!$client->post($this->PATH,$msgInfo)){
				echo 'error';
			}
			else{
				$result = $client->getContent();
				echo $result;
			}
	}
	public	function test($title,$table,$arr,$rest,$A,$B,$C,$D)
	{
		  $orderInfo = '<CB>'.$title.'</CB><BR>';
		  $orderInfo .= $table;                              //名称14 单价7 数量3 金额6-->这里的字节数可按自己需求自由改写
		  $orderInfo .= '--------------------------------<BR>';
		  foreach ($arr as $k5 => $v5) {
		    $name = $v5['title'];
		    $price = $v5['price'];
		    $num = $v5['num'];
		    $prices = $v5['prices'];
		    $kw3 = '';
		    $kw1 = '';
		    $kw2 = '';
		    $kw4 = '';
		    $str = $name;
		    $blankNum = $A;//名称控制为14个字节
		    $lan = mb_strlen($str,'utf-8');
		    $m = 0;
		    $j=1;
		    $blankNum++;
		    $result = array();
		    for ($i=0;$i<$lan;$i++){
		      $new = mb_substr($str,$m,$j,'utf-8');
		      $j++;
		      if(mb_strwidth($new,'utf-8')<$blankNum) {
		        if($m+$j>$lan) {
		          $m = $m+$j;
		          $tail = $new;
		          $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
		          $k = $A - strlen($lenght);
		          for($q=0;$q<$k;$q++){
		            $kw3 .= ' ';
		          }
		          $tail .= $kw3;
		          break;
		        }else{
		          $next_new = mb_substr($str,$m,$j,'utf-8');
		          if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
		          else{
		            $m = $i+1;
		            $result[] = $new.'<BR>';
		            $j=1;
		          }
		        }
		      }
		    }
		    $head = '';
		    foreach ($result as $value) {
		      $head .= $value;
		    }
		    if(strlen($price) < $B){
		          $k1 = $B - strlen($price);
		          for($q=0;$q<$k1;$q++){
		                $kw1 .= ' ';
		          }
		          $price = $price.$kw1;
		    }
		    if(strlen($num) < $C){
		          $k2 = $C - strlen($num);
		          for($q=0;$q<$k2;$q++){
		                $kw2 .= ' ';
		          }
		          $num = $num.$kw2;
		    }
		    if(strlen($prices) < $D){
		          $k3 = $D - strlen($prices);
		          for($q=0;$q<$k3;$q++){
		                $kw4 .= ' ';
		          }
		          $prices = $prices.$kw4;
		    }
		    $orderInfo .= $head.$tail.' '.$price.' '.$num.' '.$prices.'<BR>';
		    @$nums += $prices;
		  }
		  $time = date('Y-m-d H:i:s',time());
		  $orderInfo .= '--------------------------------<BR>';
		  // $orderInfo .= '合计：'.$nums.'元<BR>';
		  $orderInfo.=$rest;
		  return $orderInfo;
	}
}
class HttpClient {
    var $host;
    var $port;
    var $path;
    var $method;
    var $postdata = '';
    var $cookies = array();
    var $referer;
    var $accept = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,image/jpeg,image/gif,*/*';
    var $accept_encoding = 'gzip';
    var $accept_language = 'en-us';
    var $user_agent = 'Incutio HttpClient v0.9';
    var $timeout = 20;
    var $use_gzip = true;
    var $persist_cookies = true; 
    var $persist_referers = true; 
    var $debug = false;
    var $handle_redirects = true; 
    var $max_redirects = 5;
    var $headers_only = false;    
    var $username;
    var $password;
    var $status;
    var $headers = array();
    var $content = '';
    var $errormsg;
    var $redirect_count = 0;
    var $cookie_host = '';
    function __construct($host, $port=80) {
        $this->host = $host;
        $this->port = $port;
    }
    function get($path, $data = false) {
        $this->path = $path;
        $this->method = 'GET';
        if ($data) {
            $this->path .= '?'.$this->buildQueryString($data);
        }
        return $this->doRequest();
    }
    function post($path, $data) {
        $this->path = $path;
        $this->method = 'POST';
        $this->postdata = $this->buildQueryString($data);
    	return $this->doRequest();
    }
    function buildQueryString($data) {
        $querystring = '';
        if (is_array($data)) {
    		foreach ($data as $key => $val) {
    			if (is_array($val)) {
    				foreach ($val as $val2) {
    					$querystring .= urlencode($key).'='.urlencode($val2).'&';
    				}
    			} else {
    				$querystring .= urlencode($key).'='.urlencode($val).'&';
    			}
    		}
    		$querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
    	} else {
    	    $querystring = $data;
    	}
    	return $querystring;
    }
    function doRequest() {
		if (!$fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout)) {
            switch($errno) {
				case -3:
					$this->errormsg = 'Socket creation failed (-3)';
				case -4:
					$this->errormsg = 'DNS lookup failure (-4)';
				case -5:
					$this->errormsg = 'Connection refused or timed out (-5)';
				default:
					$this->errormsg = 'Connection failed ('.$errno.')';
			    $this->errormsg .= ' '.$errstr;
			    $this->debug($this->errormsg);
			}
			return false;
        }

        socket_set_timeout($fp, $this->timeout);
        $request = $this->buildRequest();
        $this->debug('Request', $request);
        fwrite($fp, $request);
    	$this->headers = array();
    	$this->content = '';
    	$this->errormsg = '';
    	$inHeaders = true;
    	$atStart = true;

    	while (!feof($fp)) {
    	    $line = fgets($fp, 4096);
    	    if ($atStart) {
    	        $atStart = false;
    	        if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/', $line, $m)) {
    	            $this->errormsg = "Status code line invalid: ".htmlentities($line);
    	            $this->debug($this->errormsg);
    	            return false;
    	        }
    	        $http_version = $m[1]; 
    	        $this->status = $m[2];
    	        $status_string = $m[3];
    	        $this->debug(trim($line));
    	        continue;
    	    }
    	    if ($inHeaders) {
    	        if (trim($line) == '') {
    	            $inHeaders = false;
    	            $this->debug('Received Headers', $this->headers);
    	            if ($this->headers_only) {
    	                break;
    	            }
    	            continue;
    	        }
    	        if (!preg_match('/([^:]+):\\s*(.*)/', $line, $m)) {
    	            continue;
    	        }
    	        $key = strtolower(trim($m[1]));
    	        $val = trim($m[2]);
    	        if (isset($this->headers[$key])) {
    	            if (is_array($this->headers[$key])) {
    	                $this->headers[$key][] = $val;
    	            } else {
    	                $this->headers[$key] = array($this->headers[$key], $val);
    	            }
    	        } else {
    	            $this->headers[$key] = $val;
    	        }
    	        continue;
    	    }
    	    $this->content .= $line;
        }
        fclose($fp);

        if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] == 'gzip') {
            $this->debug('Content is gzip encoded, unzipping it');
            $this->content = substr($this->content, 10);
            $this->content = gzinflate($this->content);
        }
        if ($this->persist_cookies && isset($this->headers['set-cookie']) && $this->host == $this->cookie_host) {
            $cookies = $this->headers['set-cookie'];
            if (!is_array($cookies)) {
                $cookies = array($cookies);
            }
            foreach ($cookies as $cookie) {
                if (preg_match('/([^=]+)=([^;]+);/', $cookie, $m)) {
                    $this->cookies[$m[1]] = $m[2];
                }
            }
            $this->cookie_host = $this->host;
        }
        if ($this->persist_referers) {
            $this->debug('Persisting referer: '.$this->getRequestURL());
            $this->referer = $this->getRequestURL();
        }

        if ($this->handle_redirects) {
            if (++$this->redirect_count >= $this->max_redirects) {
                $this->errormsg = 'Number of redirects exceeded maximum ('.$this->max_redirects.')';
                $this->debug($this->errormsg);
                $this->redirect_count = 0;
                return false;
            }
            $location = isset($this->headers['location']) ? $this->headers['location'] : '';
            $uri = isset($this->headers['uri']) ? $this->headers['uri'] : '';
            if ($location || $uri) {
                $url = parse_url($location.$uri);
                return $this->get($url['path']);
            }
        }

        return true;
    }
    function buildRequest() {
        $headers = array();
        $headers[] = "{$this->method} {$this->path} HTTP/1.0"; 
        $headers[] = "Host: {$this->host}";
        $headers[] = "User-Agent: {$this->user_agent}";
        $headers[] = "Accept: {$this->accept}";
        if ($this->use_gzip) {
            $headers[] = "Accept-encoding: {$this->accept_encoding}";
        }
        $headers[] = "Accept-language: {$this->accept_language}";
        if ($this->referer) {
            $headers[] = "Referer: {$this->referer}";
        }
    	if ($this->cookies) {
    	    $cookie = 'Cookie: ';
    	    foreach ($this->cookies as $key => $value) {
    	        $cookie .= "$key=$value; ";
    	    }
    	    $headers[] = $cookie;
    	}
    	if ($this->username && $this->password) {
    	    $headers[] = 'Authorization: BASIC '.base64_encode($this->username.':'.$this->password);
    	}
    	if ($this->postdata) {
    	    $headers[] = 'Content-Type: application/x-www-form-urlencoded';
    	    $headers[] = 'Content-Length: '.strlen($this->postdata);
    	}
    	$request = implode("\r\n", $headers)."\r\n\r\n".$this->postdata;
    	return $request;
    }
    function getStatus() {
        return $this->status;
    }
    function getContent() {

        return $this->content;
    }
    function getHeaders() {
        return $this->headers;
    }
    function getHeader($header) {
        $header = strtolower($header);
        if (isset($this->headers[$header])) {
            return $this->headers[$header];
        } else {
            return false;
        }
    }
    function getError() {
        return $this->errormsg;
    }
    function getCookies() {
        return $this->cookies;
    }
    function getRequestURL() {
        $url = 'http://'.$this->host;
        if ($this->port != 80) {
            $url .= ':'.$this->port;
        }            
        $url .= $this->path;
        return $url;
    }
    function setUserAgent($string) {
        $this->user_agent = $string;
    }
    function setAuthorization($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }
    function setCookies($array) {
        $this->cookies = $array;
    }
    function useGzip($boolean) {
        $this->use_gzip = $boolean;
    }
    function setPersistCookies($boolean) {
        $this->persist_cookies = $boolean;
    }
    function setPersistReferers($boolean) {
        $this->persist_referers = $boolean;
    }
    function setHandleRedirects($boolean) {
        $this->handle_redirects = $boolean;
    }
    function setMaxRedirects($num) {
        $this->max_redirects = $num;
    }
    function setHeadersOnly($boolean) {
        $this->headers_only = $boolean;
    }
    function setDebug($boolean) {
        $this->debug = $boolean;
    }
    function quickGet($url) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        if (isset($bits['query'])) {
            $path .= '?'.$bits['query'];
        }
        $client = new HttpClient($host, $port);
        if (!$client->get($path)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    function quickPost($url, $data) {
        $bits = parse_url($url);
        $host = $bits['host'];
        $port = isset($bits['port']) ? $bits['port'] : 80;
        $path = isset($bits['path']) ? $bits['path'] : '/';
        $client = new HttpClient($host, $port);
        if (!$client->post($path, $data)) {
            return false;
        } else {
            return $client->getContent();
        }
    }
    function debug($msg, $object = false) {
        if ($this->debug) {
            print '<div style="border: 1px solid red; padding: 0.5em; margin: 0.5em;"><strong>HttpClient Debug:</strong> '.$msg;
            if ($object) {
                ob_start();
        	    print_r($object);
        	    $content = htmlentities(ob_get_contents());
        	    ob_end_clean();
        	    print '<pre>'.$content.'</pre>';
        	}
        	print '</div>';
        }
    }   
}