<?php

/**
 * 折算过期道具
 */

namespace Game\Controller\GameBag;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Logic\ItemLogic;
use Game\Protobuf\CGConvertExpireItem;
use Game\Protobuf\GCConvertExpireItem;
use Game\Protobuf\ItemSingle;
use Game\Protobuf\PacketId;

class CG_ConvertExpireItem extends ControllerBase
{
    use ItemLogic;

    private GCConvertExpireItem $sendMessage;

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

    public function run(): int
    {
        $itemList = array();
        /**
         * @var ItemSingle $item
         */
        foreach ($this->message->getItem() as $item) {
            $uId = $item->getUid();
            $itemNum = $item->getNum();
            isset($itemList[$uId]) ? $itemList[$uId] += $itemNum : $itemList[$uId] = $itemNum;
        }
        [$code, $convertItem] = $this->convertExpireItem($itemList);
        $this->sendMessage->setCode($code);
        $this->sendMessage->setItem($convertItem);
        SendMessage::getInstance()->sendClient(PacketId::GC_ConvertExpireItem, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}
