<?php

/**
 * 日常任务操作
 */

namespace Game\Controller\Task;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Data\ActiveData;
use Game\Logic\ActiveLogic;
use Game\Logic\Task\DailyTaskLogic;
use Game\Protobuf\CGDailyTaskOption;
use Game\Protobuf\GCDailyTaskOptionResult;
use Game\Protobuf\PacketId;

class CG_DailyTaskOption extends ControllerBase
{
    use DailyTaskLogic;
    use ActiveLogic;

    private const OPTION_SUBMIT = 1;        //一键提交任务
    private const OPTION_GET_REWARD = 2;    //一键领取活跃度奖励

    private GCDailyTaskOptionResult $sendMessage;

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

    public function run(): int
    {
        $activeData = $this->getDailyActiveInfo();
        $this->sendMessage->setAPNum($activeData->activePoint);
        $this->sendMessage->setAPId($activeData->activeId);

        $option = $this->message->getOption();
        switch ($option)
        {
            case self::OPTION_SUBMIT:
                $code = $this->submit();
                break;
            case self::OPTION_GET_REWARD:
                $code = $this->getReward();
                break;
            default:
                $code = ClientErrorCode::TASK_DAILY_OPTION_ERROR;
        }
        $this->sendMessage->setCode($code);
        SendMessage::getInstance()->sendClient(PacketId::GC_DailyTaskOptionResult, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }

    private function submit(): int
    {
        $taskList = $this->getDoneDailyTask();
        if (empty($taskList)) {
            return ClientErrorCode::TASK_DAILY_NO_TASK_CAN_SUBMIT;
        }
        //提交任务
        $activeData = $this->submitDailyTask($taskList);
        //更新活跃度
        $this->sendMessage->setAPNum($activeData->activePoint);
        $this->sendMessage->setAPId($activeData->activeId);
        return ClientErrorCode::CLIENT_SUCCESS;
    }

    private function getReward(): int
    {
        //检查可领取奖励
        [$nowLv, $canLv, $maxLv] = $this->getActiveLvData();
        if ($nowLv >= $maxLv) {
            return ClientErrorCode::TASK_DAILY_REWARD_ALL_GET;
        }
        if ($nowLv >= $canLv) {
            return ClientErrorCode::TASK_DAILY_NO_REWARD_CAN_GET;
        }
        //领奖
        $activeData = $this->getActiveLvReward($nowLv, $canLv);
        //更新活跃度
        $this->sendMessage->setAPNum($activeData->activePoint);
        $this->sendMessage->setAPId($activeData->activeId);
        return ClientErrorCode::CLIENT_SUCCESS;
    }
}
