<?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\Constant\ModelTypeDefine;
use Game\Data\AccountData;
use Game\GameLive;
use Game\Method\Player\AddPlayerExp;
use Game\Model\AccountModel;
use Game\Protobuf\GMChangeExp;
use Game\Protobuf\MGChangeExp;
use Gm\Config\ErrorCode;
use Game\Protobuf\PacketId;
use Game\Logic\AccountLogic;

class ChangeExp extends ControllerBase
{
    use AccountLogic;
    use AddPlayerExp;

    public const EXP_SEARCH = 1;
    public const EXP_CHANGE = 2;

    public GMChangeExp $sendMsg;

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

    public function run(): int
    {
        $account = $this->message->getAccount();
        $option = $this->message->getOption();
        $exp = $this->message->getExp();

        if(empty($account)) {
            $this->sendMsg->setCode(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
            SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_ChangeExp, $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_ChangeExp, $this->sendServer,
                $this->sendMsg, 0, Utils::getServerTimestamp());
            return ErrorDefine::SUCCESS;
        }
        ModelManager::getInstance()->clearModelList();
        ModelManager::getInstance()->setPlayerId($playerID);
        GameLive::getInstance()->InitProtagonistPlayerId($playerID);
        switch($option)
        {
            case self::EXP_SEARCH:
                break;
            case self::EXP_CHANGE:
                $this->addPlayerExp($exp, 0, true, $playerID);
                break;
        }
        /**
         * @var AccountModel $account
         */
        $account = ModelManager::getInstance()->getModel(ModelTypeDefine::ACCOUNT);
        $account->searchAccount($playerInfo);
        $level = $playerInfo[AccountData::DB_LEVEL] ?? 1;
        $exp = $playerInfo[AccountData::DB_EXP] ?? 0;
        $this->sendMsg->setCode(ErrorCode::SUCCESS);
        $this->sendMsg->setInfo(json_encode([AccountData::DB_LEVEL => $level, AccountData::DB_EXP => $exp]));
        SendServiceMsg::getInstance()->sendServiceMsg(PacketId::GM_ChangeExp, $this->sendServer,
            $this->sendMsg, 0, Utils::getServerTimestamp());
        return ErrorDefine::SUCCESS;
    }

}