<?php

/**
 * 使用大喇叭检查
 */

namespace Game\Controller\GameBag;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Constant\ConstTemplate\TemplateConst;
use Game\Constant\ConstTemplate\TemplateItem;
use Game\Constant\TemplateDefine;
use Game\Logic\ItemLogic;
use Game\Protobuf\CGUseHorn;
use Game\Protobuf\GCUseHorn;
use Game\Protobuf\PacketId;

class CG_UseHorn extends ControllerBase
{
    use ItemLogic;

    private GCUseHorn $sendMessage;

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

    public function run(): int
    {
        //检查道具
        if ($this->getItemNumByTplID(TemplateItem::ITEM_ID_HORN) > 0) {
            $this->subItemByTID(TemplateItem::ITEM_ID_HORN, 1);
            $this->sendMessage->setCode(ClientErrorCode::CLIENT_SUCCESS);
            SendMessage::getInstance()->sendClient(PacketId::GC_UseHorn, $this->sendMessage);
            return ErrorDefine::SUCCESS;
        }
        //检查货币
        $moneyId = $this->getTerm(
            TemplateDefine::TYPE_CONST,
            TemplateConst::Const_Horn_Money_Id,
            TemplateConst::ConstNum
        );
        $needMoney = $this->getTerm(
            TemplateDefine::TYPE_CONST,
            TemplateConst::Const_Horn_Money_Num,
            TemplateConst::ConstNum
        );
        $hasMoney = $this->getMoney($moneyId);
        if ($hasMoney < $needMoney) {
            $this->sendMessage->setCode(
                $this->getMoneyNotEnoughCode($moneyId)
            );
        } else {
            //扣钱
            $this->subMoney($moneyId, $needMoney);
            $this->sendMessage->setCode(ClientErrorCode::CLIENT_SUCCESS);
        }
        SendMessage::getInstance()->sendClient(PacketId::GC_UseHorn, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}
