<?php

/**
 * 跑马灯定时器
 */

namespace Gm\CLI;

use Framework\Log\LogMark;
use Game\Protobuf\MGLampAdd;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;
use Gm\Controller\Gm;
use Gm\Controller\Lamp;
use Gm\Core\RedisLib;
use Gm\Model\Gms;
use Gm\Model\Lamps;
use Gm\Model\Logs;
use Gm\Model\Servers;

class LampTimer
{
    public array $dbData = [];

    public function run(): int
    {
        $this->getRDBData();
        if(empty($this->dbData)) {
            return ErrorCode::SUCCESS;
        }

        // 查询跑马灯 给相应服务器发送消息并记录日志
        foreach ($this->dbData as $id) {
            $lamp = Lamps::GetLampById($id);
            if(empty($lamp)) {
                return ErrorCode::SUCCESS;
            }
            $servers = json_decode($lamp['servers'], true);

            $sendMsg = new MGLampAdd();
            $sendMsg->setID($lamp['id']);
            $sendMsg->setTimeEnd($lamp['time_end']);
            $sendMsg->setContent($lamp['content']);
            $sendMsg->setNum($lamp['num']);

            $token = md5($id);
            foreach ($servers as $sid) {
                // 给相应服务器发送消息
                $server_info = Servers::GetServerById($sid);
                if (!Gms::SaveMsgDB($sid, PacketId::MG_LampAdd, $token, $sendMsg)) {
                    LogMark::getInstance()->markError(
                        ErrorCode::ERROR_LAMP_SAVE_DB_FAILED,
                        'send lamp save msg db error!',
                        ['serverID' => $sid, 'packetID' => PacketId::MG_LampAdd]
                    );

                    $info = 'lamp timer 给' . $server_info['name'] .
                        ' 增加跑马灯' . $lamp['name'] . '失败！';
                    // 返回失败
                    Logs::InsData(GM::LAMP_LOG_TYPE, 'System', $info, '');
                    continue;
                    // 取出返回数据
                }
            }
            // 修改状态
            Lamps::UpdateLampStatus($id, 2);
            // 删除定时任务
            RedisLib::GetInstance()->zRem(Lamp::LAMP_TIMER_KEY, $id);

            $this->dbData = [];

        }
        return ErrorCode::SUCCESS;
    }

    public function getRDBData():bool {
        $res = RedisLib::GetInstance()->zRangeByScore(Lamp::LAMP_TIMER_KEY, 0, time());
        if(!empty($res)) {
            $this->dbData = $res;
        }
        return true;
    }
}
