<?php

namespace Extend\VerifyDun;

use App\Utils\HttpRequest;
use GuzzleHttp\Client;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;

/**
 * 基础类
 */
class Base
{
    #[Inject]
    protected ContainerInterface $container;

    protected mixed $httpRuest;
    protected array $config;// 系统配置

    protected string $api_url = "https://verify.dun.163.com/";

    public string $version = "v1";

    protected array $options;

    protected array $params;// 请求参数

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

        $this->options['headers'] = [
            "Content-Type" => "application/x-www-form-urlencoded; charset=UTF-8"
        ];

        $this->params['secretId'] = $this->config['secretId'];
        $this->params['version'] = $this->version;
        $this->params['timestamp'] = time() * 1000;
        $this->params['nonce'] = sprintf("%d", rand());
        $this->params = $this->toUtf8($this->params);



        $container = ApplicationContext::getContainer();
        $this->httpRuest = $container->get(HttpRequest::class);
    }

    /**
     * 计算签名
     * @return string
     */
    protected function gen_signature(): string
    {
        ksort($this->params);
        $buff="";
        foreach($this->params as $key=>$value){
            if($value !== null) {
                $buff .=$key;
                $buff .=$value;
            }
        }
        $buff .= $this->config['secretKey'];
        return md5($buff);
    }

    /**
     * 将输入数据的编码统一转换成utf8
     * @param array $params 输入的参数
     * @return array
     */
    function toUtf8(array $params): array
    {
        $utf8s = array();
        foreach ($params as $key => $value) {
            $utf8s[$key] = is_string($value) ? mb_convert_encoding($value, "utf8", 'auto') : $value;
        }
        return $utf8s;
    }
}