<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/7/26 11:04
 * @Description：
 *
 */

namespace Application\Service;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\ToolSys\Config\ApiConfig;
use Laminas\Http\Client;
use Interop\Container\ContainerInterface;

class HttpSv extends BaseService
{
    protected Client $httpClient;
    private string $statusField = 'code';
    private string $statusMsgField = 'msg';
    private string $signName = '';
    public function __construct(ContainerInterface $container, array $options = [])
    {
        parent::__construct($container);
        $this->httpClient = new Client($options);
        $this->setTimeout(30);
    }

    public function setTimeout ($timeout) {
        $this->httpClient->setOptions([
            'timeout' => $timeout
        ]);
        return $this;
    }

    public function setCookies(array $cookies) {
        $this->httpClient->setCookies($cookies);
        return $this;
    }

    public function setSignName(string $signName) {
        $this->signName = $signName;
        return $this;
    }

    public function setStatusField(string $codeField, string $msgField) {
        $this->statusField = $codeField;
        $this->statusMsgField = $msgField;
        return $this;
    }

    public function setHeader(array $headers)
    {
        $this->httpClient->setHeaders($headers);
        return $this;
    }

    public function post($url, array $data = []) {
        $this->httpClient->setMethod('post');
        if(!empty($data)) $this->httpClient->setParameterPost($data);
        $this->httpClient->setUri($url);

        return $this->send();
    }

    public function get($url, array $data = []){
        if(!empty($data))  $this->httpClient->setParameterGet($data);
        $this->httpClient->setUri($url);

        return $this->send();
    }

    private function send(){
        $body = json_decode($this->httpClient->send()->getBody(), true);
        if($body[$this->statusField] !== 200) throw new InvalidArgumentException($this->appendSignName($body[$this->statusMsgField]));
        return $body['data'];
    }

    private function appendSignName(string $str) {
        return $this->signName ? "【{$this->signName}】{$str}" : $str;
    }
}