<?php

/**
 *  pvp比赛内操作
 */

namespace Game\Controller\Pvp;

use Framework\Define\ErrorDefine;
use Framework\Log\LogMark;
use Framework\MVC\ControllerBase;
use Framework\MVC\ModelManager;
use Game\Constant\EventTypeDefine;
use Game\Constant\GameConstantDefine;
use Game\Constant\ModelTypeDefine;
use Game\Data\RecordData;
use Game\Logic\EventLogic;
use Game\Logic\SeasonLogic;
use Game\Model\RecordModel;
use Game\Protobuf\CGMatchOperation;

class CG_PvpMatchOperation extends ControllerBase
{
    use EventLogic;
    use SeasonLogic;

    public function __construct()
    {
        $this->message = new CGMatchOperation();
    }

    public function run(): int
    {
        $joinId = $this->message->getJoinId();
        //校验
        /**
         * @var RecordModel $recordModel
         */
        $recordModel = ModelManager::getInstance()->getModel(ModelTypeDefine::RECORD);
        $record = $recordModel->getRecordByJoinId($joinId);
        if (is_null($record)) {
            LogMark::getInstance()->markDebug(
                "[CG_PvpMatchOperation] not found record",
                array(
                    "JoinId" => $joinId
                )
            );
            return ErrorDefine::SUCCESS;
        }
        //排位赛,检查赛季开启
        if (in_array(
                $record->matchType, [
                                   GameConstantDefine::MATCH_MODE_SINGLE_PAI_WEI,
                                   GameConstantDefine::MATCH_MODE_TEAM_PAI_WEI]
            ) &&
            $this->getSeasonStatus() == GameConstantDefine::SEASON_STATUS_CLOSE) {
            return ErrorDefine::SUCCESS;
        }
        $param = array(
            GameConstantDefine::EVENT_KEY_MATCH_OPERATION => $this->message->getMatchOperation(),
            GameConstantDefine::EVENT_KEY_PVP_OPERATION => $this->message->getTarget(),
            GameConstantDefine::EVENT_KEY_MATCH_RECORD => $record,
            GameConstantDefine::EVENT_KEY_CAR_ID => $record->carId,
        );
        // 触发事件
        $this->triggerEvent(EventTypeDefine::EVENT_TYPE_TASK_MATCH_OPERATION, $param);
        //更新记录
        /**
         * @var RecordModel $recordModel
         */
        $recordModel = ModelManager::getInstance()->getModel(ModelTypeDefine::RECORD);
        $recordModel->updateRecordData(
            $joinId,
            array(
                RecordData::CLIENT_STATISTICS => $this->message->getStatistics()
            )
        );
        return ErrorDefine::SUCCESS;
    }
}
