local PayManager = class("PayManager", BaseModule)

PayManager.PURCHARSE_TYPE = {
    ACT_GIFT = 1,
    ACT_GOLD_PIG = 2,
    CHAPTER_GIFT = 3,
    GROW_UP_GIFT = 4,-- 已废弃
    MALL_TREASURE = 5,
    GROW_UP_GIFT_NEW = 6,
}

PayManager.PURCHARSE_ACT_TYPE = {
    FIRST_RECHARGE = 1,
    COIN_GIFT = 2,
    INTRODUCTORY_GIFT = 3,
    BEGINNER_GIFT = 4,
    LEVEL_UP_GIFT = 5,
    GROWTH_FUND = 6,
    BOUNTY = 7,
    ARENA_BOUNTY = 8,
    ARENA_GIFT = 9,
    ARMOR_FUND = 10,
    WEAPON_GIFT = 11,
    ARMOR_GIFT = 12,
    ACT_SUMMER = 13,
    ACT_HERO_FUND = 14,
    WEAPON_UPGRADE_GIFT = 15,
    ARMOR_UPGRADE_GIFT = 16,
    FOURTEEN_DAY_GIFT = 17,
    ACT_PVP_BOUNTY = 22,
    FULL_MOON_HERO_GIFT = 18,
    FULL_MOON_NEW_HERO_GIFT = 19,
    FULL_MOON_SKIN_GIFT = 20,
    RUNES_GIFT = 21,
    TOURN_WAVE_GIFT = 23,
    TOURN_ARENA_GIFT = 24,
}

PayManager.PURCHARSE_TYPE_CONFIG = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = "act_gift",
    [PayManager.PURCHARSE_TYPE.ACT_GOLD_PIG] = "act_gold_pig",
    [PayManager.PURCHARSE_TYPE.MALL_TREASURE] = "mall_treasure",
    [PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = "act_chapter_store",
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = "act_growup_gift_new",
}

PayManager.BI_ITEM_GET_TYPE = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = BIReport.ITEM_GET_TYPE.FIRST_RECHARGE,
        [PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT] = BIReport.ITEM_GET_TYPE.COIN_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.INTRODUCTORY_GIFT] = BIReport.ITEM_GET_TYPE.INTRODUCTORY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT] = BIReport.ITEM_GET_TYPE.BEGINNER_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT] = BIReport.ITEM_GET_TYPE.LEVEL_UP_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.GROWTH_FUND] = BIReport.ITEM_GET_TYPE.GROWTH_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.BOUNTY] = BIReport.ITEM_GET_TYPE.BOUNTY,
        [PayManager.PURCHARSE_ACT_TYPE.ARENA_BOUNTY] = BIReport.ITEM_GET_TYPE.ARENA_BOUNTY,
        [PayManager.PURCHARSE_ACT_TYPE.ARENA_GIFT] = BIReport.ITEM_GET_TYPE.ARENA_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_FUND] = BIReport.ITEM_GET_TYPE.ARMOR_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT] = BIReport.ITEM_GET_TYPE.WEAPON_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT] = BIReport.ITEM_GET_TYPE.ARMOR_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_SUMMER] = BIReport.ITEM_GET_TYPE.ACT_SUMMER,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_HERO_FUND] = BIReport.ITEM_GET_TYPE.ACT_HERO_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT] = BIReport.ITEM_GET_TYPE.WEAPON_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT] = BIReport.ITEM_GET_TYPE.ARMOR_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FOURTEEN_DAY_GIFT] = BIReport.ITEM_GET_TYPE.FOURTEEN_DAY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_PVP_BOUNTY] = BIReport.ITEM_GET_TYPE.ACT_PVP_BOUNTY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_HERO_GIFT] = BIReport.ITEM_GET_TYPE.FULL_MOON_HERO_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_NEW_HERO_GIFT] = BIReport.ITEM_GET_TYPE.FULL_MOON_NEW_HERO_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_SKIN_GIFT] = BIReport.ITEM_GET_TYPE.FULL_MOON_SKIN_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.RUNES_GIFT] = BIReport.ITEM_GET_TYPE.RUNES_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.TOURN_WAVE_GIFT] = BIReport.ITEM_GET_TYPE.TOURN_WAVE_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.TOURN_ARENA_GIFT] = BIReport.ITEM_GET_TYPE.TOURN_ARENA_GIFT,
    },
    [PayManager.PURCHARSE_TYPE.ACT_GOLD_PIG] = BIReport.ITEM_GET_TYPE.GOLD_PIG,
    [PayManager.PURCHARSE_TYPE.MALL_TREASURE] = BIReport.ITEM_GET_TYPE.MALL_TREASURE,
    [PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = BIReport.ITEM_GET_TYPE.ACT_CHAPTER_STORE,
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = BIReport.ITEM_GET_TYPE.GROW_UP_GIFT_NEW,
}

