<?php

namespace app\logic\cmdpro;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/21
 * Time: 16:48
 */

/*
 Swoole\Server\Task Object
(
    [data] => Swoole\WebSocket\Frame Object
        (
            [fd] => 1
            [data] => {'cmd':'xxx','act'=>'xxx','data':'xxxx','time':xxxx,'token':xxx}
            [opcode] => 1
            [finish] => 1
        )

    [id] => 0
    [worker_id] => 2
    [flags] => 6
)

data:
{'cmd':'xxx','act'=>'xxx','data':'xxxx','time':xxxx,'token':xxx}
 **/

use app\lib\DataPack;
use app\lib\Wlog;
use app\lib\GlobConfigs;

class   CmdInf
{
    public function paraCmd($serv, \Swoole\Server\Task $task)
    {
        $fd = $task->data->fd;
        $dataPack = json_decode($task->data->data, true);
        $method = isset($dataPack['act']) ? $dataPack['act'] : '';

        if (empty($method) || !(method_exists($this, $method))) {
            $this->sendTo($serv, $fd, DataPack::toJson(['mtype' => 'error', 'data' => '无效的参数']), true);
            return;
        }

        try {
            return $this->$method($serv, $task);
        } catch (\Exception $e) {
            echo "发生异常或错误：" . $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getCode() . ' ' . $e->getMessage() . "\r\n";
            return;
        }

    }

    //单发
    public function sendTo($serv, $fd, $dataString, $close = false)
    {
        $serv->push($fd, $dataString);
        if ($close) {
            $serv->disconnect($fd);
        }
        return true;
    }

    //在线广播
    public function onlineBroad($serv, $dataString)
    {
        foreach ($serv->connections as $fd) {
            $serv->push($fd, $dataString);
        }
    }

    //用uid发
    public function sendToUid($serv, $uid, $dataString, $close = false)
    {
        $fd = intval($serv->utable->get($uid,'fid'));
        if ($fd) {
            return $this->sendTo($serv, $fd, $dataString, $close);
        }
        return false;
    }


}