local GiftPopData = class("GiftPopData", BaseData)

local ActGiftCfg = ConfigManager:getConfig("act_gift")

local SPECIAL_TYPE = "special"

function GiftPopData:getGiftConfig(id)
	return ActGiftCfg[id]
end

function GiftPopData:ctor()
	self:clear()
end

function GiftPopData:clear()
	self.popGiftMap = {}
	self.triggerTimeMap = {}
	self.notBuyCountMap = {} -- 距离上次购买后，触发了但是未购买的总次数，用于更新CD <giftType, notBuyCount>
	self.typeIds = {}
	self.data.isDirty = false
	self.carrierUnlockGiftPopFlag = false
end

function GiftPopData:getBiReportByGiftType(giftId)
	return PayManager:getItemGetType(PayManager.PURCHARSE_TYPE.ACT_GIFT, giftId)
end

function GiftPopData:initPopCfg()
	if self.typeIds and table.nums(self.typeIds) > 0 then
		return
	end
	local popType = {}
	for type, _ in pairs(GConst.GiftPopConst.BI_POP_GIFT_TYPE) do
		popType[type] = true
	end

	self.typeIds = {}
	for id, info in pairs(ActGiftCfg) do
		local giftType = info.type
		if popType[giftType] then
			self.typeIds[giftType] = self.typeIds[giftType] or {}

			local parameter = info.parameter or SPECIAL_TYPE
			self.typeIds[giftType][parameter] = self.typeIds[giftType][parameter] or {}

			table.insert(self.typeIds[giftType][parameter], id)
		end
	end
end

function GiftPopData:initData(data)
	self:initPopCfg()

	data = data or {}
	self.popGiftMap = {}
	self.triggerTimeMap = {}
	self.notBuyCountMap = {}
	self:refreshPopGift(data.trigger_gifts, data.not_buy_count)
	if EDITOR_MODE then
		Logger.logHighlight("---------------------------GiftPopData:initData---------------------------")
		Logger.printTable(data)
		Logger.printTable(self.popGiftMap)
		Logger.printTable(self.triggerTimeMap)
		Logger.printTable(self.notBuyCountMap)
	end
end

function GiftPopData:refreshPopGift(data, notBuyCountMap)
	if not data then
		return
	end

	self.triggerTimeMap = data or {}
	self.notBuyCountMap = notBuyCountMap or {}

	local nowTime = Time:getServerTime()
	for id, triggerTime in pairs(data) do
		local config = ActGiftCfg[id]
		if config then
			local giftType = config.type
			local endTime = triggerTime + config.limit_time * 3600
			local buyCount = DataManager.PaymentData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, id)
			local notBuyCount = self:getPopGiftNotBuyCount(id)
			local cooldown
			if config.cd then
				if config.max_cd_times then
					cooldown = triggerTime + (config.cd or 0) * 3600 * math.max(1, math.min(notBuyCount + 1, config.max_cd_times))
				else
					cooldown = triggerTime + (config.cd or 0) * 3600
				end
			else
				cooldown = triggerTime
			end

			local realEndTime = endTime
			if buyCount and buyCount > 0 then -- 已购买
				if not config.cd then
					cooldown = nowTime
				end
				endTime = nowTime
			end

			local info = {
				beginTime = triggerTime,
				endTime = endTime,
				realEndTime = realEndTime,
				cooldown = cooldown,
				type = giftType,
				id = id,
			}

			if EDITOR_MODE then
				Logger.logHighlight("初始化礼包冷却 -- giftId:%s  notBuyCount:%s  triggerTime:%s  cooldown:%s", id, notBuyCount, Time:formatTimeYMDHMS2(triggerTime), Time:formatTimeYMDHMS2(cooldown))
			end

			self.popGiftMap[giftType] = self.popGiftMap[giftType] or {}

			local parameter = config.parameter or SPECIAL_TYPE
			self.popGiftMap[giftType][parameter] = self.popGiftMap[giftType][parameter] or {}
			table.insert(self.popGiftMap[giftType][parameter], info)
		end
	end

	self:setGiftDirty()
end

function GiftPopData:getMinPopGiftData()
	local nowTime = Time:getServerTime()
	local result
	local minTime
	for type, map in pairs(self.popGiftMap) do
		local find = false
		for parameter, list in pairs(map) do
			for _, info in ipairs(list) do
				local endTime = info.endTime
				if type == PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER then
					endTime = info.beginTime + ActGiftCfg[info.id].limit_time_2 * 3600
				end
				if endTime > nowTime and (not minTime or endTime < minTime) then
					local boughtCount = self:getGiftBoughtNum(info.id)
					if boughtCount <= 0 then
						minTime = endTime
						result = info
					end
				end
			end
		end
	end

	return result
