<?php
/**
 *
 * @author：llbjj
 * @DateTime：2022/5/12 7:13
 * @Description：
 *
 */

namespace Application\Command\Swoole\Server;

use Swoole\Coroutine;
use Swoole\Process;
use Swoole\Server;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Swoole\Coroutine\Server\Connection;

class SwLogCommand extends \Application\Command\BasicCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('APP_PATH：'.APP_PATH);
        //开启LogTcp服务
        $tcpSv = new Server('127.0.0.1', 9509);
        $tcpSv->set([
            'worker_num' => 2, // 工作进程数量
            'task_worker_num' => 4,  // 异步任务进程数
            'open_eof_check' => true,   //打开EOF检测
            'package_eof'    => '|PHENOL|', //设置EOF
            'package_max_length' => 1024 * 1024 * 5
        ]);

        //接收数据
        $tcpSv->on('receive', function ($sv, $fd, $reactorId, $data) use($output) {
            $sendDataArr = array_filter(explode('|PHENOL|', $data));
            if(!empty($sendDataArr)) {
                foreach($sendDataArr as $sendData) {
                    $sv->task($sendData);
                }
            }

            $output->writeln('oprt Logs writing ...'.PHP_EOL);
        });

        // 定义异步任务
        $tcpSv->on('task', function($sv, $task_id, $src_work_id, $data) use ($output){
            $output->writeln('start write Log'.PHP_EOL);
            $logObj = $this->LocalService()->log;
            if(!$logObj->saveLogToDb($data)){
                //日志落库失败，将日志数据存缓存文件中
                $logObj->saveLogToFile($data);
            }
            $sv->finish("{$data} -> OK");
        });
        //处理异步任务的结果(此回调函数在worker进程中执行)
        $tcpSv->on('Finish', function ($serv, $task_id, $data) {
            echo "AsyncTask[{$task_id}] Finish: {$data}".PHP_EOL;
        });

        $tcpSv->start();
        //parent::execute($input, $output); // TODO: Change the autogenerated stub
        return 0;
    }
}