<?php

/**
 * 福利周任务管理
 */

namespace Game\Model\Task\Manager;

use Framework\Lib\Utils;
use Framework\Log\LogMark;
use Framework\DB\Handler\PlayerDBHandler;
use Framework\Logic\TimerLogic;
use Game\Constant\ConstTemplate\TemplateConst;
use Game\Constant\ConstTemplate\TemplateGiftPack;
use Game\Constant\ConstTemplate\TemplateInitPlayer;
use Game\Constant\ConstTemplate\TemplateItem;
use Game\Constant\ConstTemplate\TemplateTask;
use Game\Constant\DBTableDefine;
use Game\Constant\GameErrorCode;
use Game\Constant\TemplateDefine;
use Game\Data\TaskData;
use Game\Logic\ActiveLogic;
use Game\Logic\MailLogic;

class WeekTaskManager extends TaskMangerModelBase
{
    use MailLogic;
    use ActiveLogic;
    use TimerLogic;
    use PlayerDBHandler;

    private ?array $allWelfareWeekTaskDic = null;   //taskId->status

    //初始福利周任务 当天首次登录
    public function initWelfareWeekTaskOnRegisterOver()
    {
        $this->setIsRegister();
        $this->initWelfareWeekTask($this->getWelfareWeekTaskConfig());
    }
    //初始福利周任务 当天首次登录
    public function updateWelfareWeekTaskOnDayLogin()
    {
        $this->updateWelfareWeekTask($this->getWelfareWeekTaskConfig());
    }

    // 周任务创建
    private function initWelfareWeekTask(array $WelfareWeekTaskListConfig)
    {
        foreach ($WelfareWeekTaskListConfig as $taskId)
        {
            if (false == $this->createWeekTask($taskId)) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_DAILY_CREATE_ERROR,
                    "[WelfareWeekTaskManager] WelfareWeek task create error",
                    array(
                        "taskId" => $taskId
                    )
                );
                continue;
            }
        }
    }

    // 每天首次登录 更新周任务事件
    private function updateWelfareWeekTask(array $WelfareWeekTaskListConfig)
    {
        foreach ($WelfareWeekTaskListConfig as $taskId)
        {
            if (false == $this->updateWeekTask($taskId)) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_DAILY_CREATE_ERROR,
                    "[WelfareWeekTaskManager] WelfareWeek task event update error",
                    array(
                        "taskId" => $taskId
                    )
                );
                continue;
            }
        }
    }

    //获取全部周任务
    public function getWelfareWeekTask(): array
    {
        //检查是否需要初始化
        if (is_null($this->allWelfareWeekTaskDic)) {
            $this->getWelfareWeekTaskDic();
        }
        if (empty($this->allWelfareWeekTaskDic)) {
            //初始任务
            $this->initWelfareWeekTask($this->getWelfareWeekTaskConfig());
            $this->getWelfareWeekTaskDic();
        }

        $taskList = array();
        $completeTaskList = array();
        foreach ($this->allWelfareWeekTaskDic as $taskId => $status) {
            if ($status == TaskData::STATUS_OVER) {
                $completeTaskList[] = $taskId;
            } else {
                $taskData = $this->getTask($taskId);
                if (!is_null($taskData) && $taskData->taskId != 0) {
                    $taskList[] = $taskData;
                }
            }
        }
        return array($taskList, $completeTaskList);
    }

    //重置任务
    public function resetWelfareWeekTask()
    {
        //检查完成未领取与已领取任务
        $this->checkDoneNotGetTask();

        //获取表周任务
        $welfareWeekTaskListConfig = $this->getWelfareWeekTaskConfig();
        foreach ($welfareWeekTaskListConfig as $taskId)
        {
            //重置周任务
            if (false == $this->resetWeekTask($taskId)) {
                LogMark::getInstance()->markError(
                    GameErrorCode::TASK_RESET_ERROR,
                    "[WelfareWeekTaskManager] reset task fail",
                    array(
                        "taskId" => $taskId
                    )
                );
                continue;
            }
        }
    }

    /**
     * 查询完成未领取的任务
     * @return array [taskId,..]
     */
    public function getDoneAndOverTaskIds(): array
    {
        if (is_null($this->allWelfareWeekTaskDic)) {
            $this->getWelfareWeekTaskDic();
        }
        $doneTaskIds = array();
        foreach ($this->allWelfareWeekTaskDic as $taskId => $status) {
            if ($status == TaskData::STATUS_DONE || $status == TaskData::STATUS_OVER) {
                $doneTaskIds[] = $taskId;
            }
        }
        return $doneTaskIds;
    }

    //查询当前全部的周任务
    public function getWelfareWeekTaskDic()
    {
        if (is_null($this->allWelfareWeekTaskDic)) {
            $this->allWelfareWeekTaskDic = array();
        }
        $this->getTitleList(
            $this->getDBTable(),
            $this->playerId,
            $this->allWelfareWeekTaskDic
        );
    }

    //周任务 完成 与完成未领取的任务 同伙积分计算宝箱 发邮件
    public function checkDoneNotGetTask()
    {
        $taskIds = $this->getDoneAndOverTaskIds();
        if (empty($taskIds)) {
            return;
        }
        $score = 0;
        foreach($taskIds as $id) {
            $idScore = $this->getTitle(TemplateDefine::TYPE_TASK, $id)[TemplateTask::NumReward];
            $score += $idScore;
        }
        $itemID = $this->getGiftPackItemID($score);
        if(empty($itemID)) {
            return ;
        }

        // 发送邮件
        $mailTplId = $this->getTerm(TemplateDefine::TYPE_CONST,
            TemplateConst::Const_Week_Gift_MAIL_ID,
            TemplateConst::ConstNum);
        $this->createPlayerMail($mailTplId, Utils::getServerTimestamp(), [$itemID => 1]);
    }

    private function getGiftPackItemID(int $score): int {
        if($score === 0) {
            return 0;
        }
        $score1 = $this->getTerm(TemplateDefine::TYPE_CONST, TemplateConst::Const_Week_Gift_1,
            TemplateConst::ConstNum);
        if($score <= $score1) {
            return TemplateGiftPack::LEVEL_1;
        }
        $score2 = $this->getTerm(TemplateDefine::TYPE_CONST, TemplateConst::Const_Week_Gift_2,
            TemplateConst::ConstNum);
        if($score <= $score2) {
            return TemplateGiftPack::LEVEL_2;
        }
        $score3 = $this->getTerm(TemplateDefine::TYPE_CONST, TemplateConst::Const_Week_Gift_3,
            TemplateConst::ConstNum);
        if($score <= $score3) {
            return TemplateGiftPack::LEVEL_3;
        }
        return 0;
    }

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

    private function getWelfareWeekTaskConfig(): array
    {
        $configInitData = $this->getTitle(TemplateDefine::TYPE_INIT_PLAYER, TemplateInitPlayer::DEFAULT_ID);
        $welfareTaskListConfig = $configInitData[TemplateInitPlayer::WelfareWeekTaskList];
        if (empty($welfareTaskListConfig)) {
            LogMark::getInstance()->markError(
                GameErrorCode::TASK_WELFARE_WEEK_NOT_FOUND,
                "[WeekTaskManager] welfare week task not found"
            );
            return array();
        }
        return $welfareTaskListConfig;
    }
}
