<?php

/**
 * 支线任务--只有当前驾驶的车更新进度
 */

namespace Game\Model\Task\Manager;

use Framework\DB\Handler\PlayerDBPipe;
use Framework\Log\LogMark;
use Framework\DB\Handler\PlayerDBHandler;
use Game\Constant\ConstTemplate\TemplateInitPlayer;
use Game\Constant\DBTableDefine;
use Game\Constant\GameErrorCode;
use Game\Constant\TemplateDefine;
use Game\Data\TaskData;
use Game\Logic\CarLogic;

class BranchTaskManager extends TaskMangerModelBase
{
    use PlayerDBHandler;
    use CarLogic;

    private ?int $carId = null;
    private ?array $branchTaskConfig = null;    //支线任务id配置
    private const LV = "lv";    //当前支线任务等级

    //初始任务
    public function initBranchTask(int $carId)
    {
        $this->carId = $carId;
        //获取全部任务
        $this->getAllBranchConfig($carId);
        if (empty($this->branchTaskConfig)) {
            $this->branchTaskConfig = null;
            return;
        }
        //创建全部任务
        foreach ($this->branchTaskConfig as $lv => $taskIdList) {
            if (empty($taskIdList)) {
                LogMark::getInstance()->markDebug(
                    "[BranchTaskManager] not found branch task lv",
                    array(
                        "carId" => $this->carId,
                        "lv" => $lv
                    )
                );
                continue;
            }
            if ($lv == 1) {
                //1级任务通知
                $this->createBranchTaskByLv($taskIdList);
            } else {
                //其他等级任务,不通知
                $this->createBranchTaskByLv($taskIdList, false);
            }
        }
        $this->updateBranchTaskLv(1);
        $this->branchTaskConfig = null;
    }

    public function getIsRegister(): bool
    {
        return $this->isRegister;
    }

    public function pipeCreateBranchTask(int $carId)
    {
        $this->carId = $carId;
        //获取全部任务
        $this->getAllBranchConfig($carId);
        if (empty($this->branchTaskConfig)) {
            $this->branchTaskConfig = null;
            return;
        }
        PlayerDBPipe::getInstance()->start($this->playerId);
        //创建全部任务
        foreach ($this->branchTaskConfig as $lv => $taskIdList) {
            if (empty($taskIdList)) {
                LogMark::getInstance()->markDebug(
                    "[BranchTaskManager] not found branch task lv",
                    array(
                        "carId" => $this->carId,
                        "lv" => $lv
                    )
                );
                continue;
            }
            if ($lv == 1) {
                //1级任务通知
                $this->createBranchTaskByLv($taskIdList);
            } else {
                //其他等级任务,不通知
                $this->createBranchTaskByLv($taskIdList, false);
            }
        }
        PlayerDBPipe::getInstance()->finish();
        //更新支线任务索引
        $taskIndexList = array(
            self::LV => 1
        );
        $tempTaskList = $this->getPipeTempTaskList();
        foreach ($this->branchTaskConfig as $lv => $taskIdList) {
            foreach ($taskIdList as $taskId) {
                if (isset($tempTaskList[$taskId])) {
                    $taskIndexList[$taskId] = $tempTaskList[$taskId]->status;
                }
            }
        }
        $this->initBranchIndex($taskIndexList);
        $this->branchTaskConfig = null;
        $this->clearPipeTempTaskList();
    }

