local ShopData = class("ShopData", BaseData)

function ShopData:ctor()
	self.data.isDirty = false
end

function ShopData:initBase()
    self:initActChapterStoreData()
    self:initCrossDay()
end

function ShopData:clear()
    DataManager:unregisterCrossDayFunc("ShopData")
end

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

function ShopData:initCrossDay()
    DataManager:registerCrossDayFunc("ShopData", function()
        self:resetRunesGift()
        self:resetMallDaily()
        self:resetCommonDailyGemAdCount()
        self:resetCommonDailyCoinAdCount()
        self:setDirty()
    end)
end

-- 通用礼包部分 **********************************************************************************************

-- 初始化购买的礼包
function ShopData:initActGift(act)
    if EDITOR_MODE then
        Logger.logHighlight("初始化 initActGift")
        Logger.printTable(act)
    end
    act = act or {}
    local gifts = act.gifts or {}
    -- 转为map结构
    for _, gift in ipairs(gifts) do
        local giftType = gift.act_type
        local giftId = gift.id
        if not self.giftMap then
            self.giftMap = {}
        end
        if not self.giftMap[giftType] then
            self.giftMap[giftType] = {}
        end
        self.giftMap[giftType][giftId] = gift
    end
    self:initFirstRecharge()
    self:setDirty()
end

function ShopData:getActGiftConfig()
    return ConfigManager:getConfig("act_gift")
end

-- 获取通用礼包配置的所有该类型的礼包
function ShopData:getGiftsByType(giftType)
    local gifts = {}
    for id, data in pairs(self:getActGiftConfig()) do
        if data.type == giftType then
            gifts[id] = data
        end
    end

    return gifts
end

-- 已购买的礼包
function ShopData:getActGiftMap()
    return self.giftMap
end

function ShopData:getActGiftMapByType(actType)
    return self.giftMap and self.giftMap[actType]
end

function ShopData:getActGiftDetailData(actType, actId)
    if self.giftMap then
        if self.giftMap[actType] then
            return self.giftMap[actType][actId]
        end
    end
    return nil
end

-- 获得一个礼包的已购次数
function ShopData:getGiftBoughtNum(actType, actId)
    local data = self:getActGiftDetailData(actType, actId)
    if data then
        return data.buy_count
    end
    return 0
end

-- 重置一个礼包购买次数
function ShopData:resetGiftBoughtNum(actType, actId)
    local data = self:getActGiftDetailData(actType, actId)
    if data then
        data.buy_count = 0
    end
end

-- 获取通用礼包剩余可购买次数
function ShopData:getGiftRemainBuyNum(actId)
    local bought = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, actId)

    return self:getActGiftConfig()[actId].limit - bought
end

-- 礼包购买成功更新
function ShopData:updateGiftInfo(gift)
    local giftType = gift.act_type
    local giftId = gift.id

    if not self.giftMap then
        self.giftMap = {}
    end
    if not self.giftMap[giftType] then
        self.giftMap[giftType] = {}
    end
    self.giftMap[giftType][giftId] = gift

    if giftType == PayManager.PURCHARSE_TYPE.ACT_GIFT then
        local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[giftType]
        if cfgName then
            local cfg = ConfigManager:getConfig(cfgName)
            if cfg and cfg[giftId] then
                if cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.GROWTH_FUND then
                    DataManager.GrowthFundData:onBoughtFund(giftId)
                elseif cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.ARENA_GIFT then
                    DataManager.ArenaData:onBoughtGift(giftId)
                elseif cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT or cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT then
                    self:onGiftBuySuccess(cfg[giftId].type)
                elseif cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT or cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT then
                    DataManager.EquipData:onBuyGiftSuccess(giftId)
                elseif cfg[giftId].type == PayManager.PURCHARSE_ACT_TYPE.ACT_SUMMER then
                    DataManager.ActivityData:onBuyBountyGrade(giftId)
                end
            end
        end
    elseif giftType == PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW then
        self:onUpGiftBuySuccess()
    end

    self:setDirty()
end

-- 标记一个礼包需要弹出 在条件允许时会弹出
function ShopData:markPopUpGift(actType, actId)
    if not self.needPopUpGift then
        self.needPopUpGift = {}
    end
    if not self.needPopUpGift[actType] then
        self.needPopUpGift[actType] = {}
    end
    -- 如果已经有了 不作处理
    for _, id in ipairs(self.needPopUpGift[actType]) do
        if id == actId then
            return
        end
    end
    table.insert(self.needPopUpGift[actType], actId)
    table.sort(self.needPopUpGift[actType])
