local PaymentData = class("PaymentData", BaseData)
local RECHARGE_CFG = ConfigManager:getConfig("recharge")

PaymentData.PAY_WAY = {
    DIRECTE = 1,
    DAI_JIN_JUAN = 2
}

function PaymentData:ctor()
    self.data.payTotal = 0 -- 总付费(美元)
    self.data.payTotalCount = 0 -- 总付费次数
    self.data.payAverage = 0 -- 总付费/总付费次数
    self.data.thirdPayTotal = 0
    self.payCount = {}
    self.data.isDirty = false
    self.defalutPayWay = nil
end

function PaymentData:clear()
    self.data.payTotal = 0
    self.data.payTotalCount = 0
    self.data.payAverage = 0
    self.data.thirdPayTotal = 0
    self.payCount = {}
    self.giftMap = {}
    self.defalutPayWay = nil
end

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

function PaymentData:initData(data)
    data = data or {}
    local pay_counts = data.pay_counts or {}
    if EDITOR_MODE then
		Logger.logHighlight("礼包购买数据")
		Logger.printTable(data)
	end

    self.data.payTotal = 0
    self.data.payTotalCount = 0 
    self.data.payAverage = 0 
    self.data.thirdPayTotal = data.third_pay_total or 0
    self.payCount = data.pay_counts or {}

    for id, count in pairs(pay_counts) do
        if RECHARGE_CFG[id] then
            self.data.payTotal = self.data.payTotal + (RECHARGE_CFG[id].price or 0) * count
            self.data.payTotalCount = self.data.payTotalCount + count
        end
    end
    if self.data.payTotalCount > 0 then
        self.data.payAverage = self.data.payTotal / self.data.payTotalCount
    else
        self.data.payAverage = 0 
    end

    if EDITOR_MODE then
		Logger.logHighlight("消费总额：" .. tostring(self:getPayTotal()))
	end
end

function PaymentData:addPayment(rechargeId)
	local cfg = ConfigManager:getConfig("recharge")[rechargeId]
    if cfg == nil then
        return
    end

    local beforeCount = self.data.payTotal
	self.data.payTotal = self.data.payTotal + cfg.price
    self:checkFirebasePurchase(beforeCount)
    self.data.payTotalCount = self.data.payTotalCount + 1
    self.data.payAverage = self.data.payTotal / self.data.payTotalCount
	self.payCount[rechargeId] = (self.payCount[rechargeId] or 0) + 1
    -- DataManager.PlayerData:addPayScore(cfg.score)
    ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_BUY_ANYONE)

    if EDITOR_MODE then
		Logger.logHighlight("消费总额：" .. tostring(self:getPayTotal()))
	end
end

function PaymentData:checkFirebasePurchase(beforeCount)
    local beforeCount1 = (beforeCount * 1000) // 1000
    local afterCount = (self.data.payTotal * 1000) // 1000
    local beforeCount5 = beforeCount1 - beforeCount1 % 5
    if EDITOR_MODE then
        Logger.logHighlight("afterCount = %s self.data.payTotal = %s", afterCount, self.data.payTotal)
    end
    if afterCount > beforeCount1 then
        for i = beforeCount1 + 1, afterCount do
            BIReport:postPurchaseAmountEvent(1)
        end
    end
    local diffCount = (afterCount - beforeCount5) // 5
    if diffCount > 0 then
        for i = 1, diffCount do
            BIReport:postPurchaseAmountEvent(5)
        end
    end
end

function PaymentData:initActGift(gift)
    if gift == nil then
        return
    end
    if EDITOR_MODE then
		Logger.logHighlight("ActGift礼包购买数据")
		Logger.printTable(gift)
	end
    local gifts = gift.gifts or {}
    local refreshAt = gift.refresh_at or {}
    -- 转为map结构
    for _, gift in ipairs(gifts) do
        local giftType = gift.gift_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.actGiftRefreshAt = table.clearOrCreate(self.actGiftRefreshAt)
    local nowTime = Time:getServerTime()
    for id, time in pairs(refreshAt) do -- 针对act_gift
        time = GFunc.formatTimeStep(time)
        if time > nowTime then
            self.actGiftRefreshAt[id] = time
        end
    end

    self:setDirty()
end

function PaymentData:getPayTotal()
    return self.data.payTotal
end

function PaymentData:getPayAverage()
    return self.data.payAverage
end

function PaymentData:setThirdPayTotal(thirdPayTotal)
	self.data.thirdPayTotal = thirdPayTotal
    local data = {
        third_pay_money = self.data.thirdPayTotal
    }
    BIReport:TAUserSet(data)
end

function PaymentData:getThirdPayTotal()
    return self.data.thirdPayTotal
end

function PaymentData:getPayCount()
    return self.payCount
end

function PaymentData:getAllPayCount()
    local num = 0
    for rechargeIdStr, count in pairs(self.payCount) do
        num = num + count
    end
    return num
end

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

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

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

function PaymentData:getGiftMapByGiftType(giftType)
    if not self.giftMap then
        return {}
    end
    return self.giftMap[giftType] or {}
end