PayManager.BI_GIFT_TYPE = {
    [PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = BIReport.GIFT_TYPE.FIRST_RECHARGE,
        [PayManager.PURCHARSE_ACT_TYPE.COIN_GIFT] = BIReport.GIFT_TYPE.COIN_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.INTRODUCTORY_GIFT] = BIReport.GIFT_TYPE.INTRODUCTORY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.BEGINNER_GIFT] = BIReport.GIFT_TYPE.BEGINNER_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.LEVEL_UP_GIFT] = BIReport.GIFT_TYPE.LEVEL_UP_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.GROWTH_FUND] = BIReport.GIFT_TYPE.GROWTH_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.BOUNTY] = BIReport.GIFT_TYPE.BOUNTY,
        [PayManager.PURCHARSE_ACT_TYPE.ARENA_BOUNTY] = BIReport.GIFT_TYPE.ARENA_BOUNTY,
        [PayManager.PURCHARSE_ACT_TYPE.ARENA_GIFT] = BIReport.GIFT_TYPE.ARENA_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_FUND] = BIReport.GIFT_TYPE.ARMOR_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_GIFT] = BIReport.GIFT_TYPE.WEAPON_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_GIFT] = BIReport.GIFT_TYPE.ARMOR_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_SUMMER] = BIReport.GIFT_TYPE.ACT_SUMMER,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_HERO_FUND] = BIReport.GIFT_TYPE.ACT_HERO_FUND,
        [PayManager.PURCHARSE_ACT_TYPE.WEAPON_UPGRADE_GIFT] = BIReport.GIFT_TYPE.WEAPON_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ARMOR_UPGRADE_GIFT] = BIReport.GIFT_TYPE.ARMOR_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FOURTEEN_DAY_GIFT] = BIReport.GIFT_TYPE.FOURTEEN_DAY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.ACT_PVP_BOUNTY] = BIReport.GIFT_TYPE.ACT_PVP_BOUNTY_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_HERO_GIFT] = BIReport.GIFT_TYPE.FULL_MOON_HERO_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_NEW_HERO_GIFT] = BIReport.GIFT_TYPE.FULL_MOON_NEW_HERO_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.FULL_MOON_SKIN_GIFT] = BIReport.GIFT_TYPE.FULL_MOON_SKIN_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.RUNES_GIFT] = BIReport.GIFT_TYPE.RUNES_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.TOURN_WAVE_GIFT] = BIReport.GIFT_TYPE.TOURN_WAVE_GIFT,
        [PayManager.PURCHARSE_ACT_TYPE.TOURN_ARENA_GIFT] = BIReport.GIFT_TYPE.TOURN_ARENA_GIFT,
    },
    [PayManager.PURCHARSE_TYPE.ACT_GOLD_PIG] = BIReport.GIFT_TYPE.GOLD_PIG,
    [PayManager.PURCHARSE_TYPE.MALL_TREASURE] = BIReport.GIFT_TYPE.MALL_TREASURE,
    [PayManager.PURCHARSE_TYPE.CHAPTER_GIFT] = BIReport.GIFT_TYPE.ACT_CHAPTER_STORE,
    [PayManager.PURCHARSE_TYPE.GROW_UP_GIFT_NEW] = BIReport.GIFT_TYPE.GROW_UP_GIFT_NEW,
}