end

function ShopData:removePopUpGift(actType, actId)
    if self.needPopUpGift then
        if self.needPopUpGift[actType] then
            for index, id in ipairs(self.needPopUpGift[actType]) do
                if id == actId then
                    table.remove(self.needPopUpGift[actType], index)
                    break
                end
            end
        end
    end
end

-- 获取待处理弹出礼包结构 {type:[id1,id2,...]}
function ShopData:getPopUpGift()
    return self.needPopUpGift 
end

function ShopData:getPopUpGiftByType(actType)
    return self.needPopUpGift and self.needPopUpGift[actType]
end

function ShopData:checkHasPopUpGift(actType, actId)
    local gifts = self:getPopUpGiftByType(actType)
    if gifts and #gifts > 0 then
        for _, giftId in ipairs(gifts) do
            if (giftId == actId) then
                return true
            end
        end
    end
    return false
end

-- 获取下一个需要弹出的同类型礼包数据,特别的,如果是主界面部分则多个不同类型的也要考虑进去
function ShopData:getNextPopGiftData(actType, actId)
    if GConst.ShopConst.MAIN_UI_POP_TYPE[actType] then
        -- 优先找自己类型的,如果是act类则需要找同类型的
        local popUpGift = self:getPopUpGiftByType(actType)
        if popUpGift and #popUpGift > 0 then
            if actType == PayManager.PURCHARSE_TYPE.ACT_GIFT then
                for _, nextActId in ipairs(popUpGift) do
                    if self:getActGiftConfig()[nextActId].type == self:getActGiftConfig()[actId].type then
                        return actType, nextActId
                    end
                end
            else
                for _, nextActId in ipairs(popUpGift) do
                    return actType, nextActId
                end
            end
        end
        -- 按顺序找其他类型的
        if actType ~= PayManager.PURCHARSE_TYPE.ACT_GIFT then
            local popUpGift = self:getPopUpGiftByType(PayManager.PURCHARSE_TYPE.ACT_GIFT)
            if popUpGift and #popUpGift > 0 then
                for _, nextActId in ipairs(popUpGift) do
                    -- 新手礼包
                    if self:getActGiftConfig()[nextActId].type == PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT then
                        return PayManager.PURCHARSE_TYPE.ACT_GIFT, nextActId
                    end
                    -- 助力礼包
                    if self:getActGiftConfig()[nextActId].type == PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT then
                        return PayManager.PURCHARSE_TYPE.ACT_GIFT, nextActId
                    end
                end
            end
        end
        if actType ~= PayManager.PURCHARSE_TYPE.CHAPTER_GIFT then
            local popUpGift = self:getPopUpGiftByType(PayManager.PURCHARSE_TYPE.CHAPTER_GIFT)
            if popUpGift and #popUpGift > 0 then
                for _, nextActId in ipairs(popUpGift) do
                    return PayManager.PURCHARSE_TYPE.CHAPTER_GIFT, nextActId
                end
            end
        end
    else -- 直接返回同类型的即可
        local popUpGift = self:getPopUpGiftByType(actType)
        if popUpGift and #popUpGift > 0 then
            for _, nextActId in ipairs(popUpGift) do
                return actType, nextActId
            end
        end
    end
    return nil
end

-- 通用礼包结束 ----------------------------------------------------------------------------------------------

-- 每日特惠部分 **********************************************************************************************

function ShopData:getMallDailyConfig()
    return ConfigManager:getConfig("mall_daily")
end

-- 初始化每日特惠
function ShopData:initMallDaily(mallDaily)
    -- if EDITOR_MODE then
    --     Logger.logHighlight("初始化 initMallDaily")
    --     Logger.printTable(mallDaily)
    -- end

    mallDaily = mallDaily or {}
    self.mallDailyAdResetCount = mallDaily.ad_reset_Count or 0
    self.mallDailyDiamondResetCount = mallDaily.diamond_reset_Count or 0
    self.mallDailyGoods = mallDaily.goods or {} -- {id,good_index,bought}

    self:markMallDailyDirty(false)
    self:setDirty()
end

-- 购买成功后更新数据
function ShopData:updateMallDailyGoods(info)
    local goods = self:getMallDailyGoods()
    for _, data in ipairs(goods) do
        if data.id == info.id and data.good_index == info.good_index then
            data.bought = info.bought
            break
        end
    end

    self:setDirty()
