<?php

/**
 * 赛季分
 */

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\Logic\AccountLogic;
use Game\Logic\SeasonLogic;
use Game\Protobuf\GMSeasonScore;
use Game\Protobuf\MGSeasonScore;
use Game\Protobuf\PacketId;
use Gm\Config\ErrorCode;
use Game\Logic\PaiweiLevelLogic;

class SeasonScore extends ControllerBase
{
    use AccountLogic;
    use PaiweiLevelLogic;
    use SeasonLogic;

    private GMSeasonScore $sendMessage;

    private const TYPE_OPTION_SEARCH = 1;   //查询
    private const TYPE_OPTION_UPDATE = 2;   //修改

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

    public function run(): int
    {
        $account = $this->message->getAccount();
        $score = $this->message->getSeasonScore();
        //检查校验
        if(empty($account)) {
            return $this->sendFailMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        $playerId = $this->searchPlayerIdByNickName($account);
        if ($playerId == 0) {
            return $this->sendFailMessage(ErrorCode::ERROR_ACCOUNT_NOT_FOUND);
        }
        ModelManager::getInstance()->clearModelList();
        ModelManager::getInstance()->setPlayerId($playerId);

        if ($this->message->getOption() === self::TYPE_OPTION_SEARCH) {
            //查询熟练度
            return $this->sendSuccessMessage(ErrorCode::SUCCESS);
        }

        // 增加赛季积分
        $this->gmChangeSeasonScore($score);

        return $this->sendSuccessMessage(ErrorCode::SUCCESS);
    }

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

    private function sendSuccessMessage(int $code): int
    {
        $paiweiData = $this->getPaiweiLevel();
        $this->sendMessage->setCode($code);
        $this->sendMessage->setSeasonID($this->getSeasonId());
        $this->sendMessage->setSeasonScore($paiweiData->seasonScore);
        $this->sendMessage->setOverFlowExp($paiweiData->overFlowExp);
        $this->sendMessage->setHaveNum($paiweiData->haveRewardNum);
        $this->sendMessage->setNum($paiweiData->rewardNum);
        SendServiceMsg::getInstance()->sendServiceMsg(
            PacketId::GM_SeasonScore,
            $this->sendServer,
            $this->sendMessage,
            0,
            Utils::getServerTimestamp()
        );
        return ErrorDefine::SUCCESS;
    }
}
