<?php
/**
 * 保存车牌号
 * @date 2022-5-25
 * @author leeFx
 **/
namespace Game\Controller\Car;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Config\GameConfig;
use Game\Constant\DBTableDefine;
use Game\Constant\GameErrorCode;
use Game\Data\CarExteriorRefitData;
use Game\Logic\CarExteriorRefitLogic;
use Game\Protobuf\CGLicenceSave;
use Game\Protobuf\GCSyncExteriorRefit;
use Game\Protobuf\PacketId;

class LicenceSave extends ControllerBase
{
    use CarExteriorRefitLogic;

    public GCSyncExteriorRefit $sendMessage;

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

    public function run(): int
    {
        // 车牌号
        $licence = $this->message->getLicence();
        $refitID = $this->message->getRefitID();

        $getTime = Utils::getServerTimestamp();

        $refit = new CarExteriorRefitData(
            $this->playerId,
            $this->makeExteriorRefitId(),
            $refitID,
            0,
            $getTime,
            $licence
        );
        if(!$refit->createCarExteriorRefit()) {
            LogMark::getInstance()->markError(
                GameErrorCode::DATA_CREATE_ERROR,
                '[exterior refit] create car exterior refit error!', (array)$refit
            );
            return ErrorDefine::SUCCESS;
        }
        $this->sendMessage->setUID($refit->uid);
        $this->sendMessage->setCarID($refit->carID);
        $this->sendMessage->setTplID($refit->tplID);
        $this->sendMessage->setParams($refit->params);
        $this->sendMessage->setGetTime($refit->getTime);
        SendMessage::getInstance()->sendClient(
            PacketId::GC_SyncExteriorRefit, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }

    // 创建唯一id
    public function makeExteriorRefitId(): int
    {
        $index = $this->getUidIndex();
        return Utils::makeObjectID(GameConfig::getInstance()->SERVER_ID(), DBTableDefine::TABLE_EXTERIOR_REFIT, $index);
    }
}