end

-- 每日特惠跨天重置
function ShopData:resetMallDaily()
    self.mallDailyAdResetCount = 0
    self.mallDailyDiamondResetCount = 0
    self:markMallDailyDirty(true) -- 标记需要重新请求数据,在界面/下次打开界面时请求
end

function ShopData:getMallDailyDirty()
    return self.data.mallDailyDirty
end

function ShopData:markMallDailyDirty(isDirty)
    self.data.mallDailyDirty = isDirty
end

function ShopData:getMallDailyAdResetCount()
    return self.mallDailyAdResetCount
end

function ShopData:addMallDailyAdResetCount()
    self.mallDailyAdResetCount = self.mallDailyAdResetCount + 1
end

function ShopData:getMallDailyAdLeftCount()
    return 1 - self.mallDailyAdResetCount -- 目前无配置表
end

function ShopData:getMallDailyDiamondResetCount()
    return self.mallDailyDiamondResetCount
end

function ShopData:addMallDailyDiamondResetCount()
    self.mallDailyDiamondResetCount = self.mallDailyDiamondResetCount + 1
end

function ShopData:getMallDailyDiamondLeftCount()
    return 1 - self.mallDailyDiamondResetCount -- 目前无配置表
end

function ShopData:getMallDailyGoods()
    return self.mallDailyGoods
end

function ShopData:getMallDailyDiamondResetCost()
    return 30 -- 目前无配置表
end

-- 每日特惠 广告商品最大购买次数
function ShopData:getMallDailyFirstItemAdMaxCount()
    return 1 -- 目前无配置表
end

-- 每日特惠 常规商品最大购买次数
function ShopData:getMallDailyGoodsLimitCount()
    return 1 -- 目前无配置表
end

-- 每日特惠 是否开启
function ShopData:getMallDailyIsOpen()
    return ModuleManager:getIsOpen()
end

-- 根据商品id获取本日的随机商品数据
function ShopData:getMallDailyRewardAndCost(id)
    local cfg = self:getMallDailyConfig()
    local index
    for _, info in ipairs(self:getMallDailyGoods()) do
        if info.id == id then
            index = info.good_index
            break
        end
    end
    if index then
        return cfg[id].good[index], cfg[id].cost and cfg[id].cost[index]
    end
end

-- 每日特惠结束 ----------------------------------------------------------------------------------------------

-- 常驻金币礼包 **********************************************************************************************

function ShopData:getMallGoldConfig()
    return ConfigManager:getConfig("mall_gold")
end

function ShopData:initCommonDailyGoldGift(ad_count)
    -- if EDITOR_MODE then
    --     Logger.logHighlight("初始化 initCommonDailyGoldGift")
    --     Logger.printTable(ad_count)
    -- end

    ad_count = ad_count or {}
    self.commonDailyGoldBuyCount = ad_count[1] or 0 -- 已购的金币广告礼包次数

    self:setDirty()
end

function ShopData:getCommonDailyCoinAdBuyCount()
    return self.commonDailyGoldBuyCount
end

function ShopData:resetCommonDailyCoinAdCount()
    self.commonDailyGoldBuyCount = 0
end

-- 根据时间得到当前挂机金币奖励
function ShopData:getCommonDailyCoinNum(id)
    local cfgInfo = self:getMallGoldConfig()[id]
    if cfgInfo then
        return cfgInfo.gold.num
    end
end

function ShopData:getCommonDailyCoinDataById(id)
    local cfgInfo = self:getMallGoldConfig()[id]
    if cfgInfo then
        return cfgInfo.gold.num, cfgInfo.cost
    end
end

-- 常驻金币礼包结束 ----------------------------------------------------------------------------------------------

-- 常驻钻石礼包 **********************************************************************************************

function ShopData:resetCommonDailyGemAdCount()
    local gift = self:getActGiftDetailData(PayManager.PURCHARSE_TYPE.MALL_TREASURE, 1)
    if gift then
        gift.buy_count = 0
    end
end

function ShopData:getMallTreasureConfig()
    return ConfigManager:getConfig("mall_treasure") -- 审核模式会去读另一张表,在config_manager中处理的
end

-- 常驻钻石礼包结束 ----------------------------------------------------------------------------------------------

