<?php


namespace App\Service;


use GuzzleHttp\Client;

class ExternalApiService
{
    public string $domain;


    public function __construct(string $domain = '')
    {
        $this->setDomain($domain);
    }

    /**
     * 执行生成图片命令
     *
     * @param array $data
     * @return array|mixed
     */
    public function imagine(array $data = [])
    {
        $url = $this->getPath('/api/imagine');
        return $this->httpPost($url, $data);
    }

    /**
     * @param string $path
     * @return string
     */
    public function getPath(string $path = '')
    {
        return $this->getDomain() . $path;
    }

    /**
     *
     * @return string
     */
    public function getDomain()
    {
        return $this->domain;
    }

    /**
     * @param string $domain
     */
    public function setDomain(string $domain = '')
    {
        $this->domain = $domain;
        if (blank($domain)) {
            $this->domain = config('common.python_api');
        }
    }

    /**
     * 发送post请求
     *
     * @param string $url
     * @param array $data
     * @return array|mixed
     */
    public function httpPost(string $url = '', array $data = [])
    {
        $requestData = [
            'headers' => [
                'Content-Type' => 'application/json'
            ],
            'json' => [
                'data' => $data
            ],
        ];
        $client = new Client();
        try {
            $response = $client->post($url, $requestData);
            $data = json_decode($response->getBody()->getContents(), true);
            return $data ?? [];
        } catch (\Throwable $throwable) {
            return [];
        }
    }

    /**
     * 下载图片
     *
     * @param array $data
     * @return array|mixed
     */
    public function downloadImage(array $data = [])
    {
        $url = $this->getPath('/api/download-image');
        return $this->httpPost($url, $data);
    }
}
