<?php
/**
 * 内部API助手类
 * Created by PhpStorm.
 * User: Ming
 * Date: 2018/3/13
 * Time: 10:21
 */

namespace common\helpers\http;
use Yii;
use yii\httpclient\Client;
class ShopApi {
    /**
     * 通讯密钥
     */
    const AUTH_KEY = '';
    /**
     * 允许的时间差(秒)
     */
    const TIME_DIFF = '';
    /**
     * 请求方法
     */
    const HTTP_METHOD_POST = 'post';
    const HTTP_METHOD_GET = 'get';
    /**
     * 返回成功的标记
     */
    const RETURN_SUCCESS = 'success';
    /**
     * http client
     * @var null
     */
    private static $_client = null;
    /**
     * http response
     * @var null
     */
    protected static $response = null;
    /**
     * 错误代码
     * @var int
     */
    private static $_errorCode = 0;
    /**
     * 错误信息
     * @var null
     */
    private static $_errorMessage = null;
    /**
     * 获取密钥
     * @return string
     */
    public static function getAuthKey(){
        if(self::AUTH_KEY === ''){
            return Yii::$app->params['http']['shopApi']['authKey'];
        }

        return self::AUTH_KEY;
    }

    /**
     * 获取允许的时间差
     * @return string
     */
    public static function getTimeDiff(){
        if(self::TIME_DIFF === ''){
            return Yii::$app->params['http']['shopApi']['timeDiff'];
        }
        return self::TIME_DIFF;
    }
    /**
     * 生成签名
     * @param array $params
     * @return array
     */
    public static function paramsFormat(array $params){
        if(!isset($params['timestamp'])){
            $params['timestamp'] = time();
        }
        if(isset($params['signature'])){
            unset($params['signature']);
        }
        ksort($params);
        $string = '';
        foreach($params as $key=>$value){
            $string .= $key.'='.$value . '&';
        }
        $params['signature'] = sha1(trim($string,'&') . self::getAuthKey());
        return $params;
    }

    /**
     * 验证签名
     * @param $signature
     * @param array $params
     * @return bool
     */
    public static function checkSignature($signature, array $params){
        $params = self::paramsFormat($params);
        if($params['signature'] !== $signature){
            return false;
        }
        $timeDiff = (int)self::getTimeDiff();
        if($timeDiff > 0 && (time() -> $params['timestamp']) > $timeDiff){
            return false;
        }
        return true;
    }

    /**
     * 获取http client 对象
     * @return null|Client
     */
    public static function client(){
        if(is_null(self::$_client)){
            self::$_client = new Client();
        }
        return self::$_client;
    }

    /**
     * request
     * @return \yii\httpclient\Request
     */
    public static function request(){
        return self::client()->createRequest();
    }

    /**
     * POST请求
     * @param $url
     * @param $data
     * @return mixed
     */
    public static function post($url, $data){
        $data = self::paramsFormat($data);
        static::$response = self::request()
            ->setMethod(self::HTTP_METHOD_POST)
            ->setUrl($url)
            ->setData($data)
            ->send();
        unset($data);
        return static::$response;
    }

    /**
     * GET请求
     * @param $url
     * @param array $data
     * @return \yii\httpclient\Response
     */
    public static function get($url, $data = []){
        $data = self::paramsFormat($data);
        $query = self::request()
            ->setMethod(self::HTTP_METHOD_GET)
            ->setUrl($url);
        if($data){
            $query->setData($data);
        }
        static::$response = $query->send();
        unset($data, $query);
        return static::$response;
    }
    /**
     * 输出是否正确
     * @return mixed
     */
    public static function responsed(){
        return self::$response->isOk && (is_array(self::$response->data) && isset(self::$response->data[self::RETURN_SUCCESS]));
    }

    /**
     * 获取报文
     * @return null
     */
    public static function getResponse(){
        return self::$response;
    }
    /**
     * 获取报文数据
     * @return mixed
     */
    public static function result(){
        return self::$response->data;
    }

    /**
     * 设置错误
     * @param $message
     * @param null $code
     */
    public static function setError($message, $code = null){
        if(!is_null($code)){
            self::$_errorCode = $code;
        }
        self::$_errorMessage = $message;
    }

    /**
     * 获取错误
     * @return array
     */
    public static function getError(){
        return [self::$_errorMessage, self::$_errorCode];
    }
}