-- 章节礼包 act_chapter_store **********************************************************************************************
function ShopData:initActChapterStoreData()
    if not self.actChapterStoreMap then
        self.actChapterStoreId2ChapterIdMap = {}
        self.actChapterStoreChapterId2IdMap = {}
        local cfg = self:getActChapterStoreConfig()
        for id, cfgInfo in pairs(cfg) do
            self.actChapterStoreId2ChapterIdMap[id] = cfgInfo.chapter
            self.actChapterStoreChapterId2IdMap[cfgInfo.chapter] = id
        end
    end
end

function ShopData:getActChapterStoreConfig()
    return ConfigManager:getConfig("act_chapter_store")
end

-- 特定章节礼包是否已购买
function ShopData:getActChapterStoreHasBuy(chapterId)
    -- 章节礼包的id-chapterId相互对应map
    local actId = self.actChapterStoreChapterId2IdMap[chapterId]
    if self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.CHAPTER_GIFT, actId) == 0 then
        return false
    else
        return true
    end
end

-- 根据当前章节,获取可购买的id数组
function ShopData:getActChapterStoreCanBuyActIds()
    local list = {}
    local curChapterId = DataManager.ChapterData:getMaxChapterId()
    for id = 1, curChapterId do
        if not self:getActChapterStoreHasBuy(id) then
            table.insert(list, self.actChapterStoreChapterId2IdMap[id])
        end
    end
    return list
end

function ShopData:markPopUpGiftForActChapterStore(chapterId)
    local actId = self.actChapterStoreChapterId2IdMap[chapterId]
    self:markPopUpGift(PayManager.PURCHARSE_TYPE.CHAPTER_GIFT, actId)
end

-- 章节礼包结束 ----------------------------------------------------------------------------------------------

-- 新手礼包 **********************************************************************************************

function ShopData:getIsBeginnerGiftOpen()
    return ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.BEGINNER_GIFT, true)
end

function ShopData:markPopUpGiftForBeginnerGift()
    self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.BEGINNER_GIFT_ID)
end

function ShopData:getBeginnerGiftHasBuy()
    if self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.BEGINNER_GIFT_ID) == 0 then
        return false
    else
        return true
    end
end

-- 新手礼包侧边栏展示时间
function ShopData:getBeginnerGiftSideBarDurationTime()
    return 3 * 24 * 3600 -- 目前无配置表
end

-- 已开启 未购买 且 在开服的3天内
function ShopData:getBeginnerGiftShowSideBar()
    return self:getIsBeginnerGiftOpen() and not self:getBeginnerGiftHasBuy() and self:getBeginnerGiftSideBarRemainTime() > 0
end

-- 展示在侧边栏的剩余时间
function ShopData:getBeginnerGiftSideBarRemainTime()
    local createTime = DataManager.PlayerData:getCreateTime() // 1000
    local durationTime = self:getBeginnerGiftSideBarDurationTime()
    return createTime + durationTime - Time:getServerTime()
end

-- 新手礼包结束 ----------------------------------------------------------------------------------------------

-- 助力与金币礼包(act_gift) **********************************************************************************************

-- 初始化助力与金币礼包
function ShopData:initLevelUpGift(levelUpGift)
    -- if EDITOR_MODE then
    --     Logger.logHighlight("初始化 助力与金币礼包")
    --     Logger.printTable(levelUpGift)
    -- end

    levelUpGift = levelUpGift or {}
    self.levelUpGifts = levelUpGift.gifts or {} -- [{trigger_level,current_level_up_gift,trigger_at}]
    -- 金币礼包部分会一直保留
    self:initCoinGift(levelUpGift.gold_gift_id, levelUpGift.gold_gift_trigger_at)
    self.data.currentPayAmount = levelUpGift.current_pay_amount or 0 -- 已经计算过降档的付费数额

    self:setDirty()
end

function ShopData:initCoinGift(id, triggerTime)
    -- if EDITOR_MODE then
    --     Logger.logHighlight("初始化 金币礼包 -- id:%s  time:%s", id, triggerTime)
    -- end

    self.coinGiftId = id or 0 -- 金币礼包触发id
    self.coinGiftTriggerTime = triggerTime or 0 -- 金币礼包触发时间

    self:setDirty()
end

function ShopData:getPayAmount()
    return self.data.currentPayAmount
end

function ShopData:addPayment(rechargeId)
    local cfg = ConfigManager:getConfig("recharge")[rechargeId]
	self.data.currentPayAmount = self.data.currentPayAmount + cfg.price
end

function ShopData:getLevelUpGift()
    return self.levelUpGifts
end

