<?php

declare(strict_types=1);

namespace App\Master\Framework\Library\Easywechat;

use App\Master\Framework\Library\Extend\Module;
use EasyWeChat\OfficialAccount\Application;

/**
 * 微信小程序开发组
 * class MiniAppService
 */
class OfficialService extends EasyModule
{
    /**
     * @var Application
     */
    private Application $app;
    private array       $config;

    /**
     * 实例化
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     */
    public function __construct()
    {
        parent::__construct();
        // 微信开发配置
        $_table = "EasywechatConfig";
        $config = Cache::remember("OFFICIAL_SERVICE_{$_table}", $this->ttl, function () use ($_table) {
            $module = Module::_SetupModule($_table);
            return $module['official'] ?? [];
        });

        $config = [
            'app_id'  => $config['app_id'] ?? '',
            'secret'  => $config['app_secret'] ?? '',
            'token'   => $config['token'] ?? '',
            'aes_key' => $config['aes_key'] ?? '',
            /**
             * 接口请求相关配置,超时时间等,具体可用参数请参考:
             * https://github.com/symfony/symfony/blob/5.3/src/Symfony/Contracts/HttpClient/HttpClientInterface.php
             */
            'http'    => [
                'throw'   => true, // 状态码非 200、300 时是否抛出异常,默认为开启
                'timeout' => 5.0,
                'retry'   => true, // 使用默认重试配置
            ],
        ];

        $this->config = $config;
        $this->app    = new Application($config);
    }
}