function PayManager:getItemGetType(purchaseType, id)
    local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[purchaseType]
    if not cfgName then
        return
    end
    local cfg = ConfigManager:getConfig(cfgName)
    local typeMap = PayManager.BI_ITEM_GET_TYPE[purchaseType]
    if not cfg or not cfg[id] or not typeMap then
        return
    end
    local subType = cfg[id].type
    if subType then
        return typeMap[cfg[id].type]
    else
        if type(typeMap) ~= "table" then
            return typeMap
        end
    end
end

function PayManager:getGiftType(purchaseType, id)
    local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[purchaseType]
    if not cfgName then
        return
    end
    local cfg = ConfigManager:getConfig(cfgName)
    local typeMap = PayManager.BI_GIFT_TYPE[purchaseType]
    if not cfg or not cfg[id] or not typeMap then
        return
    end
    local subType = cfg[id].type
    if subType then
        return typeMap[cfg[id].type]
    else
        if type(typeMap) ~= "table" then
            return typeMap
        end
    end
end

function PayManager:getGiftConfigInfo(purchaseType, id)
    local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[purchaseType]
    if not cfgName then
        return
    end
    local cfg = ConfigManager:getConfig(cfgName)
    if not cfg or not cfg[id] then
        return
    end
    return cfg[id]
end

function PayManager:getPackageRechargeId(purchaseType, id)
    local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[purchaseType]
    if not cfgName then
        return
    end
    local cfg = ConfigManager:getConfig(cfgName)
    if not cfg or not cfg[id] then
        return
    end
    return cfg[id].recharge_id
end

function PayManager:purchasePackage(id, purchaseType)
    local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[purchaseType]
    if not cfgName then
        return
    end
    local cfg = ConfigManager:getConfig(cfgName)
    if not cfg or not cfg[id] then
        return
    end

    local rechargeId = cfg[id].recharge_id
    local giftType = PayManager:getGiftType(purchaseType, id)
    local productId
    if rechargeId then
        local rechargeCfg = ConfigManager:getConfig("recharge")[rechargeId]
        if rechargeCfg == nil then
            return
        end
        productId = rechargeCfg.payId
        BIReport:postPayClick(giftType, id, rechargeId)
    end
    self:checkAndPay(productId, id, purchaseType, rechargeId)
end

