<?php
/**
 * GM 完成任务
 **/
namespace Game\Controller\Gm;

use Framework\Define\ErrorDefine;
use Framework\Lib\Utils;
use Framework\MVC\ControllerBase;
use Framework\MVC\ModelManager;
use Framework\Network\SendServiceMsg;
use Game\GameLive;
use Game\Logic\Task\TaskLogic;
use Game\Protobuf\GMCompleteTask;
use Game\Protobuf\MGCompleteTask;
use Gm\Config\ErrorCode;
use Game\Protobuf\PacketId;
use Game\Logic\AccountLogic;

class CompleteTask extends ControllerBase
{
    use AccountLogic;
    use TaskLogic;

    public GMCompleteTask $sendMsg;

    public function __construct() {
        $this->message = new MGCompleteTask();
        $this->sendMsg = new GMCompleteTask();
    }

    public function run(): int
    {
        $account = $this->message->getAccount();
        $taskID = $this->message->getTaskID();

        if(empty($account)) {
            $this->sendMsg->setCode(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
            SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_CompleteTask,
                $this->sendServer, $this->sendMsg, 0, Utils::getServerTimestamp());
            return ErrorDefine::SUCCESS;
        }

        // 查询id
        $playerID = $this->searchPlayerIdByNickName($account);

        if(empty($playerID)) {
            $this->sendMsg->setCode(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
            SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_CompleteTask,
                $this->sendServer, $this->sendMsg, 0, Utils::getServerTimestamp());
            return ErrorDefine::SUCCESS;
        }
        ModelManager::getInstance()->clearModelList();
        ModelManager::getInstance()->setPlayerId($playerID);
        GameLive::getInstance()->InitProtagonistPlayerId($playerID);

        if(!$this->gmCompleteTask($taskID)) {
            $this->sendMsg->setCode(ErrorCode::ERROR_TASK_NOT_FOUND);
            SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_CompleteTask,
                $this->sendServer, $this->sendMsg, 0, Utils::getServerTimestamp());
            return ErrorDefine::SUCCESS;
        }
        $this->sendMsg->setCode(ErrorCode::SUCCESS);
        SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_CompleteTask, $this->sendServer,
            $this->sendMsg, 0, Utils::getServerTimestamp());
        return ErrorDefine::SUCCESS;
    }

}