local FullMoonData = class("FullMoonData", BaseData)

function FullMoonData:ctor()
    self.data.isDirty = false

    self.taskFinished = 0
    self.curHeroGiftChoose = nil
    self.taskStatus = GConst.EMPTY_TABLE
    self.taskProgReward = GConst.EMPTY_TABLE
    self.chapterSkinClaimed = GConst.EMPTY_TABLE
end

function FullMoonData:clear()
    DataManager:unregisterCrossDayFunc("FullMoonData")
    DataManager:unregisterTryOpenFunc("FullMoonData")
end

-- 设置活动数据
function FullMoonData:setActStatus(data)
    data = data or GConst.EMPTY_TABLE

    self.startTime = GFunc.formatTimeStep(data.start_at)
    self.endTime = GFunc.formatTimeStep(data.end_at)

    if EDITOR_MODE then
        Logger.logHighlight("圆月活动开启时间：")
        Logger.printTable(data)
    end

    if not self:isOpen() then
        -- 活动开启
        DataManager:registerTryOpenFunc("FullMoonData", function()
            if not self:isOpen() then
                return
            end
            if not self:isOpenTime() then
                return
            end

            DataManager:unregisterTryOpenFunc("FullMoonData")
            ModuleManager.FullMoonManager:reqActData()
        end)
    end
end

-- 获取活动数据成功
function FullMoonData:onGetActData(data)
    data = data or GConst.EMPTY_TABLE

    self.taskFinished = data.finished or 0-- 任务奖励总计
    self.taskStatus = data.tasks or GConst.EMPTY_TABLE
    self.taskProgReward = data.claimed or GConst.EMPTY_TABLE
    self.curHeroGiftChoose = data.custom_gift_choose
    self.chapterSkinClaimed = data.chapter_skin_claimed or GConst.EMPTY_TABLE

    if self:isOpenTime() then
        -- 注册任务进度监听
        for id, data in ipairs(ConfigManager:getConfig("activity_full_moon_quest")) do
            ModuleManager.TaskManager:registerTask("FullMoonData", data.type, function(count)
                self:addTaskProgress(data.type, count)
            end)
        end
    end

    if EDITOR_MODE then
        Logger.logHighlight("圆月活动数据：")
        Logger.printTable(data)
    end
    -- 跨天
    DataManager:registerCrossDayFunc("FullMoonData", function()
        if not self:isOpen() then
            return
        end
        if not self:isOpenTime() then
            return
        end

        self:setInReset(true)
        self:setDirty()
    end)

    self.isInitedData = true
    self:setDirty()
end

function FullMoonData:setDirty()
    self.data.isDirty = not self.data.isDirty 
end

function FullMoonData:isOpen()
    if GFunc.isShenhe() then
        return false
    end
    if not ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.ACTIVITY, true) then
        return false
    end
    return true
end

-- 是否在活动配置时间内
function FullMoonData:isOpenTime()
    if self.startTime == nil or self.startTime <= 0 then
        return false
    end
    if self.endTime == nil or self.endTime <= 0 then
        return false
    end
    return Time:getServerTime() >= self.startTime and Time:getServerTime() <= self.endTime
end

-- 获取活动开启剩余时间（秒）
function FullMoonData:getStartRemainTime()
    if self.startTime == nil or self.startTime <= 0 then
        return 0
    end
    return self.startTime - Time:getServerTime()
end

-- 获取活动结束剩余时间（秒）
function FullMoonData:getEndRemainTime()
    if self.endTime == nil or self.endTime <= 0 then
        return 0
    end
    return self.endTime - Time:getServerTime()
end

-- 获取需要展示的活动界面
function FullMoonData:getNeedShowActPanel()
    -- 引导其间不处理
    if DataManager.TutorialData:getIsHaveTutorial() then
        return nil
    end
    if not self:isOpen() then
        return nil
    end
    if not self:isOpenTime() then
        return nil
    end
    if not self.isInitedData then
        return nil
    end
    if self.isWatchedActPanel then
        return nil
    end

    if not self:isAllBoughtSkinGifts() then
        return GConst.FullMoonConst.PANEL_TYPE.SKIN
    end

    if not self:isAllBoughtNewHeroGifts() then
        return GConst.FullMoonConst.PANEL_TYPE.NEW_HERO
    end

    if not self:isAllBoughtChooseHeroGifts() then
        return GConst.FullMoonConst.PANEL_TYPE.CHOOSE_HERO
    end

    if not self:isTaskAllRewardReceived() then
        return GConst.FullMoonConst.PANEL_TYPE.TASK
    end

    return nil