end

function GiftPopData:getCustomGiftList(giftType, parameter)
	if not self.popGiftMap[giftType] then
		return
	end

	return self.popGiftMap[giftType][parameter]
end

function GiftPopData:getPopGiftMap()
	return self.popGiftMap
end

function GiftPopData:getPopGiftListByGiftType(giftType)
	if not self.popGiftMap[giftType] then
		return {}
	end
	local list = {}
	for k,v in pairs(self.popGiftMap[giftType]) do
		for kk, vv in pairs(v) do
			local boughtCount = DataManager.GiftPopData:getGiftBoughtNum(vv.id)
			if boughtCount <= 0 then
				table.insert(list, vv)
			end
		end
	end
	table.sort(list, function(a, b)
		return a.id < b.id
	end)
	return list
end

function GiftPopData:getPopGiftTriggerTime(giftId)
	return self.triggerTimeMap and self.triggerTimeMap[giftId] or 0
end

function GiftPopData:getPopGiftNotBuyCount(giftId)
	local giftType = ActGiftCfg[giftId].type
	return self.notBuyCountMap and self.notBuyCountMap[giftType] or 0
end

function GiftPopData:resetNotBuyCount(giftId)
	if ActGiftCfg[giftId] then
		local giftType = ActGiftCfg[giftId].type
		if self.notBuyCountMap and self.notBuyCountMap[giftType] then
			self.notBuyCountMap[giftType] = 0

			-- 本地重置冷却时间
			for giftType, map in pairs(self.popGiftMap) do
				for parameter, list in pairs(map) do
					for _, info in ipairs(list) do
						if info.type == ActGiftCfg[giftId].type then
							local triggerTime = self:getPopGiftTriggerTime(info.id)
							local oldCoolDown = info.cooldown
							info.cooldown = triggerTime + (ActGiftCfg[info.id].cd or 0) * 3600

							if EDITOR_MODE then
								Logger.logHighlight("因购买调整礼包 %s 冷却时间:%s->%s", info.id, Time:formatTimeYMDHMS2(oldCoolDown), Time:formatTimeYMDHMS2(info.cooldown))
							end
						end
					end
				end
			end

			-- 同步服务器
			ModuleManager.GiftPopManager:syncActivePopGiftNotBuyCountOnly(self.notBuyCountMap)
		end
	end
end

function GiftPopData:setPopGiftType(type, params)
	self.data.popGiftType = type
	self.params = params
end

function GiftPopData:getPopGiftType(isFirstEnter)
	if self.data.popGiftType then
		return self.data.popGiftType, self.params
	end

	if isFirstEnter then
		if not self.data.popGiftType then
			local nowTime = Time:getServerTime()
			for type, map in pairs(self.popGiftMap) do
				for parameter, list in pairs(map) do
					for _, info in ipairs(list) do
						if info.endTime > nowTime then
							local boughtCount = self:getGiftBoughtNum(info.id)
							if boughtCount <= 0 then
								self.data.popGiftType = type
								return self.data.popGiftType, self.params
							end
						end
					end
				end
			end
		end
	end
	return self.data.popGiftType, self.params
end

function GiftPopData:setGiftDirty()
	self.data.isDirty = not self.data.isDirty
end

function GiftPopData:onPopGiftTime()
	-- if not GFunc.IsGotServerTime() then
	-- 	return false
	-- end

	if not self.lastGiftPopTime then
		self.lastGiftPopTime = LocalData:getPopGiftTime()
	end

	return Time:getServerTime() > self.lastGiftPopTime
end

-- 获得自选礼包的所选index
function GiftPopData:getGiftChooseRewardIndex(giftId)
	return LocalData:getPopGiftChooseIndex(giftId)
end

function GiftPopData:setGiftChooseRewardIndex(giftId, index)
	LocalData:setPopGiftChooseIndex(giftId, index)

	self:setGiftDirty()
end

