<?php

/**
 * 提交任务
 */

namespace Game\Controller\Task;

use Framework\Define\ErrorDefine;
use Framework\MVC\ControllerBase;
use Framework\Network\SendMessage;
use Game\Constant\ClientErrorCode;
use Game\Constant\ConstTemplate\TemplateTask;
use Game\Data\TaskData;
use Game\Logic\Task\FriendIntimacyRewardLogic;
use Game\Logic\Task\TaskLogic;
use Game\Protobuf\CGSubmitTask;
use Game\Protobuf\GCSubmitTaskReset;
use Game\Protobuf\PacketId;

class CG_SubmitTask extends ControllerBase
{
    use TaskLogic;
    use FriendIntimacyRewardLogic;

    private GCSubmitTaskReset $sendMessage;

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

    public function run(): int
    {
        $taskId = $this->message->getTaskId();
        //检查任务
        $code = $this->checkTaskExist($taskId);
        if ($code != ClientErrorCode::CLIENT_SUCCESS) {
            return $this->sendClientMessage($code);
        }
        $taskData = $this->searchTask($taskId);
        if (is_null($taskData)) {
            return $this->sendClientMessage(ClientErrorCode::TASK_NOT_FOUND);
        }
        //检查状态
        /**
         * @var TaskData $taskData
         */
        if ($taskData->status == TaskData::STATUS_DOING) {
            return $this->sendClientMessage(ClientErrorCode::TASK_IS_DOING);
        }
        if ($taskData->status == TaskData::STATUS_OVER) {
            return $this->sendClientMessage(ClientErrorCode::TASK_IS_OVER);
        }
        //战令任务 检查对应周是否开启
        if (($taskData->taskConfig[TemplateTask::TaskType] == TemplateTask::TASK_TYPE_SEASON_WEEK) &&
            !$this->checkHasOpenWeek($taskData->taskConfig[TemplateTask::GroupId])) {
                return $this->sendClientMessage(ClientErrorCode::TASK_SEASON_WEEK_NOT_OPEN);
            }
        //战令任务 检查是否解锁
        if ($taskData->taskConfig[TemplateTask::TaskType] == TemplateTask::TASK_TYPE_SEASON &&
            !$this->checkHasOpenExpert()) {
            return $this->sendClientMessage(ClientErrorCode::TASK_SEASON_EXPERT_NOT_OPEN);
        }
        //好友亲密度任务 检查是否开启
        if ($taskData->taskConfig[TemplateTask::TaskType] == TemplateTask::TASK_TYPE_FRIEND_INTIMACY &&
            !$this->checkFriendIntimacyRewardIsOpen()) {
            return $this->sendClientMessage(ClientErrorCode::FRIEND_INTIMACY_REWARD_NOT_OPEN);
        }

        //提交任务
        $this->submitTask($taskData);
        return $this->sendClientMessage(ClientErrorCode::CLIENT_SUCCESS);
    }

    private function sendClientMessage(int $code): int
    {
        $this->sendMessage->setCode($code);
        $this->sendMessage->setTaskId($this->message->getTaskId());
        SendMessage::getInstance()->sendClient(PacketId::GC_SubmitTaskReset, $this->sendMessage);
        return ErrorDefine::SUCCESS;
    }
}
