<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/19 8:28
 * @Description：
 *
 */

namespace Application\Command\Swoole\Client;

use Application\Service\BaseService;
use Interop\Container\ContainerInterface;

class SwTaskClient extends BaseService
{
    protected $swClient;
    public function __construct(ContainerInterface $container)
    {
        parent::__construct($container);
    }

    /**
     * @files.saveConflictResolution: overwriteFileOnDisk
     * @Description: 连接swoole服务器
     * @Author: llbjj
     * @Date: 2022-07-04 20:23:15
     * @return {*}
     */
    private function connect() {
        $this->swClient = new \Swoole\Client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        $svConfigData = [
            'ip' => '127.0.0.1',
            'port' => 9511,
            'timeout' => -1
        ];
        $isConnect = $this->swClient->connect($svConfigData['ip'], $svConfigData['port'], $svConfigData['timeout']);
        if(!$isConnect) {
            throw new  \Exception("connect failed. Error: {".$this->swClient->errCode."}\n");
        }
    }

    /**
     * @files.saveConflictResolution: overwriteFileOnDisk
     * @Description: 关闭swoole客户端
     * @Author: llbjj
     * @Date: 2022-07-04 20:25:50
     * @return {*}
     */    
    private function close() {
        $this->swClient->close();
    }
    /**
     * Notes: 投递日志异步任务
     * User: llbjj
     * DateTime: 2022/5/19 8:54
     *
     */
    public function send(array $data){
        // 是否开启了异步任务
        if($this->LocalService()->config['swAsyncTask']['task']) {
            $data['token'] = $this->LocalService()->identity->getToken();
            $data['domainName'] = $_SERVER['HTTP_HOST'];

            $this->connect();
            $data = json_encode($data, true);
            $data .= '|PHENOL|';
            $this->swClient->send($data);
            self::close();
        }else{
            $this->LocalService()->{$data['svName']}->{$data['methodName']}($data['params']);
        }
    }
}