function ShopData:onTriggerLevelUpGift(gift)
    table.insert(self.levelUpGifts, gift)
    -- 标记弹窗
    self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, gift.current_level_up_gift)
end

function ShopData:removeLevelUpGift(actId)
    for index, gift in ipairs(self.levelUpGifts) do
        if gift.current_level_up_gift == actId then
            table.remove(self.levelUpGifts, index)
            break
        end
    end
end

-- 获得可购买的助力礼包Ids
function ShopData:getLevelUpGiftActIds()
    local list = {}
    for index, gift in ipairs(self.levelUpGifts) do
        -- 剔除已购的助力礼包 这个礼包只会有一次
        if self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, gift.current_level_up_gift) == 0 then
            table.insert(list, gift.current_level_up_gift)
        end
    end


    table.sort(list)
    return list
end

-- 获得当前金币礼包的id
function ShopData:getCoinGiftId()
    return self.coinGiftId
end

-- 获得金币礼包的触发时间
function ShopData:getCoinGiftTriggerTime()
    return self.coinGiftTriggerTime // 1000
end

-- 获得当前可购买的金币礼包id,需要未购买且时间满足
function ShopData:getValidCoinGiftId()
    local actId = self:getCoinGiftId()
    if actId > 0 then
        local cfgInfo = self:getActGiftConfig()[actId]
        local triggerTime = self:getCoinGiftTriggerTime()
        local remainTime = triggerTime + (cfgInfo.limit_time or 0) * 3600 - Time:getServerTime()
        if remainTime > 0 then
            -- 查看最近一次购买时间
            local actGiftDetailData = self:getActGiftDetailData(PayManager.PURCHARSE_TYPE.ACT_GIFT, actId)
            if actGiftDetailData then
                local latestBuyTime = actGiftDetailData.latest_buy_at // 1000
                if latestBuyTime <= 0 then
                    return actId
                else
                    -- 目前规则上有CD 所以如果购买时间在CD范围内则该礼包无效
                    local limitTime = (self:getActGiftConfig()[actId].limit_time or 0) * 3600
                    if Time:getServerTime() > latestBuyTime + limitTime then
                        return actId
                    end
                end
            else -- 没有买过,这个肯定可以购买
                return actId
            end
        end
    end
    return nil
end

-- 获取金币礼包付款条件cfgInfo数组 从小到大
function ShopData:_getCoinGiftPayConditionList()
    if not self.coinGiftPayConditionList then
        self.coinGiftPayConditionList = {}
        for id, cfgInfo in pairs(self:getActGiftConfig()) do
            if cfgInfo.type == PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT then
                local tmpCfgInfo = clone(cfgInfo)
                tmpCfgInfo.id = id
                table.insert(self.coinGiftPayConditionList, tmpCfgInfo)
            end
        end
        table.sort(self.coinGiftPayConditionList, function (a, b)
            return a.pay_condition[1] < b.pay_condition[1] 
        end)
    end
    return self.coinGiftPayConditionList
end

-- 根据当前付费和金币礼包数据 判断并返回合法的金币礼包触发id
function ShopData:checkAndGetCoinGiftTriggerId()
    local triggerId 
    local canTrigger = true
    local curActId = self:getCoinGiftId()
    if curActId > 0 then
        local cfgInfo = self:getActGiftConfig()[curActId]
        local cdTime = (cfgInfo.cd or 0) * 3600
        local curTriggerTime = self:getCoinGiftTriggerTime()
        -- 是否还在已触发限时内
        if Time:getServerTime() < curTriggerTime + cdTime then
            canTrigger = false
        end
    end
    if canTrigger then
        -- 从表中找出符合付费金额的actId
        local payAmount = self:getPayAmount()
        local payConditionList = self:_getCoinGiftPayConditionList()
        for index, info in ipairs(payConditionList) do
            local p1 = info.pay_condition[1]
            local p2 = info.pay_condition[2]
            if p1 <= payAmount and payAmount < p2 then
                triggerId = info.id
                break
            end
        end
        -- 超出上限
        if not triggerId then
            local count = #payConditionList
            triggerId = payConditionList[count].id
        end
    end
    return triggerId
end

function ShopData:onTriggerCoinGift(actId)
    self:initCoinGift(actId, Time:getServerTime() * 1000)
    -- 标记弹窗
    self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, actId)
end

-- 助力礼包结束 ----------------------------------------------------------------------------------------------

-- 成长礼包 **********************************************************************************************