end

-- 展示活动界面
function FullMoonData:showActPanel()
    self.isWatchedActPanel = true
end

function FullMoonData:setInReset(isInReset)
	self.isInReset = isInReset
end

function FullMoonData:getIsInReset()
	return self.isInReset
end

-- 是否有入口红点
function FullMoonData:hasEntryRedPoint()
    return self:hasTaskRedPoint()
end

-- 任务--------------------------------------------------------------------------------------------------

-- 是否奖励全领完
function FullMoonData:isTaskAllRewardReceived()
    for index, id in ipairs(self:getTaskListSort()) do
        if not self:isReceivedTaskReward(id) then
            return false
        end
    end

    return true
end

-- 是否有任务红点
function FullMoonData:hasTaskRedPoint()
    for index, id in ipairs(table.keys(ConfigManager:getConfig("activity_full_moon_quest"))) do
        if self:canGetTaskReward(id) and not self:isReceivedTaskReward(id) then
            return true
        end
    end

    for index, id in ipairs(table.keys(ConfigManager:getConfig("activity_full_moon_reward"))) do
        if self:isReachTaskProgressReward(id) and not self:isReceivedTaskProgressReward(id) then
            return true
        end
    end

    return false
end

-- 获取任务完成个数
function FullMoonData:getTaskFinishNum()
    return self.taskFinished
end

-- 获取任务完成总目标个数
function FullMoonData:getTaskTotalNum()
    local max
    for id, value in pairs(ConfigManager:getConfig("activity_full_moon_reward")) do
        if max == nil or max < value.quest then
            max = value.quest
        end
    end

    return max
end

-- 获取下标对应的任务进度奖励id
function FullMoonData:getTaskProgressRewardIdByIndex(index)
    for id, value in pairs(ConfigManager:getConfig("activity_full_moon_reward")) do
        if index == 1 then
            return id
        end
        index = index - 1
    end
end

-- 获取任务进度奖励总个数
function FullMoonData:getTaskProgressRewardTotalNum()
    return table.nums(ConfigManager:getConfig("activity_full_moon_reward"))
end

-- 获取任务进度奖励
function FullMoonData:getTaskProgressReward(id)
    return ConfigManager:getConfig("activity_full_moon_reward")[id].reward
end

-- 获取任务进度目标
function FullMoonData:getTaskProgressTarget(id)
    return ConfigManager:getConfig("activity_full_moon_reward")[id].quest
end

-- 任务进度奖励是否满足领取条件
function FullMoonData:isReachTaskProgressReward(id)
    return self:getTaskFinishNum() >= self:getTaskProgressTarget(id)
end

-- 任务进度奖励是否已领取
function FullMoonData:isReceivedTaskProgressReward(id)
    return self.taskProgReward[id]
end

-- 获取当前定位的任务进度奖励index
function FullMoonData:getCurTaskProgressRewardIndex()
    local index = 0

    for id, data in pairs(ConfigManager:getConfig("activity_full_moon_reward")) do
        index = index + 1
        if self:isReachTaskProgressReward(id) and not self:isReceivedTaskProgressReward(id) then
            return index
        end
    end

    index = 0
    local curStage = self:getTaskProgressRewardId()
    for id, data in pairs(ConfigManager:getConfig("activity_full_moon_reward")) do
        index = index + 1
        if curStage == id then
            return index
        end
    end

    return nil
end

-- 获取任务奖励阶段id
function FullMoonData:getTaskProgressRewardId()
    local finish = self:getTaskFinishNum()
    local curId
    for id, data in pairs(ConfigManager:getConfig("activity_full_moon_reward")) do
        if finish >= data.quest then
            curId = id
        else
            break
        end
        finish = finish - data.quest
    end

    return curId
end

-- 获取今日任务列表
function FullMoonData:getTaskListSort()
    local ids = {}

    for id, data in pairs(self.taskStatus) do
        local sort = id + 10000000
        if self:canGetTaskReward(id) and not self:isReceivedTaskReward(id) then
            sort = sort - 100000
        end
        if self:isReceivedTaskReward(id) then
            sort = sort + 100000
        end
        table.insert(ids, {id = id, sort = sort})
    end
    table.sort(ids, function (a, b)
        return a.sort < b.sort
    end)

    -- Logger.logHighlight("任务列表排序:")
    -- Logger.printTable(ids)
    return ids
