<?php

namespace App\Utils;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use RuntimeException;

class HttpRequestTool
{
    /** @var Client */
    private $client;

    public function __construct($baseUri = '', $timeOut = 60)
    {
        $config       = ['base_uri' => $baseUri, 'timeout' => $timeOut];
        $this->client = new Client($config);
    }

    /**
     * 通过发送json数据的方式进行请求
     *
     * @param $method   string   GET/POST/PUT...
     * @param $uri      string   可以是完整的请求地址。也可以是基于base_uri参数后的补充链接
     * @param $data     array    请求的数据内容
     * @return array
     */
    public function requestByJson($method, $uri, $data)
    {
        try {
            $response = $this->client->request($method, $uri, ['json' => $data]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (GuzzleException $e) {
            $msg = __FUNCTION__ . '请求异常:';
            Log::info($msg . $e->getMessage());
            throw new RuntimeException($e->getMessage());
        }
    }

    /**
     * 通过表单的方式进行请求
     *
     * @param $method
     * @param $uri
     * @param $data
     * @return array|mixed|\stdClass
     */
    public function requestByFormParams($method, $uri, $data)
    {
        try {
            $response = $this->client->request($method, $uri, ['form_params' => $data]);

            return json_decode($response->getBody()->getContents(), true);
        } catch (GuzzleException $e) {
            $msg = __FUNCTION__ . '请求异常:';
            Log::info($msg . $e->getMessage());
            throw new RuntimeException($e->getMessage());
        }
    }

    /**
     * GET方式进行请求
     *
     * @param       $uri
     * @param array $headers
     * @return array
     */
    public function requestGet($uri, $headers = [])
    {
        try {
            if ($headers) {
                $response = $this->client->request('GET', $uri, ['headers' => $headers]);
            } else {
                $response = $this->client->request('GET', $uri);
            }

            return json_decode($response->getBody()->getContents(), true);
        } catch (GuzzleException $e) {
            $msg = __FUNCTION__ . '请求异常:';
            Log::info($msg . $e->getMessage());
            throw new RuntimeException($e->getMessage());
        }
    }
}