function PaymentData:updateGiftInfo(gift, rewards)
    local giftType = gift.gift_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.SHOP_GEM then
        DataManager.ShopData:setDirty()
    elseif giftType == PayManager.PURCHARSE_TYPE.GIFT_ROUTINE then
        DataManager.GiftRoutineData:setDirty()
    elseif giftType == PayManager.PURCHARSE_TYPE.ACT_GIFT then
        local config = ConfigManager:getConfig("act_gift")[giftId]
        if config and config.type == PayManager.PURCHARSE_ACT_TYPE.ACT_SEVEN_DAY then
            local giftType = 1
            if config.item_cost then
                giftType = 2
            elseif config.recharge_id then
                giftType = 3
            end
            if rewards then
                BIReport:postSevenDayGift(BIReport.SEVEN_DAY_GIFT_OPT.REWARD, giftId, giftType, GFunc.getRewardsStr(rewards), config.parameter)
            end
        elseif config and config.type == PayManager.PURCHARSE_ACT_TYPE.FORCE_SKIN then
            DataManager.ForceData:onSkinBoughtSuccess()
        end
        if GConst.ShopConst.PRIVILEGE_CARD_ID_MAP[giftId] then
            DataManager.PrivilegeCardData:onGiftBuySuccess(giftId)
        end
        if giftId == DataManager.SignWeekData:getProRewardGiftId() then
            DataManager.SignWeekData:onBountyBuySuccess()
        end
        -- if giftId == DataManager.ActMagicData:getProRewardGiftId() then
        --     DataManager.ActMagicData:onBountyBuySuccess()
        -- end
        -- if giftId == DataManager.ActIceData:getProRewardGiftId() then
        --     DataManager.ActIceData:onBountyBuySuccess()
        -- end
        -- if giftId == DataManager.ActNewYearData:getProRewardGiftId() then
        --     DataManager.ActNewYearData:onBountyBuySuccess()
        -- end
        -- if giftId == DataManager.ActSailingData:getProRewardGiftId() then
        --     DataManager.ActSailingData:onBountyBuySuccess()
        -- end
        -- if giftId == DataManager.ActDreamData:getProRewardGiftId() then
        --     DataManager.ActDreamData:onBountyBuySuccess()
        -- end
        -- if giftId == DataManager.ActTimeGapData:getProRewardGiftId() then
        --     DataManager.ActTimeGapData:onBountyBuySuccess()
        -- end
        if GConst.ActSprintConst.ACT_ID_MAP[giftId] then
            DataManager.ActSprintData:onGiftBuySuccess(giftId)
        end
    end

    self:setDirty()
end

-- 获得一个礼包的上次购买时间
function PaymentData:getGiftBoughtTime(actType, actId)
    local data = self:getActGiftDetailData(actType, actId)
    if data then
        return data.latest_buy_at
    end
    return 0
end

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

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

-- 得到act_gift限购礼包的重置时间，为nil则表示不重置
function PaymentData:getActGiftRefreshAt(actId)
    return self.actGiftRefreshAt and self.actGiftRefreshAt[actId]
end

function PaymentData:clearActGiftRefreshAt(actId)
    if not self.actGiftRefreshAt then
        return
    end
    self.actGiftRefreshAt[actId] = nil
end

function PaymentData:isGemStoreDouble(id)
	local cfg = ConfigManager:getConfig("mall_treasure")[id]
	if not cfg then
		return false
	end
	local count = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.SHOP_GEM, id)
	return count < cfg.limit
end

function PaymentData:getGemStoreDoubleCount(id)
    local cfg = ConfigManager:getConfig("mall_treasure")[id]
    if not cfg then
        return 0
    end
    local count = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.SHOP_GEM, id)
    return cfg.limit - count
end

function PaymentData:isJollyMaxDouble(id)
    local count = self:getGiftBoughtNum(PayManager.PURCHARSE_TYPE.GIFT_JOLLYMAX, id)
    return count <= 0
end

-- 免广告
function PaymentData:getIsOpenAdFree()
    return false
end

-- 免广告或者终身卡买了都算
function PaymentData:getIsSkipAd()
    if DataManager.PrivilegeCardData:getIsSkipAd() then
        return true
    end
    return false
end

function PaymentData:getDefaultPayWay()
    return self.defalutPayWay
end

function PaymentData:setDefaultPayWay(payWay)
    self.defalutPayWay = payWay
end

--@region 俄罗斯JollyMax网页支付处理
function PaymentData:updateJollyMaxGiftInfo(gift, rewards)
	local giftType = PayManager.PURCHARSE_TYPE.ACT_GIFT
	local giftId = gift.id

    self.giftMap = self.giftMap or {}
    self.giftMap[giftType] = self.giftMap[giftType] or {}
    self.giftMap[gift.gift_type] = self.giftMap[gift.gift_type] or {}

    self.giftMap[gift.gift_type][giftId] = table.refCopy(gift)
	-- if giftId == 1001 then
	-- 	gift.id = GConst.MonthlyCardConst.CARD_GIFT_ID[GConst.MonthlyCardConst.CARD_TYPE.CARD_1]
	-- 	gift.gift_type = giftType
	-- 	self.giftMap[giftType][gift.id] = gift
    --     DataManager.MonthlyCardData:onGiftBuySuccess(gift.id)
	-- elseif giftId == 1002 then
	-- 	gift.id = GConst.MonthlyCardConst.CARD_GIFT_ID[GConst.MonthlyCardConst.CARD_TYPE.CARD_2]
	-- 	gift.gift_type = giftType
	-- 	self.giftMap[giftType][gift.id] = gift
	-- 	DataManager.MonthlyCardData:onGiftBuySuccess(gift.id)
	-- end

	self:setDirty()
end
--@endregion
return PaymentData