function ShopData:getActGrowUpGiftConfig()
    return ConfigManager:getConfig("act_growup_gift_new")
end

-- 初始化成长礼包
function ShopData:initGrowUpGift(growUpGift)
    if EDITOR_MODE then
        Logger.logHighlight("初始化成长礼包 growUpGift -- now_ts:%s", Time:getServerTime())
        Logger.printTable(growUpGift)
    end

    self.growUpGift = growUpGift
    if self:hasGrowUpGift() then
        self:markPopUpGiftForGrowUpGift(self.growUpGift.current_grow_up_id)
    end

    self:setDirty()
end

-- 当前是否有成长礼包
function ShopData:hasGrowUpGift()
    return self.growUpGift ~= nil and self:getGrowUpGiftRemainTime() > 0
end

-- 获取当前成长礼包
function ShopData:getGrowUpGift()
    if not self:hasGrowUpGift() then
        return nil
    end
    return self.growUpGift
end

-- 获取成长礼包倒计时
function ShopData:getGrowUpGiftRemainTime()
    if not self.growUpGift then
        return -1
    end
    return (self.growUpGift.trigger_end_at // 1000) - Time:getServerTime()
end

function ShopData:markPopUpGiftForGrowUpGift(actId)
    self:markPopUpGift(PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW, actId)
end

-- 成长礼包购买成功
function ShopData:onUpGiftBuySuccess()
    self.growUpGift.trigger_end_at = -1
    self:setDirty()
end

-- 成长礼包结束 ----------------------------------------------------------------------------------------------

-- 首充(作废) **********************************************************************************************

function ShopData:getIsFirstRechargeOpen()
    return false -- ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.FIRST_RECHARGE, true)
end

-- 用于标记是否弹窗 要求等级不低于2 未领取该奖励
function ShopData:initFirstRecharge()
    -- local lv = DataManager.PlayerData:getLv()
    -- if lv > 1 and not self:getHasGotFirstRechargeReward() then
    --     self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.FIRST_RECHARGE_ID)
    -- end
end

-- 是否有首充奖励 有支付且未领取
function ShopData:getHasFirstRechargeReward()
    -- local pay = DataManager.PlayerData:getTotalPayAmount()
    -- if pay > 0 and not self:getHasGotFirstRechargeReward() then
    --     return true
    -- else
    --     return false
    -- end
    return false
end

-- 是否已领取首充奖励
function ShopData:getHasGotFirstRechargeReward()
    -- 通用act礼包中是否有已购
    -- local boughtNum = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.FIRST_RECHARGE_ID)
    -- return boughtNum > 0
    return true
end

-- 侧边栏是否展示 要求功能开启 未领取该奖励
function ShopData:getShowFirstRechargeSideBar()
    -- if not self:getIsFirstRechargeOpen() then
    --     return false
    -- end
    -- if not self:getHasGotFirstRechargeReward() then
    --     return true
    -- else
    --     return false
    -- end
    return false
end

-- 侧边栏红点
function ShopData:showFirstRechargeRp()
    -- if not self:getIsFirstRechargeOpen() then
    --     return false
    -- end

    -- return self:getHasFirstRechargeReward()
    return false
end

-- 首充结束 ----------------------------------------------------------------------------------------------

-- 入门礼包 ----------------------------------------------------------------------------------------------

function ShopData:initIntroductGift(introductGift)
    introductGift = introductGift or {}
    self.introductGift = introductGift or {}
    self.introductGiftTriggerTime = self.introductGift.trigger_at or 0

    self:checkPopIntroductGift()
end

 -- 如果可购买则标记可弹窗
function ShopData:checkPopIntroductGift()
    if (self:getIntroductGiftRemainTime() > 0 and self:getIntroductGiftRemainBuyCount() > 0) then
        self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.INTRODUCT_GIFT_ID)
    end
end

function ShopData:getIntroductGiftTriggerTime()
    return self.introductGiftTriggerTime // 1000
end

function ShopData:setIntroductGiftTriggerTime(time)
    self.introductGiftTriggerTime = time
end

-- 入门礼包剩余时间
function ShopData:getIntroductGiftRemainTime()
    local cfgInfo = self:getActGiftConfig()[GConst.ShopConst.INTRODUCT_GIFT_ID]
    local triggerTime = self:getIntroductGiftTriggerTime()
    local remainTime = triggerTime + (cfgInfo.limit_time or 0) * 3600 - Time:getServerTime()
    return remainTime
end