function GiftPopData:getGiftValueStr(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return GConst.EMPTY_STRING
	end
	if not cfg.value then
		return GConst.EMPTY_STRING
	end
	return cfg.value .. "%"
end

function GiftPopData:getGiftRewards(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return
	end
	return cfg.reward
end

function GiftPopData:getGiftChooseRewards(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return
	end
	return cfg.choose_reward
end

function GiftPopData:getGiftPrice(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return
	end
	return GFunc.getFormatPrice(cfg.recharge_id)
end

function GiftPopData:getGiftParameter(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return
	end
	return cfg.parameter
end

function GiftPopData:getGiftBanner(giftId)
	local cfg = self:getGiftConfig(giftId)
	if not cfg then
		return
	end
	return cfg.banner or 1
end

function GiftPopData:activePopGift(giftType, parameter, parameter2, parameter3)
	if EDITOR_MODE then
		Logger.logHighlight("----activePopGift----  giftType = %s | parameter = %s | parameter2 = %s" , giftType, parameter, parameter2)
		Logger.printTable(self.typeIds[giftType])
	end

	if not ModuleManager:getIsOpen(ModuleManager.MODULE_KEY.GIFT_POPUP, true) then
		return
	end

	local giftIds
	if not self.typeIds[giftType] then
		return
	end

	giftIds = table.refCopy(self.typeIds[giftType][parameter])
	if not giftIds then
		return
	end

	local map = {}
	-- for _, id in ipairs(giftIds) do
	-- 	map[id] = true
	-- end

	local nowTime = Time:getServerTime()
	local activingGiftInfos = self.popGiftMap[giftType] and self.popGiftMap[giftType][parameter]
	if activingGiftInfos then
		for _, info in ipairs(activingGiftInfos) do
			-- if map[info.id] then
				if info.cooldown > nowTime then -- 冷却或未结束
					map[info.id] = true
				end

				if info.endTime > nowTime then -- 冷却或未结束
					map[info.id] = true
				end

				if giftType == 19 then
					map[info.id] = true
				end
			-- end
		end
	end
	for i = #giftIds, 1, -1 do
		if map[giftIds[i]] then
			table.remove(giftIds, i)
		end
	end
	---- 需要触发了
	self.popGiftMap[giftType] = self.popGiftMap[giftType] or {}
	self.popGiftMap[giftType][parameter] = self.popGiftMap[giftType][parameter] or {}
	self.triggerTimeMap = self.triggerTimeMap or {}
	self.notBuyCountMap = self.notBuyCountMap or {}
	-- 记录得该类型礼包得未购买次数,根据购买时间更新
	local notBuyCount = self.notBuyCountMap[giftType] or 0
	local bought = false
	for _, giftId in ipairs(giftIds) do
		local lastBoughtTime = DataManager.PaymentData:getGiftBoughtTime(giftType, giftId) -- 上次购买时间
		local lastTriggerTime = self:getPopGiftTriggerTime(giftId)
		if lastBoughtTime < 0 then
			lastBoughtTime = 0
		end
		if lastTriggerTime < 0 then
			lastTriggerTime = 0
		end
		-- 如果上一次的购买时间大于最近一次的触发时间，说明上一次买了
		if lastBoughtTime > lastTriggerTime then
			bought = true
			break
		end
	end
	if bought then
		notBuyCount = 1
	else
		notBuyCount = notBuyCount + 1
	end

	local isActiveThisTime = false
	local activeMap = {}
	local payAverage = DataManager.PaymentData:getPayAverage()
	for _, giftId in ipairs(giftIds) do
		local isPayConditionValid = false
		-- 判断档位有效性,只触发对应档位的
		local payCondition = ActGiftCfg[giftId].pay_condition
		if payCondition then
			if payCondition[1] <= payAverage and payAverage < payCondition[2] then
				isPayConditionValid = true
			elseif payCondition[2] >= 9999 and payAverage >= 9999 then
				isPayConditionValid = true
			end
		else
			isPayConditionValid = true
		end
		-- 判断额外参数
		local isParameterProValid = false
		local parameterPro = ActGiftCfg[giftId].parameter_pro
		if parameterPro then
			if giftType == PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_HERO_LV then -- 英雄等级
				local lv = parameterPro[1] or 0
				if parameter2 == lv then
					isParameterProValid = true
				end
			elseif giftType == PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER then -- 章节礼包
				if parameterPro[1] and DataManager.PaymentData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, parameterPro[1]) > 0 then
					isParameterProValid = true
				end
			elseif giftType == PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_EQUIP_RESONANCE then -- 装备共鸣弹窗礼包
				if parameterPro[1] and parameterPro[1] == parameter2 and parameterPro[2] <= parameter3 then
					isParameterProValid = true
				end

			end
		else
			isParameterProValid = true
		end

		if isPayConditionValid and isParameterProValid then
			local cfg = ActGiftCfg[giftId]
			local info = {
				id = giftId,
				type = giftType,
				beginTime = nowTime,
				endTime = nowTime + cfg.limit_time * 3600,
				realEndTime = nowTime + cfg.limit_time * 3600,
			}
			if cfg.cd then
				if cfg.max_cd_times then
					info.cooldown = nowTime + cfg.cd * 3600 * math.max(1, math.min(notBuyCount + 1, cfg.max_cd_times))
				else
					info.cooldown = nowTime + cfg.cd * 3600
				end
			else
				info.cooldown = nowTime
			end
			table.insert(self.popGiftMap[giftType][parameter], info)
			self.triggerTimeMap[giftId] = nowTime
			self.notBuyCountMap[giftType] = notBuyCount
			activeMap[giftId] = nowTime
			self:setPopGiftType(giftType, giftId)
			self:setGiftDirty()
			-- bi日志上报
			local biType = self:getBiReportByGiftType(giftId)
			if biType then
				BIReport:postPopGift(biType, giftId, cfg.recharge_id, Time:getServerTime())
			end
			DataManager.PaymentData:resetGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, giftId)

			-- 标记本次触发
			isActiveThisTime = true

			if EDITOR_MODE then
				Logger.logHighlight("成功触发礼包 -- giftId:%s  notBuyCount:%s  cooldown:%s", giftId, notBuyCount, Time:formatTimeYMDHMS2(info.cooldown))
			end
		end
	end

	if table.nums(activeMap) <= 0 then
		return
	end
	ModuleManager.ActivityPopManager:setGiftPopState(true)
	ModuleManager.GiftPopManager:syncActivePopGift(activeMap, self.notBuyCountMap)

	return true, isActiveThisTime, activeMap
end

function GiftPopData:getGiftBoughtNum(giftId)
	return DataManager.PaymentData:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.ACT_GIFT, giftId) or 0
end

-- 等级弹窗礼包
function GiftPopData:activeLvUpPopGift(lv)
	local giftType = PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_LV
	self:activePopGift(giftType, lv)
end

function GiftPopData:getActivePopGiftId()
	return self.heroLvUpPopGiftId
end

function GiftPopData:setActivePopGiftId(giftId)
	self.heroLvUpPopGiftId = giftId
end

-- 装备共鸣弹窗礼包
function GiftPopData:activeEquipResonancePopGift(type, lv)
	local giftType = PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_EQUIP_RESONANCE
	local _, _, activeMap = self:activePopGift(giftType, SPECIAL_TYPE, type, lv)
	if activeMap then
		for k,v in pairs(activeMap) do
			self:setActivePopGiftId(k)
			EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.MAIN_UI_CHECK_POP_TIMELY)
			break
		end
	end
end

-- 英雄等级弹窗礼包
function GiftPopData:activeHeroLvUpPopGift(heroId, lv)
	local giftType = PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_HERO_LV
	local _, _, activeMap = self:activePopGift(giftType, heroId, lv)
	if activeMap then
		for k,v in pairs(activeMap) do
			self:setActivePopGiftId(k)
			EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.MAIN_UI_CHECK_POP_TIMELY)
			break
		end
	end
