<?php

namespace xmvc;

/**
 * Message 消息类
 */

class Message
{
    /**
     * 发送 Message 消息 到 WebSocket 服务
     *  - composer require textalk/websocket
     * @param string|array $to 发送给谁 'ALL' 所有用户, 'user1' 单用户, ['user1','user2'] 多用户
     * @param array $message 要发送的信息
     * @param bool $requireInteraction 是否允许弹框一直显示
     */
    public static function sendToWs(string|array $to, array $message, bool $requireInteraction = true)
    {
        $data = [
            'cmd' => 'SEND',
            'value' => [
                'to' => $to,
                'data' => [
                    'type' => 'msg',
                    'data' => [
                        'title' => $message['title'],
                        'body' => $message['body'],
                        'requireInteraction' => $requireInteraction, // 是否允许弹框一直显示
                        'icon' => $message['icon'] ?? URL_STATIC . '/media/icon/apple-touch-icon.png',
                        'url' => $message['url'] ?? '', // 点击时要打开的网址
                        'target' => $message['target'] ?? '_blank', // _blank 新窗口, _page 内部新标签,  _href 当前浏览器, 其他则为 iframe 的 id
                        'callBackUrl' => $message['callBackUrl'] ?? '', // 关闭消息时(包括点击时的自动关闭)要回调的网址
                        'callBackParams' => $message['callBackParams'] ?? [], // 关闭消息时要回调的 POST 参数
                    ]
                ]
            ]
        ];
        /** @var \WebSocket\Client $client*/
        $client = Container::get('websocket');
        $client->text(json_encode($data));
    }
}
