<?php

/**
 * 跑马灯撤回
 */

namespace Game\Controller\Gm;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\Network\SendServiceMsg;
use Game\Constant\DBTableDefine;
use Game\Constant\ModelTypeDefine;
use Game\Protobuf\GMLampCancel;
use Game\Protobuf\MGLampAdd;
use Game\Protobuf\MGLampCancel;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;
use Framework\DB\Handler\CommonDBHandler;
use Framework\Logic\CommonDataLogic;

class LampCancel extends ControllerBase
{
    use CommonDBHandler;
    use CommonDataLogic;

    private GMLampCancel $sendMessage;

    public function __construct()
    {
        $this->message = new MGLampCancel();
        $this->sendMessage = new GMLampCancel();
    }

    public function run(): int
    {
        $id = $this->message->getID();
        $commonID = $this->getCommonValueByModel(ModelTypeDefine::LAMP);

        if(is_null($commonID) || $commonID != $id) {
            $this->sendMessage(ErrorCode::ERROR_LAMP_CANCEL_FAILED);
        }

        $this->searchTermMultiCommon($ret, DBTableDefine::TABLE_LAMP, 0, [$commonID]);
        $lampMsg = new MGLampAdd();
        $strMsg = base64_decode($ret[$commonID]);
        $lampMsg->mergeFromString($strMsg);
        $lampMsg->setNum(0);
        // 新增数据
        $data[$id] = base64_encode($lampMsg->serializeToString());
        $this->updateCommonTitle(DBTableDefine::TABLE_LAMP, 0, $data);
        return $this->sendMessage(ErrorCode::SUCCESS);
    }

    private function sendMessage(int $code): int
    {
        $this->sendMessage->setCode($code);
        SendServiceMsg::getInstance()->sendServiceMsg(
            PacketId::GM_LampCancel,
            $this->sendServer,
            $this->sendMessage,
            0,
            Utils::getServerTimestamp()
        );
        return ErrorDefine::SUCCESS;
    }
}
