<?php

namespace App\Services\Vendor\Xunfei;

use GuzzleHttp\Client;

/**
 * 发送请求基类
 */
class HttpBase
{
    /**
     * guzzle对象
     */
    private $httpClient;
    // AppID
    private $appId;
    // ApiKey
    private $apiKey;

    public function __construct($baseUri)
    {
        $this->appId = config('services.xunfei.app_id');
        $this->apiKey = config('services.xunfei.secret_key');
        $this->httpClient = new Client(['base_uri' => $baseUri]);
    }


    /**
     * 发送post请求,form表单
     * @param $keyWord
     * @param  array  $extData
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function postForm($keyWord, array $extData)
    {
        $baseData = $this->getBaseData();
        $data = array_merge($baseData, $extData);
        // 发起urlencode请求
        $response = $this->httpClient->request('POST', $keyWord, [
            'form_params' => $data,
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * 获取基本数据信息
     *
     * @return  array
     */
    private function getBaseData()
    {
        $timestamp = time();

        return [
            'app_id' => $this->appId,
            'signa' => $this->makeSign($timestamp),
            'ts' => $timestamp,
        ];
    }

    /**
     * 加密算法
     * @param $timestamp
     * @return string
     */
    private function makeSign($timestamp)
    {
        // 拼写基本数据
        $baseString = $this->appId . $timestamp;
        // 进行md5加密
        $md5String = md5($baseString);
        // 进行HmacSHA1加密
        $signString = base64_encode(hash_hmac("sha1", $md5String, $this->apiKey, true));

        return $signString;
    }

    /**
     * 发送post请求,form表单
     * @param $keyWord
     * @param  array  $extData
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function postMulti($keyWord, array $extData)
    {
        $baseData = $this->getBaseData();
        $data = array_merge($baseData, $extData);
        // 发起urlencode请求
        $response = $this->httpClient->request('POST', $keyWord, [
            'multipart' => $this->changeDataFormat($data),
        ]);

        return json_decode($response->getBody()->getContents(), true);
    }

    /**
     * 改变数据格式
     *
     * @return  array
     */
    private function changeDataFormat($array)
    {
        $return = [];
        foreach ($array as $key => $val) {
            $return[] = [
                'name' => $key,
                'contents' => $val,
            ];
        }

        return $return;
    }
}
