<?php

/**
 * 任务逻辑基类
 */

namespace Game\Model\Task\Logic;

use Framework\Log\LogMark;
use Framework\Logic\TemplateHelp;
use Game\Constant\ConstTemplate\TemplateTask;
use Game\Constant\GameErrorCode;
use Game\Constant\TemplateDefine;
use Game\Data\TaskData;

abstract class TaskLogicBase
{
    use TemplateHelp;

    protected int $playerId;
    protected bool $isRegister = false;     //初始创建用户,初始检查任务条件用

    public function setPlayerId(int $playerId)
    {
        $this->playerId = $playerId;
    }

    //设置为初始创建用户
    public function setIsRegister()
    {
        $this->isRegister = true;
    }

    protected function checkIsDone(TaskData $taskData): bool
    {
        if ($taskData->taskConfig[TemplateTask::TargetHandle] == TemplateTask::TASK_TARGET_HANDLE_MIN) {
            //记录最小值
            if ($taskData->schedule > 0 && $taskData->schedule <= $taskData->taskConfig[TemplateTask::Target]) {
                return true;
            }
        } else {
            if ($taskData->schedule >= $taskData->taskConfig[TemplateTask::Target]) {
                return true;
            }
        }
        return false;
    }

    //更新进度 需要检查值记录方式
    protected function updateTaskSchedule(TaskData $taskData, int $num)
    {
        if ($num == 0) {
            return;
        }
        switch ($taskData->taskConfig[TemplateTask::TargetHandle]) {
            case TemplateTask::TASK_TARGET_HANDLE_ADD:
                //累加
                $taskData->schedule += $num;
                $taskData->isChange = true;
                break;
            case TemplateTask::TASK_TARGET_HANDLE_MIN:
                //记录最小值
                if ($taskData->schedule == 0) {
                    $taskData->schedule = $num;
                    $taskData->isChange = true;
                } else {
                    if ($num < $taskData->schedule) {
                        $taskData->schedule = $num;
                        $taskData->isChange = true;
                    }
                }
                break;
            case TemplateTask::TASK_TARGET_HANDLE_MAX:
                //记录最大值
                if ($num > $taskData->schedule) {
                    $taskData->schedule = $num;
                    $taskData->isChange = true;
                }
                break;
            default:
                break;

        }
    }

    protected function getTaskConfigByTaskId(int $taskId): ?array
    {
        $taskConfig = $this->getTitle(TemplateDefine::TYPE_TASK, $taskId);
        if (is_null($taskConfig)) {
            LogMark::getInstance()->markError(
                GameErrorCode::TASK_ID_NOT_FOUND,
                "[TaskLogicBase] taskId not found",
                array(
                    "taskId" => $taskId
                )
            );
        }
        return $taskConfig;
    }

    abstract public function getDefaultValue(TaskData $taskData, array $param);
    abstract public function updateTask(TaskData $taskData, array $param);
}
