<?php
/**
 * Created by PhpStorm.
 * User: 清闲
 * Date: 2020/6/23
 * Time: 14:06 PM
 */

namespace Util\CloudPrint;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;


class Feie
{
    /**
     * 飞鹅云后台注册账号
     */
    private $user = 'phperstar@163.com';

    /**
     * 飞鹅云后台注册账号后生成的UKEY 【备注：这不是填打印机的KEY】
     */
    private $ukey = '7CW8fsUTR6dULwsS';

    /**
     * 打印机编号，必须要在管理后台里添加打印机或调用API接口添加之后，才能调用API
     */
    private $sn;

    /**
     * 打印机识别码
     */
    private $code;

    /**
     * 请求域名
     */
    private $apiUrl = 'api.feieyun.cn';

    /**
     * 请求地址
     * @var string
     */
    private $path = '/Api/Open/';

    /**
     * Feie constructor.
     * @param string $sn
     * @param string $code
     */
    public function __construct($sn = '', $code = '')
    {
        $this->sn = $sn;
        $this->code = $code;
    }

    /**
     * 添加打印机设备
     * @return ResultWrapper
     */
    public function adddev()
    {
        $time = time();
        $postData = [
            'user' => $this->user,
            'stime' => $time,
            'sig' => sha1($this->user.$this->ukey.$time),
            'apiname' => 'Open_printerAddlist',
            'printerContent' => $this->sn.'#'.$this->code,//打印机编号(必填) # 打印机识别码(必填)
        ];
        $apiUrl = $this->apiUrl.$this->path;
        $reponse = request($apiUrl, $postData);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['ret']) && $reponseData['ret'] != 0){
                return ResultWrapper::fail($reponseData['msg'],$reponseData['ret']);
            }
            return ResultWrapper::success($reponseData['data']);
        }
    }

    /**
     * 发送打印机信息
     * @param $params
     * @return ResultWrapper
     */
    public function sendMsg($params)
    {
        $time = time();
        $postData = [
            'user' => $this->user,
            'stime' => $time,
            'sig' => sha1($this->user.$this->ukey.$time),
            'apiname' => 'Open_printMsg',
        ];
        $postData['sn'] = $this->sn;
        $postData['content'] = $params;
        $apiUrl = $this->apiUrl.$this->path;
        $reponse = request($apiUrl, $postData);
        if($reponse['httpcode'] != 200){
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }else{
            $reponseData = json_decode($reponse['content'], true);
            if( isset($reponseData['ret']) && $reponseData['ret'] != 0){
                return ResultWrapper::fail($reponseData['msg'],$reponseData['ret']);
            }
            return ResultWrapper::success($reponseData['data']);
        }
    }






}