-- 入门礼包剩余可购次数
function ShopData:getIntroductGiftRemainBuyCount()
    local cfgInfo = self:getActGiftConfig()[GConst.ShopConst.INTRODUCT_GIFT_ID]
    local buyCount = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.INTRODUCT_GIFT_ID)
    return (cfgInfo.limit or 1) - buyCount
end

-- 触发入门礼包(如果已经触发则不会更新)
function ShopData:onTriggerIntroductGift()
    if self:getIntroductGiftTriggerTime() <= 0 then
        self:initIntroductGift({trigger_at = Time:getServerTime() * 1000})
        -- 标记弹窗
        self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, GConst.ShopConst.INTRODUCT_GIFT_ID)
    end
end

-- 侧边栏是否展示(时间次数均满足)
function ShopData:getIntroductGiftShowSideBar()
    return self:getIntroductGiftRemainBuyCount() > 0 and self:getIntroductGiftRemainTime() > 0
end

-- 入门礼包结束 --------------------------------------------------------------------------------------------

-- 武器礼包 --------------------------------------------------------------------------------------------

-- 初始化礼包(礼包类型1下的礼包，可以直接复用这里的方法)
function ShopData:initGift(giftType, gift, isInit)
    if giftType == nil or gift == nil then
        return
    end
    if EDITOR_MODE then
        Logger.logHighlight("初始化礼包[%s] -- now_ts:%s", giftType, Time:getServerTime())
        Logger.printTable(gift)
    end
    if not self.gifts then
        self.gifts = {}
    end

    local giftStruct = {}
    if giftType == PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT or giftType == PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT then
        giftStruct.id = gift.gift_id
        giftStruct.triggerTime = gift.trigger_at
        giftStruct.expireTime = gift.expire_at
        giftStruct.cdEndTime = gift.cd_end_at
    end

    local tempId = self.gifts[giftType] and self.gifts[giftType].id or 0
    local tempTrigerTime = self.gifts[giftType] and self.gifts[giftType].triggerTime or 0
    self.gifts[giftType] = giftStruct

    if not isInit and self:hasGift(giftType) then
        if tempId == self.gifts[giftType].id and tempTrigerTime == self.gifts[giftType].triggerTime then
            if EDITOR_MODE then
                Logger.logHighlight("重复礼包数据，不处理弹窗:" .. tempId)
            end
        else
            self:markPopUpGift(PayManager.PURCHARSE_TYPE.ACT_GIFT, self.gifts[giftType].id)
        end
    end
    self:setDirty()
end

-- 当前是否有礼包
function ShopData:hasGift(giftType)
    if GFunc.isShenhe() then
        return false
    end
    return self.gifts ~= nil and self:getGiftRemainTime(giftType) > 0
end

-- 获取当前礼包
function ShopData:getGift(giftType)
    if not self:hasGift(giftType) then
        return nil
    end
    return self.gifts[giftType]
end

-- 获取礼包倒计时
function ShopData:getGiftRemainTime(giftType)
    if not self.gifts or not self.gifts[giftType] then
        return -1
    end
    return (self.gifts[giftType].expireTime // 1000) - Time:getServerTime()
end

-- 检查是否弹出ACT_GIFT类型的礼包
function ShopData:checkPopGift(actGiftType)
    local gifts = self:getPopUpGiftByType(PayManager.PURCHARSE_TYPE.ACT_GIFT)
    if gifts and #gifts > 0 then
        for _, actId in ipairs(gifts) do
            local cfgInfo = self:getActGiftConfig()[actId]
            if cfgInfo and cfgInfo.type == actGiftType then
                ModuleManager.ShopManager:triggerGiftPopUI(PayManager.PURCHARSE_TYPE.ACT_GIFT, actId, BIReport.PAY_UI_SHOW_TYPE.TRIGGER_POP)
            end
        end
    end
end

-- 礼包购买成功
function ShopData:onGiftBuySuccess(giftType)
    self.gifts[giftType].expireTime = -1
    self:setDirty()
end

-- 武器礼包结束 -----------------------------------------------------------------------------------------

-- 底部栏是否有红点
function ShopData:getRp()
    if not ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.MALL, true) then
        return false
    end
    if GFunc.isShenhe() then
        return false
    end
    local isHotOpen = ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.MALL_DAILY, true)
    -- 主要商品 每日特惠广告道具
    local hotAdGoods = self:getMallDailyGoods() and self:getMallDailyGoods()[1]
    local hotAdGoodsBuyCount = hotAdGoods and hotAdGoods.bought or 0
    local hotAdGoodsRp = self:getMallDailyFirstItemAdMaxCount() - hotAdGoodsBuyCount > 0
    -- 主要商品 每日特惠刷新
    local hotRefreshRp = self:getMallDailyAdLeftCount() > 0
    -- 主要商品 钻石广告道具
    local gemAdId = 1 -- 约定首位为免费栏位
    local cfgInfo = self:getMallTreasureConfig()[gemAdId] 
    local gemAdMaxTimes = cfgInfo and cfgInfo.daily or 0
    local gemAdRp =  gemAdMaxTimes - DataManager.ShopData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.MALL_TREASURE, gemAdId) > 0
    -- 主要商品 金币广告道具
    local coinAdId = 1 -- 约定首位为免费栏位
    local cfgInfo = self:getMallGoldConfig()[coinAdId] 
    local coinAdMaxTimes = cfgInfo and cfgInfo.daily or 0
    local coinAdRp =  coinAdMaxTimes - DataManager.ShopData:getCommonDailyCoinAdBuyCount() > 0

    return (isHotOpen and (hotAdGoodsRp or hotRefreshRp)) or gemAdRp or coinAdRp or self:getShopDiscountRedPoint()
