<?php

namespace Extend\TencentIm;

use App\Constants\HttpEnumCode;
use App\Exception\BusinessException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\HandlerStackFactory;
use Psr\Container\ContainerInterface;


class Base
{
    protected array $config;// 系统配置
    protected string $identifier = "administrator";// 管理员账户

    public function __construct()
    {
        $this->config = config("im");

        if (empty($this->config)) {
            throw new BusinessException("系统配置错误", HttpEnumCode::SERVER_ERROR);
        }
    }

    /**
     * 获取用户签名
     * @param string $user_id
     * @return string
     */
    protected function getUserSign(string $user_id = ""): string
    {
        try {
            $TLSSigAPIv2 = new TLSSigAPIv2($this->config['app_id'], $this->config['secret']);

            if (empty($user_id)){
                $user_sign = $TLSSigAPIv2->genUserSig($this->identifier);
            }else{
                $user_sign = $TLSSigAPIv2->genUserSig($user_id);
            }

            if (empty($user_sign)) {
                throw new BusinessException("获取im用户签名失败");
            }

            return $user_sign;
        } catch (\Exception $e) {
            throw new BusinessException($e->getMessage());
        }
    }

    /**
     * 组合请求参数
     * @return string
     */
    protected function buildRequestParams(): string
    {
        $result = array();
        $result['sdkappid'] = $this->config['app_id'];
        $result['identifier'] = $this->identifier;
        $result['usersig'] = $this->getUserSign();
        $result['random'] = mt_rand(0, 4294967295);
        $result['contenttype'] = "json";

        return http_build_query($result);
    }

    /**
     * 封装请求
     * @param string $path
     * @param array $option
     * @return array
     * @throws GuzzleException
     */
    protected function postRequest(string $path, array $option = []): array
    {
        $factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = make(Client::class, [
            'config' => [
                'handler' => $stack,
                'timeout'  => 10,
                'verify'  => false,
            ],
        ]);
        $response = $client->post($path, $option);

        if ($response->getStatusCode() != '200'){
            // 请求失败
            throw new BusinessException($response->getBody()->getContents());
        }

        $content = json_decode($response->getBody(),true);

        if (empty($content)){
            throw new BusinessException("请求失败");
        }

        if ($content['ErrorCode'] != 0){
            throw new BusinessException($content['ErrorInfo']);
        }
        return $content;
    }
}