<?php

namespace app\subscribe;

use app\entity\gateway\script\ElNotification;
use app\entity\gateway\script\Swal;
use app\entity\gateway\ws\OutMessage;
use app\entity\gateway\ws\PutMessage;
use app\entity\SysUser;
use app\entity\SysUserClient;
use app\entity\SysUserClientLog;
use app\enum\gateway\message\ScriptEnum;
use app\enum\gateway\message\SystemEnum;
use app\service\GatewayClientService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Event;

/**
 * 网关事件订阅类
 */
class GatewaySubscribe
{
    /**
     * 统一订阅监听注册
     * @param Event $event
     * @return void
     */
    public function subscribe(Event $event): void
    {
        $event->listen('gateway.clientLogin', [$this,'onClientLogin']);
        $event->listen('gateway.lockClient',[$this,'onLockClient']);
        $event->listen('gateway.clientClose',[$this,'onClientClose']);
    }

    /**
     * Ws客户端登录
     * @param $vars
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function onClientLogin($vars): void
    {
        /**
         * @var PutMessage $put
         * @var SysUser $sysUser
         */
        [$put, $sysUser] = $vars;


        $client = SysUserClient::where([
            'client_id'  => $put->getClientId(),
            'client_name'=> $put->getClientName(),
            'user_id'    => $put->userId,
        ])->find();
        /*
         * 判断客户端是否锁定状态
         */
        if($client && $client['is_lock']) {
            // 通知客户端锁定屏幕
            GatewayClientService::sendToClient($put->wsClientId,new OutMessage(
                SystemEnum::Lock_Client
            ));
        }
        /*
         * 客户端登录通知
         */
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';

        // 方式0. 通过enum枚举类型指定
        GatewayClientService::sendToClient($put->wsClientId, new OutMessage(
            ScriptEnum::ElNotification,
            new ElNotification(title: '登录成功,欢迎您', message: "当前登录Ip: $ip", position: 'bottom-right'),
        ));

//        // 方式1. 通过注入Array
//        GatewayClientService::sendToClient($put->wsClientId, new OutMessage(
//            ScriptEnum::create(
//                new Swal(title: '登录成功,欢迎您', text: "当前登录Ip: $ip")
//            ),
//        ));
    }

    /**
     * Ws客户端锁定
     * @param $vars
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function onLockClient($vars): void
    {
        /**
         * @var PutMessage $put
         */
        [$put] = $vars;

        $client = SysUserClient::where([
            'client_id'  => $put->getClientId(),
            'client_name'=> $put->getClientName(),
            'user_id'    => $put->userId,
        ])->find();
        if($client) {
            // 加密传递的锁屏密码
            $lock_password = password_hash($put->get('password',''), PASSWORD_DEFAULT);
            // 保存锁屏信息
            $client->save([
                'is_lock'=>1,
                'lock_password'=>$lock_password,
                'lock_time'=>date('Y-m-d H:i:s')
            ]);
            // 保存锁屏日志
            SysUserClientLog::create([
                'event'  => "{$put->type->value}.{$put->event->value}",
                'message'=> "A. 锁定客户端",
                'data'   => json_encode(['inputPass'=> $lock_password]),
                'create_time' => date('Y-m-d H:i:s'),
                'client_data_id' => $client['id']
            ]);
            // 通知客户端锁定屏幕
            GatewayClientService::sendToClient($put->wsClientId,new OutMessage(
                SystemEnum::Lock_Client
            ));
        }

    }


    /**
     * Ws客户端连接被关闭
     * @return void
     */
    public function onClientClose()
    {

    }
}