<?php

namespace app\command\admin;


use app\entity\SysUserClient;
use app\entity\SysUserClientLog;
use app\service\admin\LoginService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use Workerman\Worker as WmWorker;

class Worker extends Command
{
    protected function configure()
    {
        $this->setName('admin:worker')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, 'Run the workerman server in daemon mode.')
            ->setDescription('后台系统worker服务');
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('convert start');

        $action = $input->getArgument('action');
        $mode = $input->getOption('mode');


        global $argv;

        $argv = [];

        array_unshift($argv, 'think', $action);
        if ($mode == 'd') {
            $argv[] = '-d';
        } else if ($mode == 'g') {
            $argv[] = '-g';
        }

        /*
         * 创建后台ws链接
         */
        $adminWorker = new WmWorker('websocket://0.0.0.0:19980');
        $adminWorker->onMessage = function ($connection, $message) {
            var_dump($message);
            $this->app->event->trigger('admin.websocket.Open', $connection, $message);
            $messageJson = json_decode($message, true);
            if($messageJson) {
                if($messageJson['event'] == 'bind_connect_id') {
                    $authorization = $messageJson['data']['token'] ?? '';
                    $clientId = $messageJson['data']['clientId'] ?? '';
                    $clientName = $messageJson['data']['clientName'] ?? '';
                    $clientVersion = $messageJson['data']['clientVersion'] ?? '';
                    $authorization = str_replace('Bearer ', '', $authorization);
                    $loginSrv = new LoginService();
                    $auth = $loginSrv->checkUserAccessToken($authorization);
                    var_dump("当前用户: ".$auth->userId);
                    // 用户信息
                    $connection->userId = $auth->userId;
                    // 客户端信息
                    $connection->clientId = $clientId;
                    $connection->clientName = $clientName;
                    $connection->clientVersion = $clientVersion;
                    // 绑定成功通知
                    $connection->send(json_encode(['event'=>'BIND_USER_SUCCESS','userId'=>$auth->userId]));
                    $client = SysUserClient::where([
                        'client_id'  => $clientId,
                        'client_name'=> $clientName,
                        'user_id'    => $connection->userId,
                    ])->find();
                    if($client && $client['is_lock']) {
                        // 锁定屏幕
                        $connection->send(json_encode(['event'=>'LOCK_CLIENT_SCREEN']));
                    }
                }
                if ($messageJson['event'] == 'lock_client_screen') {
                    if($connection->userId) {
                        $lock_password  = $messageJson['data']['lockPassword'] ?? '';
                        var_dump("锁定客户端/通知全部ws触发锁定操作");
                        $client = SysUserClient::where([
                            'client_id'  => $connection->clientId,
                            'client_name'=> $connection->clientName,
                            'user_id'    => $connection->userId,
                        ])->find();
                        if($client) {
                            $client->save(['is_lock'=>1,'lock_password'=>$lock_password,'lock_time'=>date('Y-m-d H:i:s')]);
                            // 锁定屏幕
                            $connection->send(json_encode(['event'=>'LOCK_CLIENT_SCREEN']));
                            if(empty($lock_password)){
                                $lock_password = password_hash("1", PASSWORD_DEFAULT);
                            }
                            SysUserClientLog::create([
                                'event'  => 'LOCK',
                                'message'=> "A. 锁定客户端",
                                'data'   => json_encode(['inputPass'=> $lock_password]),
                                'create_time' => date('Y-m-d H:i:s'),
                                'client_data_id'=> $client['id']
                            ]);
                        }
                    }
                }
            }
        };
        $adminWorker->onClose = function ($connection) {
            $this->app->event->trigger('admin.websocket.Close', $connection);
        };

        WmWorker::runAll();
    }
}