end

-- 获取任务类型
function FullMoonData:getTaskType(id)
    return ConfigManager:getConfig("activity_full_moon_quest")[id].type
end

-- 获取任务目标
function FullMoonData:getTaskTarget(id)
    return ConfigManager:getConfig("activity_full_moon_quest")[id].number
end

-- 获取任务奖励
function FullMoonData:getTaskReward(id)
    return ConfigManager:getConfig("activity_full_moon_quest")[id].reward
end

-- 获取任务进度
function FullMoonData:getTaskProgress(id)
    if self:getTaskType(id) == GConst.TaskConst.TASK_TYPE.X_PLAYER_LV_REACH then
        -- 玩家等级实时处理
        return DataManager.PlayerData:getLv()
    end

    return self.taskStatus[id] and self.taskStatus[id].progress or 0
end

-- 任务是否完成
function FullMoonData:canGetTaskReward(id)
    return self:getTaskProgress(id) >= self:getTaskTarget(id)
end

-- 任务奖励是否已领取
function FullMoonData:isReceivedTaskReward(id)
    if self.taskStatus[id] == nil then
        return false
    end

    return self.taskStatus[id].claimed
end

-- 添加任务进度
function FullMoonData:addTaskProgress(taskType, count)
    -- Logger.logHighlight("任务进度改变："..tostring(taskType)..","..tostring(count))
    if not self:isOpen() then
        return
    end
    if not self:isOpenTime() then
        return
    end

    -- 检查圆月活动任务更新
    if self:getIsInReset() then
        ModuleManager.FullMoonManager:reqActData()
    end

    for id, data in pairs(self.taskStatus) do
        local tt = self:getTaskType(id)
        if tt == taskType then
            if self.taskStatus[id] == nil then
                self.taskStatus[id] = {}
                self.taskStatus[id].progress = 0
            end
            self.taskStatus[id].progress = self.taskStatus[id].progress + count
        end
    end

	self:setDirty()
end

-- 领取任务奖励成功
function FullMoonData:onReceivedTaskReward(id, finished)
    self.taskFinished = finished
    if self.taskStatus[id] then
        self.taskStatus[id].claimed = true
    end
    self:setDirty()
end

-- 领取任务进度奖励成功
function FullMoonData:onReceivedTaskProgressReward(id)
    self.taskProgReward[id] = true
    self:setDirty()
end

-- 英雄自选连购礼包--------------------------------------------------------------------------------------------------

-- 所有自选英雄礼包都被购买
function FullMoonData:isAllBoughtChooseHeroGifts()
    for index, id in ipairs(self:getChooseHeroGiftIds()) do
        if not self:isGiftBought(id) then
            return false
        end
    end
    return true
end

-- 获取英雄自选礼包ids
function FullMoonData:getChooseHeroGiftIds()
    if self.chooseHeroIds == nil then
        self.chooseHeroIds = table.keys(DataManager.ShopData:getGiftsByType(PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_HERO_GIFT))
        table.sort(self.chooseHeroIds)
    end

    return self.chooseHeroIds
end

