<?php

namespace Application\Service\Extension\Wechat;


use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\Laminas;
use EasyWeChat\Factory;
use EasyWeChat\OfficialAccount\Application;

/**
 * 组件文档地址: https://easywechat.com/5.x/official-account/index.html
 */
class Wechat
{
    public static ?Application $easyWechatApp = null;

    public static ?\EasyWeChat\MiniProgram\Application $miniApp = null;

    public static ?\EasyWeChat\Work\Application $workApp = null;

    public static ?Application $patientH5App = null;

    /**
     * 获取组件实例
     * @return Application
     */
    public function getApp(): Application
    {
        if (!self::$easyWechatApp instanceof Application) {
            self::$easyWechatApp = Factory::officialAccount(Laminas::$app->getConfig()['wechat']);
            self::$easyWechatApp->rebind('cache', new WechatCache());
        }

        return self::$easyWechatApp;
    }

    /**
     * 获取组件实例
     * @param string $platform
     * @return \EasyWeChat\MiniProgram\Application
     */
    public function getMiniApp(string $platform = 'scitrials'): \EasyWeChat\MiniProgram\Application
    {
        $platform = strtolower($platform);
        if (!self::$miniApp instanceof \EasyWeChat\MiniProgram\Application) {
            $config = Laminas::$app->getConfig()['applets'][$platform] ?? [];
            if (!$config) {
                throw new InvalidArgumentException('平台参数不对。');
            }
            self::$miniApp = Factory::miniProgram($config);
            self::$miniApp->rebind('cache', new WechatCache());
        }

        return self::$miniApp;
    }

    /**
     * Notes: 获取企业微信组件实例
     * User: llbjj
     * DateTime: 2022/9/5 14:19
     *
     * @return \EasyWeChat\Work\Application
     */
    public function getWorkApp(): \EasyWeChat\Work\Application
    {
        if (!self::$workApp instanceof \EasyWeChat\Work\Application) {
            self::$workApp = Factory::work(Laminas::$app->getConfig()['work']['app']);
            self::$workApp->rebind('cache', new WechatCache());
        }
        return self::$workApp;
    }

    /**
     * Notes: 获取受试者公众号微信组件实例
     * User: llbjj
     * DateTime: 2024/7/24 9:36
     *
     * @param string $appType
     * @return Application
     */
    public function getPatientH5App(string $appType = 'default'): Application
    {
        if (!self::$patientH5App instanceof Application) {
            self::$patientH5App = Factory::officialAccount(Laminas::$app->getConfig()['patient_H5'][$appType]);
            self::$patientH5App->rebind('cache', new WechatCache(2));
        }
        return self::$patientH5App;
    }

}