end

-- 商店界面特惠页签是否有红点
function ShopData:checkShopDiscountRedPoint()
    local discountRedPointTime = LocalData:getShopDiscountRedPointTime()
    local today = Time:getBeginningOfServerToday()
    if discountRedPointTime == today then
        self.shopDiscountRedPoint = false
        return
    end
    local actIds = self:getActChapterStoreCanBuyActIds()
    if actIds and #actIds > 0 then
        self.shopDiscountRedPoint = true
        return
    end
    if not self:getBeginnerGiftHasBuy() then
        self.shopDiscountRedPoint = true
        return
    end
    actIds = self:getLevelUpGiftActIds()
    if actIds and #actIds > 0 then
        self.shopDiscountRedPoint = true
        return
    end
    if self:hasGrowUpGift() then
        self.shopDiscountRedPoint = true
        return
    end
    local id = self:getValidCoinGiftId()
    if id and id > 0 then
        self.shopDiscountRedPoint = true
        return
    end
    self.shopDiscountRedPoint = false
    LocalData:setShopDiscountRedPointTime(today)
end

function ShopData:getShopDiscountRedPoint()
    return self.shopDiscountRedPoint
end

function ShopData:markShopDiscountRedPoint()
    if not self.shopDiscountRedPoint then
        return
    end
    self.shopDiscountRedPoint = false
    local today = Time:getBeginningOfServerToday()
    LocalData:setShopDiscountRedPointTime(today)
end

function ShopData:getEntranceDiscountRedPoint()
    return not self.isClickedDiscount
end

function ShopData:markEntranceDiscountRedPoint()
    self.isClickedDiscount = true
end

function ShopData:checkLoginPopInfo()
    -- 初始化礼包弹出逻辑
    local actPopUpGifts = self:getPopUpGiftByType(PayManager.PURCHARSE_TYPE.ACT_GIFT)
    if not actPopUpGifts or #actPopUpGifts <= 0 then
        self:markPopLastChapterActGift()
    end
end

function ShopData:markPopLastChapterActGift()
    local chapterPopUpGifts = self:getPopUpGiftByType(PayManager.PURCHARSE_TYPE.CHAPTER_GIFT)
    if not chapterPopUpGifts or #chapterPopUpGifts <= 0 then
        local list = self:getActChapterStoreCanBuyActIds()
        if list and list[1] then
            self:markPopUpGift(PayManager.PURCHARSE_TYPE.CHAPTER_GIFT, list[#list])
        end
    end
end

-- 重置符文每日礼包次数
function ShopData:resetRunesGift()
    for index, id in ipairs(GConst.RunesConst.GIFT_IDS) do
        self:resetGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id)
    end
end

-- 重置波次锦标赛礼包次数
function ShopData:resetTournWaveGift()
    local ids = GConst.TournWaveConst.GIFT_IDS
    for index, id in ipairs(ids) do
        self:resetGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id)
    end
end

-- 重置竞技场锦标赛礼包次数
function ShopData:resetTournArenaGift()
    local ids = GConst.TournArenaConst.GIFT_IDS
    for index, id in ipairs(ids) do
        self:resetGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id)
    end
end

return ShopData