    //查询对应等级级任务 创建任务
    private function createBranchTaskByLv(array $taskIdList, bool $isSync = true)
    {
        $param = array(
            "CarId" => $this->carId,
            "IsSync" => $isSync
        );
        //创建任务
        foreach ($taskIdList as $taskId) {
            if (false == $this->createTask($taskId, $param)) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_BRANCH_CREATE_ERROR,
                    "[BranchTaskManager] branch task create error",
                    array(
                        "taskId" => $taskId
                    )
                );
            }
        }
    }

    //查询对应车当前的任务
    public function getBranchTaskByCarId(int $carId): array
    {
        $this->carId = $carId;
        $allBranchTaskList = $this->getAllBranchTaskList();
        if (empty($allBranchTaskList)) {
            //初始任务
            $this->initBranchTask($this->carId);
            $allBranchTaskList = $this->getAllBranchTaskList();
            if (empty($allBranchTaskList)) {
                return array([], []);
            }
        }
        $taskList = array();
        $completeTaskList = array();
        //查询当前等级和对应任务
        $lv = $allBranchTaskList[self::LV];
        $branchTaskList = $this->getBranchConfigByLv($carId, $lv);
        foreach ($branchTaskList as $taskId) {
            $status = $allBranchTaskList[$taskId];
            if ($status == TaskData::STATUS_OVER) {
                $completeTaskList[] = $taskId;
            } else {
                $taskData = $this->getTask($taskId);
                if (!is_null($taskData) && $taskData->taskId != 0) {
                    $taskList[] = $taskData;
                }
            }
        }
        $this->carId = null;
        $this->branchTaskConfig = null;
        return array($taskList, $completeTaskList);
    }

    //完成当前等级主任务,如果有下一级任务,将下一级任务通知状态置为true
    public function completeBranchMainTask(int $carId, int $lv): array
    {
        $this->carId = $carId;
        //检查是否有下一级任务
        $nextLvTaskList = $this->getBranchConfigByLv($carId, $lv + 1);
        if (empty($nextLvTaskList)) {
            //没有后续任务 当前任务继续保留
            return array();
        }
        //删除当前等级任务
        $nowLvTaskList = $this->getBranchConfigByLv($carId, $lv);
        foreach ($nowLvTaskList as $taskId) {
            $this->delTask($taskId);
        }
        $unlockTaskList = array();
        //解锁下一级任务
        foreach ($nextLvTaskList as $taskId) {
            $taskData = $this->getTask($taskId);
            if (is_null($taskData)) {
                continue;
            }
            if ($taskData->taskId == 0) {
                //新任务
                $param = array(
                    "CarId" => $carId,
                    "IsSync" => true
                );
                if (false == $this->createTask($taskId, $param)) {
                    continue;
                }
                $taskData = $this->getTask($taskId);
            } else {
                //修改任务属性
                $taskData->changeSync(true);
            }
            $unlockTaskList[] = $taskData;
        }
        //更新支线任务等级
        $this->updateBranchTaskLv($lv + 1);
        return $unlockTaskList;
    }

    //获取全部支线任务
    private function getAllBranchConfig(int $carId)
    {
        if (is_null($this->branchTaskConfig)) {
            $configInitData = $this->getTitle(TemplateDefine::TYPE_INIT_PLAYER, TemplateInitPlayer::DEFAULT_ID);
            $taskListConfig = $configInitData[TemplateInitPlayer::BranchTaskList];
            if (!isset($taskListConfig[$carId])) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_BRANCH_CAR_NOT_FOUND,
                    "[BranchTaskManager] not found car branch task",
                    array(
                        "carId" => $carId
                    )
                );
                $this->branchTaskConfig = array();
            } else {
                $this->branchTaskConfig = $taskListConfig[$carId];
            }
        }
    }

    //获取配置支线任务id
    private function getBranchConfigByLv(int $carId, int $lv): array
    {
        if (is_null($this->branchTaskConfig)) {
            $configInitData = $this->getTitle(TemplateDefine::TYPE_INIT_PLAYER, TemplateInitPlayer::DEFAULT_ID);
            $taskListConfig = $configInitData[TemplateInitPlayer::BranchTaskList];
            if (!isset($taskListConfig[$carId])) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_BRANCH_CAR_NOT_FOUND,
                    "[BranchTaskManager] not found car branch task",
                    array(
                        "carId" => $carId
                    )
                );
                return array();
            }
            $this->branchTaskConfig = $taskListConfig[$carId];
        }
        //检查有没有对应等级的任务
        return $this->branchTaskConfig[$lv] ?? array();
    }

    //获取当前车的全部任务id
    private function getAllBranchTaskList(): array
    {
        $result = array();
        $this->searchTitle(
            $this->getDBTable(),
            $this->playerId,
            $this->carId,
            $result,
        );
        ksort($result);
        return $result;
    }

    private function getDBTable(): int
    {
        return DBTableDefine::TABLE_TASK_BRANCH;
    }

    //更新当前支线任务等级
    private function updateBranchTaskLv(int $lv): bool
    {
        return $this->updateTitle(
            $this->getDBTable(),
            $this->playerId,
            $this->carId,
            array(
                self::LV => $lv
            ),
        );
    }

    private function initBranchIndex(array $data): bool
    {
        return $this->updateTitle(
            $this->getDBTable(),
            $this->playerId,
            $this->carId,
            $data,
        );
    }
}