function PayManager:requestRewards(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback)
    self:sendMsgToServer(purchaseToken, orderId, originOrderId, productId, function(binder, msgData)
        if msgData.status == 0 then
            local showRewards = not notShowRewardsBox
            if DataManager.TutorialData and DataManager.TutorialData:getIsInTutorial() then -- 引导时不弹
                showRewards = false
            end

            if showRewards then
                if not EDITOR_MODE and not ModuleManager.AccountManager:getIsBinded() then -- 没绑定账户信息，提示去绑定
                    ModuleManager.AccountManager:showBindUI()
                end
                if msgData.rewards and table.nums(msgData.rewards) > 0 then
                    GFunc.showRewardBox(msgData.rewards)
                end
            end

            local biPayGetInfo = {}
            table.foreach(msgData.gift, function(i, gift)
                local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[gift.act_type]
                local cfgInfo = ConfigManager:getConfig(cfgName)[gift.id]
                local rechargeId = cfgInfo.recharge_id
                local beforCount = DataManager.PlayerData:getPayCounts(rechargeId)
                DataManager.PlayerData:addPayment(rechargeId)
                DataManager.ShopData:addPayment(rechargeId) -- 降档版本
                DataManager.ShopData:updateGiftInfo(gift)
                table.insert(biPayGetInfo, {
                    giftType = gift.act_type,
                    giftId = gift.id,
                    rechargeId = cfgInfo.recharge_id
                })
                if beforCount <= 0 then
                    BIReport:postFirstRechargeEvent(rechargeId)
                end
            end)

            for _, info in ipairs(biPayGetInfo) do
                local giftType = PayManager:getGiftType(info.giftType, info.giftId)
                BIReport:postPayGet(giftType, info.giftId, info.rechargeId, orderId, originOrderId, 1, msgData.rewards or {})
                local rechargeCfg = ConfigManager:getConfig("recharge")[info.rechargeId]
                if rechargeCfg then
                    BIReport:postPurchase(rechargeCfg.price, rechargeCfg.payId, originOrderId, orderId)
                end
            end

            -- 支付上报
            local data = {}
            data.pay_money = DataManager.PlayerData:getTotalPayAmount()
            data.pay_count = DataManager.PlayerData:getPayCount()
            CS.ThinkingAnalytics.ThinkingAnalyticsAPI.UserSet(data)

            -- 支付验证成功后消耗此订单
            if CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.Android then
                if purchaseToken then
                    SDKManager:consumePurchase(purchaseToken)
                end
            elseif CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.IPhonePlayer then
                if productId then
                    SDKManager:consumePurchase(productId)
                    SDKManager:delIosOrder(productId)
                end
                if originOrderId ~= "gm" then
                    SDKManager:delIosPayInfo(originOrderId)
                end
            end
        elseif msgData.status == 1008 then -- 验证异常,但是需要消耗订单
            if CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.Android then
                if purchaseToken then
                    SDKManager:consumePurchase(purchaseToken)
                end
            elseif CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.IPhonePlayer then
                if productId then
                    SDKManager:consumePurchase(productId)
                    SDKManager:delIosOrder(productId)
                end
                if originOrderId ~= "gm" then
                    SDKManager:delIosPayInfo(originOrderId)
                end
            end
            Logger.logError("重复验证")
        else
            Logger.logError("支付验证失败:%s", msgData.status)
            local params = {
                content = I18N:getGlobalText(I18N.GlobalConst.PAY_FAILED_DESC_1),
                boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
                okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
            }
            GFunc.showMessageBox(params)
        end
        if callback then
            callback()
        end
    end)
end

function PayManager:checkAndPay(productId, id, purchaseType, rechargeId)
    -- 检查是否可以支付
    SDKManager:checkPay(productId, function(code)
        if code == 0 then
            self:sendMessage(ProtoMsgType.FromMsgEnum.ActPayReq, {id = id, act_type = purchaseType}, {}, function(binder, msgData)
                if msgData.status == 0 then
                    if msgData.uuid and msgData.uuid ~= GConst.EMPTY_STRING then
                        local giftType = PayManager:getGiftType(purchaseType, id)
                        BIReport:postPayTurn(giftType, id, rechargeId)
                        SDKManager:pay(productId, msgData.uuid, rechargeId, giftType, purchaseType, id, function(purchaseToken, orderId, originOrderId)
                            if purchaseToken and orderId then
                                self:requestRewards(purchaseToken, orderId, originOrderId, productId)
                            end
                        end)
                    else -- 没有支付信息，直接发奖
                        if table.nums(msgData.rewards) > 0 then
                            GFunc.showRewardBox(msgData.rewards)
                        end
                        local giftData = {}
                        giftData.act_type = msgData.act_type
                        giftData.id = msgData.id
                        giftData.buy_count = DataManager.ShopData:getGiftBoughtNum(msgData.act_type, msgData.id) + 1
                        giftData.latest_buy_at = Time:getServerTime() * 1000 -- 服务器都是毫秒
                        DataManager.ShopData:updateGiftInfo(giftData)
                    end
                else
                    Logger.logError("预支付失败")
                end
            end)
        end
    end)
end

function PayManager:sendMsgToServer(purchaseToken, uuid, originOrderId, productId, callback)
    local args = SDKManager:getPurchaseArgs(purchaseToken, uuid, originOrderId, productId)
    self:sendMessage(ProtoMsgType.FromMsgEnum.ActPaidResultReq, args, {}, callback)
end

return PayManager