<?php
namespace Common\Vendor;
class ylyApi
{
    private $client_id;//应用ID;
    private $client_secret;//平台密钥 非空值;
    private $request_url = 'https://open-api.10ss.net';
    public function __construct($client_id = '', $client_secret = ''){
        if(empty($client_id))$client_id=C('PRINT_APPID');
        if(empty($client_secret))$client_secret=C('PRINT_SECRET');
        $this->client_id=$client_id;
        $this->client_secret=$client_secret;
    }
    //获取token
    public function getToken(){
        $cachecontent=$this->filecache('print_ylyApi.php');
        if($cachecontent){
            if($cachecontent['expires_time']>NOW_TIME)return $cachecontent['access_token'];
        }        
        $param=array(
            'action'=>'getylytoken',
            'signtype'=>'sha1',
            'appid'=>C('appid'),//站点ID
            'timestamp'=>NOW_TIME,//时间戳
            'client_id'=>$this->client_id
        );
        ksort($param);$key=C('SAAS_APPSECRET');
        $param['sign']= sha1(format_array2http($param).$key);
        $url='http://www.hanchao9999.com/index.php?s=/home/saas/index';
        $result=curlget($url,$param,'POST');$result=json_decode($result,1);
        if($result['status']==1 && !empty($result['info'])){
            $resultbody['access_token']=$result['info'];
            $resultbody['expires_time']=NOW_TIME+86400;
            $this->filecache('print_ylyApi.php',$resultbody);
            return $resultbody['access_token'];
        }else{
            if(empty($result['info']))$result['info']='获取token失败';
             $return= array('status'=>0,'info'=>$result['info']);return $return;
        }
    }
    /**
     * 添加终端授权
     * @param $machine_code 易联云打印机终端号
     */
    public function addPrint($machine_code){
        $return= array('status'=>0,'info'=>'');
        if(empty($machine_code)){$return['info']='打印机终端号错误';return $return;}
        $token=$this->getToken();
        if(empty($machine_code)){$return['info']='获取token失败';return $return;}
        $data = array(
            'machine_code'=>$machine_code,
            'access_token'=>$token,
            'issign' => true,
            'uuid' => true,
            'timestamp'=>NOW_TIME,
        );
        $msg = $this->ServiceInlet($data,'addPrint');
        $result=json_decode($msg,1);
        if($result['error']==0 && $result['error_description']=='success'){
            $return['status']=1;$return['info']='操作成功';
        }else{
            $return['info']='添加终端授权失败!error:'.$result['error'].' description:'.$result['error_description'];
        }return $return;
    }
    /**
     * 删除终端授权
     * @param $machine_code 易联云打印机终端号
     */
    public function delPrint($machine_code){
        $return= array('status'=>0,'info'=>'');
        if(empty($machine_code)){$return['info']='打印机终端号错误';return $return;}
        $token=$this->getToken();
        if(empty($token)){$return['info']='获取token失败';return $return;}
        $data = array(
            'machine_code'=>$machine_code,
            'access_token'=>$token,
            'issign' => true,
            'uuid' => true,
            'timestamp'=>NOW_TIME,
        );
        $msg = $this->ServiceInlet($data,'delPrint');
        $result=json_decode($msg,1);
        if($result['error']==0 && $result['error_description']=='success'){
            $return['status']=1;$return['info']='操作成功';
        }else{
            $return['info']='删除终端授权失败!error:'.$result['error'].' description:'.$result['error_description'];
        }return $return;
    }
    /**
     * 执行打印
     * @param $machine_code 易联云打印机终端号
     * @param $content 打印内容(需要urlencode)
     * @param $order_sn 商户订单号要求32个字符内
     */
    public function doPrint($machine_code,$content,$order_sn=''){
        $return= array('status'=>0,'info'=>'');
        if(empty($machine_code)){$return['info']='打印机终端号错误';return $return;}
        if(empty($content)){$return['info']='打印内容错误';return $return;}
        $token=$this->getToken();
        if(is_array($token))return $token;
        if(empty($token)){$return['info']='获取token失败';return $return;}
        if(empty($order_sn))$order_sn=base_order();
        $data = array(
            'access_token'=>$token,
            'machine_code'=>$machine_code,
            'content'     =>$content,
            'origin_id'   =>$order_sn,
            'issign'      => true,
            'uuid'        => true,
            'timestamp'   =>NOW_TIME,
        );
        //file_put_contents('uploads/yly'.NOW_TIME.'txt',var_export($data,1));
        $msg = $this->ServiceInlet($data,'Print');
        $result=json_decode($msg,1);
        if($result['error']==0 && $result['error_description']=='success'){
            $return['status']=1;$return['info']='打印成功';
        }else{
            $return['info']='打印失败!error:'.$result['error'].' description:'.$result['error_description'];
        }return $return;
    }
    /**
     * @param $data
     * @param $type
     * @return string
     */
    public function ServiceInlet($data,$type)
    {
        $data['client_id'] = $this->client_id;
        if(isset($data['issign']) === true){
            $data['sign'] = $this->getSign($data);
        }
        if(isset($data['uuid']) === true){
            unset($data['uuid']);
            $data['id'] = $this->Uuid4();
        }
        $data = http_build_query($data);
        $msg = '';
        switch($type){
            case 'Token':
                $url = $this->request_url.'/oauth/oauth';
                $msg = $this->push($data,$url);
                break;
            case 'addPrint':
                $url = $this->request_url.'/printer/addprinter';
                $msg = $this->push($data,$url);
                break;
            case 'delPrint':
                $url = $this->request_url.'/printer/deleteprinter';
                $msg = $this->push($data,$url);
                break;
            case 'addMenu':
                $url = $this->request_url.'/printmenu/addprintmenu';
                $msg = $this->push($data,$url);
                break;
            case 'Print':
                $url = $this->request_url.'/print/index';
                $msg = $this->push($data,$url);
                break;
            case 'shutdownRestart':
                $url = $this->request_url.'/printer/shutdownRestart';
                $msg = $this->push($data,$url);
                break;
            case 'setSound':
                $url = $this->request_url.'/printer/setsound';
                $msg = $this->push($data,$url);
                break;
            case 'printInfo':
                $url = $this->request_url.'/printer/printinfo';
                $msg = $this->push($data,$url);
                break;
            case 'cancelall':
                $url = $this->request_url.'/printer/cancelall';
                $msg = $this->push($data,$url);
                break;
            case 'getversion':
                $url = $this->request_url.'/printer/getversion';
                $msg = $this->push($data,$url);
                break;
            case 'cancelone':
                $url = $this->request_url.'/printer/cancelone';
                $msg = $this->push($data,$url);
                break;
            case 'setlogo':
                $url = $this->request_url.'/printer/seticon';
                $msg = $this->push($data,$url);
                break;
            case 'dellogo':
                $url = $this->request_url.'/printer/deleteicon';
                $msg = $this->push($data,$url);
                break;
            case 'getorder':
                $url = $this->request_url.'/printer/getorder';
                $msg = $this->push($data,$url);
                break;
            case 'scancodemodel':
                $url = $this->request_url.'/oauth/scancodemodel';
                $msg = $this->push($data,$url);
                break;
            case 'btnprint':
                $url = $this->request_url.'/btn/btnprint';
                $msg = $this->push($data,$url);
                break;
            default:
                $msg = '无效参数type';
        }
        return $msg;
    }    
   public function filecache($name,$value=''){
        if(empty($name))return false;
        $name=ROOT_PATH.'/Public/data/'.$name;
        if($value){
            $con = "<?php return;//".json_encode($value)."?>";
            oaofile($name, $con);
        }else{
            $content=oaofile($name);
            $content=strtr($content,array('<?php return;//'=>'','?>'=>''));
            return json_decode($content,1);
        }
   }
    /**
     * @param $data
     * @return string
     */
    private function getSign($data){
        $param = $data;
        unset($param['issign']);
        $sign = $param['client_id'].$param['timestamp'].$this->client_secret;
        return md5($sign);
    }
    /**
     * 获取唯一的uuid
     * @return string
     */
    private function Uuid4(){
        mt_srand((double)microtime() * 10000);
        $charid = strtolower(md5(uniqid(rand(), true)));
        $hyphen = '-';
        $uuidv4 =
            substr($charid, 0, 8) . $hyphen .
            substr($charid, 8, 4) . $hyphen .
            substr($charid, 12, 4) . $hyphen .
            substr($charid, 16, 4) . $hyphen .
            substr($charid, 20, 12);
        return $uuidv4;
    }
    /**
     * @param $data
     * @param $url
     * @return mixed
     */
    private function push($data,$url) {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检测
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Expect:'
        )); // 解决数据包大不能提交
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包\
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl); // 关键CURL会话
        return $tmpInfo; // 返回数据
    }
}