<?php

/**
 * 赛车强化任务
 * 限定条件 carId
 */

namespace Game\Model\Task\Logic;

use Game\Constant\ConstTemplate\TemplateTask;
use Game\Constant\GameConstantDefine;
use Game\Constant\TaskLogicDefine;
use Game\Data\TaskData;
use Game\Logic\AccountLogic;
use Game\Logic\CarLogic;
use Game\Data\AccountData;

class TaskLogicCarGrade extends TaskLogicBase
{
    use CarLogic;
    use AccountLogic;

    public function getDefaultValue(TaskData $taskData, array $param)
    {
        //车升级次数,不限车辆,初始为0,次数从接到后开始累计
        if ($taskData->taskConfig[TemplateTask::ConditionType] == TaskLogicDefine::TASK_CONDITION_CAR_UPGRADE_NUM) {
            return;
        }
        //新号初始车等级1级
        if ($this->isRegister) {
            $carLv = 1;
        } else {
            //检查已有等级
            $carId = $this->getNeedCarId($taskData->taskConfig);
            $carLv = 0;
            if ($carId != 0) {
                $carLv = $this->getCarLv($carId);
            }
        }
        $this->updateTaskSchedule($taskData, $carLv);
        if ($this->checkIsDone($taskData)) {
            $taskData->schedule = $taskData->taskConfig[TemplateTask::Target];
            $taskData->status = TaskData::STATUS_DONE;
        }
    }

    /**
     * @param TaskData $taskData
     * @param array $param
     * param参数
     *      EVENT_KEY_NUM => 强化等级1
     *      EVENT_KEY_CAR_ID=>CarTplId
     */
    public function updateTask(TaskData $taskData, array $param)
    {
        if (!isset($param[GameConstantDefine::EVENT_KEY_NUM])) {
            return;
        }
        if ($taskData->taskConfig[TemplateTask::ConditionType] == TaskLogicDefine::TASK_CONDITION_CAR_UPGRADE_NUM &&
            $param[GameConstantDefine::EVENT_KEY_NEW_CAR]) {
            //升级次数任务,检查是否新车
            return;
        }
        //检查是否要求指定赛车
        $needCarId = $this->getNeedCarId($taskData->taskConfig);
        if ($needCarId != 0 && $needCarId != $param[GameConstantDefine::EVENT_KEY_CAR_ID]) {
            return;
        }
        $num = $param[GameConstantDefine::EVENT_KEY_NUM];
        $this->updateTaskSchedule($taskData, $num);
        if ($this->checkIsDone($taskData)) {
            $taskData->schedule = $taskData->taskConfig[TemplateTask::Target];
            $taskData->status = TaskData::STATUS_DONE;
        }
    }

    private function getNeedCarId(array $taskConfig): int
    {
        return $taskConfig[TemplateTask::Condition];
    }

    //查询车强化等级
    private function getCarLv(int $carId): int
    {
        $carData = $this->searchCarDataByCarID($carId);
        if (is_null($carData)) {
            return 0;
        }
        return $carData->level;
    }
}
