<?php

namespace Base\Tool;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class AggregateClient
{
    const SUCCESS = '0000';

    protected $client;

    private $apis = [
        'game-data' => '/index.php?g=api&m=Game&a=rechargeData',
        'game-recharge-detail' => '/index.php?g=api&m=Game&a=rechargeDetail',
        'aggregate-gamename' => '/index.php?g=api&m=Game&a=getAggregatePacket',
        'aggregate-companylist' => '/index.php?g=api&m=Game&a=getAggregateCompanyList',
        'aggregate-companyinfo'=>'/index.php?g=api&m=Game&a=getAggregateCompanyInfo'
    ];

    public function __construct()
    {
        $this->client = new Client([
            'base_uri' => C('AGGREGATE_URL'),
            'timeout'  => 10.0,
        ]);
    }

    public function api($api, array $params = [])
    {
        $uri = $this->apis[$api] ?? null;
        if (is_null($uri)) {
            throw new \Exception('接口不存在');
        }
        $params['api-name'] = $api;
        $sign = Sign::generate($params);
        $params[Sign::SIGN_NAME] = $sign;

        try {
            return $this->post($uri, $params);
        } catch (\Exception $e) {
            return ['code' => '1000', 'message' => '接口请求错误:' . $e->getMessage() , 'data' => []];
        }
    }

    protected function post($uri, array $params = [])
    {
        $response = $this->client->post($uri, [
            'verify' => false,
            'form_params' => $params,
        ]);
        $result = (string)$response->getBody();
        return json_decode($result, true);
    }
}