-- 当前所处的英雄礼包
function FullMoonData:getCurChooseHeroGiftId()
    for index, id in pairs(self:getChooseHeroGiftIds()) do
        if not self:isGiftBought(id) then
            return id
        end
    end

    return self:getChooseHeroGiftIds()[#self:getChooseHeroGiftIds()]
end

-- 获取当前组礼包ids
function FullMoonData:getCurStepChooseHeroGiftIds()
    local ids = self:getChooseHeroGiftIds()
    local curId = self:getCurChooseHeroGiftId()
    local result = {}
    local step = 1

    local idx = 0
    for index, value in ipairs(GConst.FullMoonConst.HERO_GIFT_SHOW_STEP) do
        result[index] = {}
        for i = 1, value do
            idx = idx + 1
            if curId == ids[idx] then
                step = index
            end
            if ids[idx] then
                table.insert(result[index], ids[idx])
            end
        end
    end

    return result[step]
end

-- 当前自选英雄的下标
function FullMoonData:getChooseHeroIndex()
    if not self.curHeroGiftChoose or self.curHeroGiftChoose <= 0 then
        return nil
    end
    return self.curHeroGiftChoose
end

-- 获取固定奖励
function FullMoonData:getFixedRewards(id)
    return DataManager.ShopData:getActGiftConfig()[id].reward
end

-- 获取自选奖励
function FullMoonData:getChooseRewards(id, isAll)
    local rewards = {}

    if not isAll then
        for index, reward in ipairs(DataManager.ShopData:getActGiftConfig()[id].choose_reward) do
            local info = ConfigManager:getConfig("item")[reward.id]
            if info.type == GConst.ItemConst.ITEM_TYPE.HERO_FRAGMENT then
                if DataManager.HeroData:getHeroIsActive(info.parameter) then
                    table.insert(rewards, reward)
                end
            end
        end
    else
        rewards = DataManager.ShopData:getActGiftConfig()[id].choose_reward
    end

    return rewards
end

-- 获取可选择的自选奖励下标对应的全部自选奖励下标
function FullMoonData:getChooseRewardsIndexByCanChooseIndex(index)
    local selectReward = self:getChooseRewards(self:getCurChooseHeroGiftId())[index]
    local result = {}
    for idx, reward in ipairs(self:getChooseRewards(self:getCurChooseHeroGiftId(), true)) do
        if reward == selectReward then
            return idx
        end
    end

    Logger.logError("未找到"..index)
    return result
end

-- 自选成功
function FullMoonData:onChooseHeroSuccess(index)
    self.curHeroGiftChoose = index
    self:setDirty()
end

-- 新英雄连购礼包--------------------------------------------------------------------------------------------------

-- 所有新英雄礼包都被购买
function FullMoonData:isAllBoughtNewHeroGifts()
    for index, id in ipairs(self:getNewHeroGiftIds()) do
        if not self:isGiftBought(id) then
            return false
        end
    end
    return true
end

-- 获取新英雄礼包ids
function FullMoonData:getNewHeroGiftIds()
    if self.newHeroIds == nil then
        self.newHeroIds = table.keys(DataManager.ShopData:getGiftsByType(PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_NEW_HERO_GIFT))
        table.sort(self.newHeroIds)
    end

    return self.newHeroIds
end

-- 当前所处的新英雄礼包
function FullMoonData:getCurNewHeroGiftId()
    for index, id in pairs(self:getNewHeroGiftIds()) do
        if DataManager.ShopData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id) == 0 then
            return id
        end
    end

    return self:getNewHeroGiftIds()[#self:getNewHeroGiftIds()]
end

-- 获取当前组礼包ids
function FullMoonData:getCurStepNewHeroGiftIds()
    local ids = self:getNewHeroGiftIds()
    local curId = self:getCurNewHeroGiftId()
    local result = {}
    local step = 1

    local idx = 0
    for index, value in ipairs(GConst.FullMoonConst.HERO_GIFT_SHOW_STEP) do
        result[index] = {}
        for i = 1, value do
            idx = idx + 1
            if curId == ids[idx] then
                step = index
            end
            if ids[idx] then
                table.insert(result[index], ids[idx])
            end
        end
    end

    return result[step]
end

-- 皮肤礼包--------------------------------------------------------------------------------------------------

-- 所有皮肤礼包都被购买
function FullMoonData:isAllBoughtSkinGifts()
    for index, id in ipairs(table.keys(DataManager.ShopData:getGiftsByType(PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_SKIN_GIFT))) do
        if not self:isGiftBought(id) then
            return false
        end
    end
    return true
end

-- 皮肤礼包剩余购买次数
function FullMoonData:getSkinGiftRemainBuyNum(id)
    return DataManager.ShopData:getGiftRemainBuyNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id)
end

-- 获取皮肤挑战首通奖励
function FullMoonData:getSkinFirstChallengeReward(id)
    return ConfigManager:getConfig("chapter_new_skin_fight")[id].reward[1]
end

-- 皮肤挑战首通奖励是否已领取
function FullMoonData:isReceivedSkinFirstChallengeReward(id)
    return self.chapterSkinClaimed[id]
end

-- 设置当前皮肤挑战关卡id
function FullMoonData:setCurSkinChallengeId(id)
    self.curSkinChallengeId = id
end

-- 获取当前皮肤挑战关卡id
function FullMoonData:getCurSkinChallengeId()
    return self.curSkinChallengeId
end

-- 皮肤挑战奖励领取成功
function FullMoonData:onReceivedSkinChallengeReward(id)
    self.chapterSkinClaimed[id] = true
    self:setDirty()
end

-- 礼包是否已购买
function FullMoonData:isGiftBought(id)
    return DataManager.ShopData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id) > 0
end

return FullMoonData