end

-- 章节弹窗礼包
function GiftPopData:activeChapterPopGift(chapterId)
	local giftType = PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER
	local _, _, activeMap = self:activePopGift(giftType, chapterId)
	if activeMap then
		for k,v in pairs(activeMap) do
			self:setActivePopGiftId(k)
			EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.MAIN_UI_CHECK_POP_TIMELY)
			break
		end
	end
end

-- 防线弹窗礼包
function GiftPopData:activeDefenseLinePopGift(lv)
	local giftType = PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_DEFENSE_LINE
	local _, _, activeMap = self:activePopGift(giftType, lv)
	if activeMap then
		for k,v in pairs(activeMap) do
			self:setActivePopGiftId(k)
			EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.MAIN_UI_CHECK_POP_TIMELY)
			break
		end
	end
end

function GiftPopData:checkChapterGiftVersion()
	if self.popGiftMap == nil then
		return
	end
	if self.typeIds == nil then
		return
	end
	local popGiftServerMap = self.popGiftMap[PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER] or GConst.EMPTY_TABLE
	local maxId = DataManager.ChapterData:getMaxPassId() or 0
	local popGiftCfgMap = self.typeIds[PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER] or GConst.EMPTY_TABLE
	for chapterId, v in pairs(popGiftCfgMap) do
		if maxId >= chapterId then
			if popGiftServerMap[chapterId] == nil or #popGiftServerMap[chapterId] <= 0 then
				self:activeChapterPopGift(chapterId)
			end
		end
	end
end

return GiftPopData