local PayManager = class("PayManager", BaseModule)

PayManager.PURCHARSE_TYPE = {
	ACT_GIFT = 1,
	SHOP_GEM = 2,
	-- GIFT_ROUTINE = 3,
	-- GIFT_JOLLYMAX = 4,
}

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,
	FIRST_RECHARGE = 1,
    PRIVILEGE_CARD = 2,
	BOUNTY = 3,
	FUND = 4,
	SIGN_BOUNTY = 5,
	GIFT_POP_CHAPTER = 10, -- 章节礼包
	ACT_COMMON = 11,-- 活动礼包通用11,具体礼包类型使用activity表中的act_type
	ACT_SEVEN_DAY = 15, -- 七天乐
}

PayManager.ACT_COMMON_TYPE = {
	-- ACT_SUMMON_HERO_GIFT = 1,
	ACT_SPRINT_SUMMON_GIFT = 2,
	-- ACT_SPRINT_BOX_GIFT = 3,
	-- ACT_SPRINT_SUMMON_GIFT_V2 = 4,
	-- ACT_SPRINT_BOX_GIFT_V2 = 5,
	-- ACT_SPRINT_TREE_GIFT = 6,
}

PayManager.PURCHARSE_TYPE_CONFIG = {
	[PayManager.PURCHARSE_TYPE.ACT_GIFT] = "act_gift",
	[PayManager.PURCHARSE_TYPE.SHOP_GEM] = "mall_treasure",
	-- [PayManager.PURCHARSE_TYPE.GIFT_ROUTINE] = "gift_routine",
	-- [PayManager.PURCHARSE_TYPE.GIFT_JOLLYMAX] = "gift_jollymax",
}

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.PRIVILEGE_CARD] = BIReport.ITEM_GET_TYPE.PRIVILEGE_CARD,
		[PayManager.PURCHARSE_ACT_TYPE.BOUNTY] = BIReport.ITEM_GET_TYPE.BOUNTY,
		[PayManager.PURCHARSE_ACT_TYPE.FUND] = BIReport.ITEM_GET_TYPE.FUND_GROW,
		[PayManager.PURCHARSE_ACT_TYPE.SIGN_BOUNTY] = BIReport.ITEM_GET_TYPE.SIGN_BOUNTY,
		[PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER] = BIReport.ITEM_GET_TYPE.GIFT_POP_CHAPTER,
		[PayManager.PURCHARSE_ACT_TYPE.ACT_COMMON] = {},
		[PayManager.PURCHARSE_ACT_TYPE.ACT_SEVEN_DAY] = BIReport.ITEM_GET_TYPE.SEVEN_DAY_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.SHOP_GEM] = BIReport.ITEM_GET_TYPE.SHOP_GEM,
}

PayManager.BI_GIFT_TYPE = {
	[PayManager.PURCHARSE_TYPE.ACT_GIFT] = {
        [PayManager.PURCHARSE_ACT_TYPE.FIRST_RECHARGE] = BIReport.GIFT_TYPE.FIRST_RECHARGE,
        [PayManager.PURCHARSE_ACT_TYPE.PRIVILEGE_CARD] = BIReport.GIFT_TYPE.PRIVILEGE_CARD,
		[PayManager.PURCHARSE_ACT_TYPE.BOUNTY] = BIReport.GIFT_TYPE.BOUNTY_PRO_REWARD,
		[PayManager.PURCHARSE_ACT_TYPE.FUND] = BIReport.GIFT_TYPE.FUND_GROW,
		[PayManager.PURCHARSE_ACT_TYPE.SIGN_BOUNTY] = BIReport.GIFT_TYPE.SIGN_BOUNTY,
		[PayManager.PURCHARSE_ACT_TYPE.GIFT_POP_CHAPTER] = BIReport.GIFT_TYPE.GIFT_POP_CHAPTER,
		[PayManager.PURCHARSE_ACT_TYPE.ACT_COMMON] = {},
		[PayManager.PURCHARSE_ACT_TYPE.ACT_SEVEN_DAY] = BIReport.GIFT_TYPE.SEVEN_DAY_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.SHOP_GEM] = BIReport.GIFT_TYPE.SHOP_GEM,
}

function PayManager:getActCommonTypeByActId(id)
	local actType
	local cfg = ConfigManager:getConfig("activity")
	for actId, info in pairs(cfg) do
		local actGiftIds = info.act_gift
		if actGiftIds then
			for _, giftId in ipairs(actGiftIds) do
				if giftId == id then
					actType = info.act_type
					break
				end
			end
		end
	end
	-- 一些特殊活动特殊处理
	if actType == nil then
		local cfg = ConfigManager:getConfig("act_bounty")
		for actId, info in pairs(cfg) do
			if id == info.reward_pro_pay and info.activity then
				local cfg = ConfigManager:getConfig("activity")[info.activity]
				if cfg and cfg.act_type then
					actType = cfg.act_type
				end
			end
		end
	end
	return actType
end

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
		if subType == PayManager.PURCHARSE_ACT_TYPE.ACT_COMMON then
			local commonType = self:getActCommonTypeByActId(id)
			if commonType then
				return typeMap[cfg[id].type][commonType]
			end
			return
		else
			return typeMap[cfg[id].type]
		end
	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
		if subType == PayManager.PURCHARSE_ACT_TYPE.ACT_COMMON then  
			local commonType = self:getActCommonTypeByActId(id)
			if commonType then
				return typeMap[cfg[id].type][commonType]
			end
			return
		else
			return typeMap[cfg[id].type]
		end
	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, freeShowRewards, doubleType, isFromBattle)
	local isFromBattle = isFromBattle or false -- 标记是否是战斗中购买
	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[VersionCompatible:getRechargePayId()]
		BIReport:postPayClick(giftType, id, rechargeId, doubleType, isFromBattle, purchaseType)
		self:showPayselectUI(rechargeId, function(useDaiJinJuan)
			if not useDaiJinJuan then
				self:checkAndPay(productId, id, purchaseType, rechargeId, doubleType, freeShowRewards, isFromBattle)
			else
				self:reqGiftPay(productId, id, purchaseType, rechargeId, doubleType, freeShowRewards, isFromBattle, true)
			end
		end)
	else
		self:checkAndPay(productId, id, purchaseType, rechargeId, doubleType, freeShowRewards, isFromBattle)
	end
end

function PayManager:requestRewards(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback, cmdId, payDouble, isFromBattle, isSpecialOrder, wayCode)
	local args = SDKManager:getPurchaseArgs(purchaseToken, orderId, originOrderId, productId)
	if isSpecialOrder then
		args = SDKManager:getPurchaseArgs2(purchaseToken, orderId, originOrderId, productId)
	end
	self:sendMessage(ProtoMsgType.FromMsgEnum.GiftPaidResultReq, args, function(binder, result)
		if result.err_code ~= GConst.ERROR_STR.SUCCESS then
			if result.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, nil, "repeat consume")
						SDKManager:delIosOrder(productId)
					end
					if originOrderId ~= "gm" then
						SDKManager:delIosPayInfo(originOrderId)
					end
				else
					if purchaseToken then
						SDKManager:consumePurchase(purchaseToken)
					end
				end
				Logger.logError("重复验证")
				BIReport:postRepeatPayOrder(productId, originOrderId, orderId, isFromBattle)

				if callback then
					callback(false)
				end
			elseif result.status == 1003 then -- 订单异常
				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)

				if callback then
					callback(false)
				end
			elseif result.status == 1001 then -- 订单异常
				-- 支付失败，服务器未找到此订单，所以消耗此订单，直接算掉单
				if CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.Android then
					if purchaseToken then
						SDKManager:consumePurchase(purchaseToken)
						GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.PAY_FAILED_DESC_1))
					end
				elseif CS.UnityEngine.Application.platform == CS.UnityEngine.RuntimePlatform.IPhonePlayer then
					if productId then
						SDKManager:consumePurchase(productId, nil, "repeat consume")
						SDKManager:delIosOrder(productId)
						GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.PAY_FAILED_DESC_1))
					end
					if originOrderId ~= "gm" then
						SDKManager:delIosPayInfo(originOrderId)
					end
				end
			else
				-- Logger.logError("支付验证失败:%s", result.status)
				self:retrySendPayRecord(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback, cmdId, payDouble, isFromBattle, isSpecialOrder, wayCode)
			end
			return
		end

		local showRewards = not notShowRewardsBox
		if DataManager.TutorialData and DataManager.TutorialData:getIsInTutorial() then -- 引导时不弹
			showRewards = false
		end

		if showRewards then
			-- if not EDITOR_MODE and not DataManager.PlayerData:isBinded() then -- 没绑定账户信息，提示去绑定
			--     ModuleManager.AccountManager:showBindUI()
			-- end
			if result.rewards and table.nums(result.rewards) > 0 then
				local unlockIds = {}
				for k, v in ipairs(result.rewards) do
					if v.type == GConst.REWARD_TYPE.ITEM then
						local cfg = ConfigManager:getConfig("item")[v.item.id]
						if cfg.type == GConst.ItemConst.ITEM_TYPE.FORCE then 
							if DataManager.ForceData:getForceIsNew(v.item.id) then
								table.insert(unlockIds, v.item.id)
								DataManager.ForceData:setForceIsNew(v.item.id, true)
							end
						end
					end
				end
				GFunc.showRewardBox(result.rewards, {unlockIds = unlockIds})
			end
		end

		local biPayGetInfo = {}
		local changeRechargeMap = {}
		local oneKeyRechargeId = 0
		local oneKeyGiftId = 0

		-- 打包购买
		table.foreach(result.gift, function(i, gift)
			local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[gift.gift_type]
			local cfgInfo = ConfigManager:getConfig(cfgName)[gift.id]
			local rechargeId = cfgInfo.recharge_id
			if cfgInfo.one_key then
				oneKeyRechargeId = rechargeId
				oneKeyGiftId = gift.id
			end
		end)

		table.foreach(result.gift, function(i, gift)
			local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[gift.gift_type]
			local cfgInfo = ConfigManager:getConfig(cfgName)[gift.id]
			local rechargeId = cfgInfo.recharge_id

			DataManager.PaymentData:updateGiftInfo(gift, result.rewards)
			if oneKeyGiftId <= 0 or oneKeyGiftId == gift.id then
				local beforCount = DataManager.PaymentData:getPayCount()[rechargeId] or 0
				DataManager.PaymentData:addPayment(rechargeId)
				table.insert(biPayGetInfo, {
					giftType = gift.gift_type,
					giftId = gift.id,
					rechargeId = cfgInfo.recharge_id
				})
				if beforCount <= 0 then
					BIReport:postFirstRechargeEvent(rechargeId)
				end
				BIReport:postRechargeEvent(rechargeId)
				changeRechargeMap[rechargeId] = (changeRechargeMap[rechargeId] or 0) + 1
			end
		end)

		-- 支付分成比例,不同支付方式不一样
		-- if payProportion == nil then
		--     payProportion = 1
		-- elseif type(payProportion) ~= "number" then
		--     payProportion = 1
		-- end
		for _, info in ipairs(biPayGetInfo) do
			local giftType = self:getGiftType(info.giftType, info.giftId)
			BIReport:postPayGet(giftType, info.giftId, info.rechargeId, payDouble, orderId, originOrderId, 1, result.rewards or {}, isFromBattle, nil, info.giftType)
			local rechargeCfg = ConfigManager:getConfig("recharge")[info.rechargeId]
			if rechargeCfg then
				if VersionCompatible:getIsPackageRU() and wayCode then
					self:calcDukPayProportion(rechargeCfg, wayCode, function (price)
						BIReport:postPurchase(nil, price, rechargeCfg.price, rechargeCfg[VersionCompatible:getRechargePayId()], originOrderId, orderId, rechargeCfg)
					end)
				elseif VersionCompatible:getIsPackageRUHW() and wayCode then
					self:calcHWPayProportion(rechargeCfg.price, wayCode, function (price)
						BIReport:postPurchase(nil, price, rechargeCfg.price, rechargeCfg[VersionCompatible:getRechargePayId()], originOrderId, orderId, rechargeCfg)
					end)
				else
					if productId then
						local currencyCode = SDKManager:getPriceCurrencyCode(productId)
						local price = SDKManager:getProductPriceAmountMicros(productId) or rechargeCfg.price
						if price <= 0 then
							currencyCode = nil
							price = rechargeCfg.price
						end
						BIReport:postPurchase(currencyCode, price, rechargeCfg.price, rechargeCfg[VersionCompatible:getRechargePayId()], originOrderId, orderId, rechargeCfg)
					else
						BIReport:postPurchase(nil, rechargeCfg.price, rechargeCfg.price, rechargeCfg[VersionCompatible:getRechargePayId()], originOrderId, orderId, rechargeCfg)
					end
				end
			end
		end

		if oneKeyRechargeId > 0 then
			changeRechargeMap = {}
			changeRechargeMap[oneKeyRechargeId] = 1
		end
		if changeRechargeMap then
			local score = 0
			local changeCount = 0
			local cfg = ConfigManager:getConfig("recharge")
			for id, count in pairs(changeRechargeMap) do
				local info = cfg[id]
				if info then
					if info.score then
						score = score + info.score * count
						changeCount = changeCount + count
					end
				end
			end
			if score > 0 then
				ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.RECHARGE_NUM, score)
				ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.RECHARGE_NUM_2, score)
			end
		end

		-- 支付上报
		local data = {}
		data.pay_money = DataManager.PaymentData:getPayTotal()
		data.pay_count = DataManager.PaymentData:getAllPayCount()
		BIReport:TAUserSet(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, nil, "success consume")
				SDKManager:delIosOrder(productId)
			end
			if originOrderId ~= "gm" then
				SDKManager:delIosPayInfo(originOrderId)
			end
		else
			if purchaseToken then
				SDKManager:consumePurchase(purchaseToken)
			end
		end

		if callback then
			callback(true)
		end
	end)
end

-- 三方礼包处理
function PayManager:requestThirdGiftRewards(gifts)
	local changeRechargeMap = {}
	local gem = 0
	table.foreach(gifts, function(i, gift)
		local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[gift.gift_type]
		local cfgInfo = ConfigManager:getConfig(cfgName)[gift.id]
		local rechargeId = cfgInfo.recharge_id

		if gift.gift_type == PayManager.PURCHARSE_TYPE.SHOP_GEM then
			local isDouble = DataManager.PaymentData:getGemStoreDoubleCount(gift.id) > 0
			gem = gem + cfgInfo.reward[1].num
			if isDouble then
				gem = gem + cfgInfo.reward[1].num
			end
		end

		local beforCount = DataManager.PaymentData:getPayCount()[rechargeId] or 0
		DataManager.PaymentData:addPayment(rechargeId)
		DataManager.PaymentData:updateGiftInfo(gift)
		changeRechargeMap[rechargeId] = (changeRechargeMap[rechargeId] or 0) + 1
	end)

	if gem > 0 then
		DataManager.GiftRoutineData:addScore(gem)
	end

	-- if changeRechargeMap then
	-- 	local score = 0
	-- 	local changeCount = 0
	-- 	local cfg = ConfigManager:getConfig("recharge")
	-- 	for id, count in pairs(changeRechargeMap) do
	-- 		local info = cfg[id]
	-- 		if info then
	-- 			if info.score then
	-- 				score = score + info.score * count
	-- 				changeCount = changeCount + count
	-- 			end
	-- 		end
	-- 	end

	-- 支付上报
	local data = {}
	data.pay_money = DataManager.PaymentData:getPayTotal()
	data.pay_count = DataManager.PaymentData:getAllPayCount()
	BIReport:TAUserSet(data)
end

-- 三方礼包处理
function PayManager:requestThirdJollyMaxGiftRewards(gifts)
	table.foreach(gifts, function(i, gift)
		local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[gift.gift_type]
		local cfgInfo = ConfigManager:getConfig(cfgName)[gift.id]
		DataManager.PaymentData:updateJollyMaxGiftInfo(gift)
	end)

	-- 支付上报
	local data = {}
	data.pay_money = DataManager.PaymentData:getPayTotal()
	data.pay_count = DataManager.PaymentData:getAllPayCount()
	BIReport:TAUserSet(data)
end

function PayManager:checkAndPay(productId, id, purchaseType, rechargeId, payDouble, freeShowRewards, isFromBattle)
	-- 检查是否可以支付
	SDKManager:checkPay(productId, function(code)
		if code == 0 then
			self:reqGiftPay(productId, id, purchaseType, rechargeId, payDouble, freeShowRewards, isFromBattle)
		end
	end)
end

function PayManager:reqGiftPay(productId, id, purchaseType, rechargeId, payDouble, freeShowRewards, isFromBattle, useDaiJinJuan)
	self:sendMessage(ProtoMsgType.FromMsgEnum.GiftPayReq, {id = id, gift_type = purchaseType, voucher = useDaiJinJuan == true}, function(sender, result)
		if result.err_code ~= GConst.ERROR_STR.SUCCESS then
			Logger.logError("预支付失败")
			return
		end

		local giftType = PayManager:getGiftType(purchaseType, id)
		if result.uuid and result.uuid ~= GConst.EMPTY_STRING then
			BIReport:postPayCreateOrder(giftType, id, rechargeId, result.uuid, isFromBattle, purchaseType)
			local giftType = PayManager:getGiftType(purchaseType, id)
			BIReport:postPayTurn(giftType, id, rechargeId, payDouble, isFromBattle, purchaseType)
			SDKManager:pay(productId, result.uuid, rechargeId, giftType, purchaseType, id, function(purchaseToken, orderId, originOrderId)
				if purchaseToken and orderId then
					local notShowRewardBox = freeShowRewards == false -- 原本传的是nil，默认必须展示奖励弹窗，现在改成能控制
					self:requestRewards(purchaseToken, orderId, originOrderId, productId, notShowRewardBox, nil, nil, payDouble, isFromBattle)
				end
			end, freeShowRewards)
		else -- 没有支付信息，直接发奖
			if freeShowRewards or useDaiJinJuan then
				if table.nums(result.rewards) > 0 then
					GFunc.showRewardBox(result.rewards)
				end
			end

			local giftData = {}
			giftData.gift_type = result.gift_type
			giftData.id = result.id
			giftData.buy_count = DataManager.PaymentData:getGiftBoughtNum(result.gift_type, result.id) + 1
			giftData.latest_buy_at = Time:getServerTime() -- * 1000 -- 服务器都是毫秒
			DataManager.PaymentData:updateGiftInfo(giftData, result.rewards)

			if useDaiJinJuan then -- 代金卷也要上报
				local biPayGetInfo = {}
				local changeRechargeMap = {}
				local cfgName = PayManager.PURCHARSE_TYPE_CONFIG[result.gift_type]
				local cfgInfo = ConfigManager:getConfig(cfgName)[result.id]
				local rechargeId = cfgInfo.recharge_id
				-- local beforCount = DataManager.PaymentData:getPayCount()[rechargeId] or 0
				-- DataManager.PaymentData:addPayment(rechargeId)
				table.insert(biPayGetInfo, {
					giftType = result.gift_type,
					giftId = result.id,
					rechargeId = cfgInfo.recharge_id
				})
				-- if beforCount <= 0 then
				--     BIReport:postFirstRechargeEvent(rechargeId)
				-- end
				-- BIReport:postRechargeEvent(rechargeId)
				changeRechargeMap[rechargeId] = (changeRechargeMap[rechargeId] or 0) + 1
		
				for _, info in ipairs(biPayGetInfo) do
					local giftType = self:getGiftType(info.giftType, info.giftId)
					BIReport:postPayGet(giftType, info.giftId, info.rechargeId, payDouble, "", "", 1, result.rewards or {}, isFromBattle, useDaiJinJuan, info.giftType)
				--     local rechargeCfg = ConfigManager:getConfig("recharge")[info.rechargeId]
				--     if rechargeCfg then
				--         BIReport:postPurchase(nil, rechargeCfg.price, rechargeCfg[VersionCompatible:getRechargePayId()], nil, nil)
				--     end
				end
				-- 暂时屏蔽上报
				
				if changeRechargeMap then
					local score = 0
					local changeCount = 0
					local cfg = ConfigManager:getConfig("recharge")
					for id, count in pairs(changeRechargeMap) do
						local info = cfg[id]
						if info then
							if info.score then
								score = score + info.score * count
								changeCount = changeCount + count
							end
						end
					end
					
					if score > 0 then
						-- ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_RECHARGE_SCORE, {num = score})
					end
					if changeCount > 0 then
						-- ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.X_TOTAL_RECHARGE, {num = changeCount})
					end
				end
		
				-- 支付上报
				local data = {}
				data.pay_money = DataManager.PaymentData:getPayTotal()
				data.pay_count = DataManager.PaymentData:getAllPayCount()
				BIReport:TAUserSet(data)
			end
		end
	end)
end

function PayManager:retrySendPayRecord(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback, cmdId, payDouble, isFromBattle, isSpecialOrder, wayCode)
	if self.retryPaySid then
		SchedulerManager:unscheduleGlobal(self.retryPaySid)
	end
	self.retryPaySid = SchedulerManager:performWithDelayGlobal(function()
		self.retryPaySid = nil
		if not NetManager:getIsBusy() then
			return self:requestRewards(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback, cmdId, payDouble, isFromBattle, isSpecialOrder, wayCode)
		end
		return self:retrySendPayRecord(purchaseToken, orderId, originOrderId, productId, notShowRewardsBox, callback, cmdId, payDouble, isFromBattle, isSpecialOrder, wayCode)
	end, 5)
end

function PayManager:showPayselectUI(rechargeId, callback)
	local num = DataManager.BagData.ItemData:getItemNumById(GConst.ItemConst.ITEM_ID_ACT_DAIJINJUAN)
	if num <= 0 then
		callback(false)
		return
	end

	if DataManager.PaymentData:getDefaultPayWay() == DataManager.PaymentData.PAY_WAY.DIRECTE then
		callback(false)
		return
	end

	local rechargeCfg = ConfigManager:getConfig("recharge")[rechargeId]
	if rechargeCfg and rechargeCfg.vouchers and rechargeCfg.vouchers.num <= 0 then
		callback(false)
		return
	end

	UIManager:showUI("app/ui/shop/pay_select_ui", {rechargeId = rechargeId, callback = callback})
end

--@region dukpay payProportion
-- 更新公式为：应结算美元（去所有分成）= (商品售价RUB-该笔手续费)/结算汇率
-- 目前的实际公式为:(商品售价RUB-该笔手续费)/87.42, 其中card，SBP，Tinkoff单笔支付手续费小于5RUB时，按照5RUB计算
function PayManager:calcDukPayProportion(rechargeCfg, wayCode, callback)
	local price = rechargeCfg.price_ru
	local serviceCharge = 0
	if wayCode == "BANK_CARD" then
		serviceCharge = price * 0.04
		if serviceCharge < 5 then
			serviceCharge = 5
		end
	elseif wayCode == "SBP" then
		serviceCharge = price * 0.025
		if serviceCharge < 5 then
			serviceCharge = 5
		end
	elseif wayCode == "SBER_PAY" then
		serviceCharge = price * 0.055
	elseif wayCode == "TINKOFF_PAY" then
		serviceCharge = price * 0.045
		if serviceCharge < 5 then
			serviceCharge = 5
		end
	elseif wayCode == "YOOMONEY" then
		serviceCharge = price * 0.055
	end
	local finalPrice = (price - serviceCharge)/87.42
	callback(finalPrice)
end
--@endregion

--@region hw payProportion
function PayManager:calcHWPayProportion(price, wayCode, callback)
	-- （（金额*0.96）- 5RUB*汇率（个别支付方式没有）)*0.935*0.8
	local finalPrice = price
	if not wayCode then
		callback(finalPrice)
		return
	end
	-- 花币
	local way1 = {
		["0"] = true,
		["21"] = true,
		["81"] = true,
	}
	-- Voucher
	local way2 = {
		["19"] = true,
		["45"] = true,
		["49"] = true,
	}
	-- 手机话费
	local way3 = {
		["6"] = true,
		["23"] = true,
		["70"] = true,
	}
	-- 银行卡/信用卡
	local way4 = {
		["3"] = true,
		["4"] = true,
		["13"] = true,
		["16"] = true,
		["17"] = true,
		["20"] = true,
		["24"] = true,
		["31"] = true,
		["32"] = true,
		["33"] = true,
		["34"] = true,
		["35"] = true,
		["36"] = true,
		["37"] = true,
		["38"] = true,
		["39"] = true,
		["40"] = true,
		["41"] = true,
		["42"] = true,
		["43"] = true,
		["44"] = true,
		["46"] = true,
		["47"] = true,
		["48"] = true,
		["61"] = true,
		["62"] = true,
		["63"] = true,
		["64"] = true,
		["65"] = true,
		["66"] = true,
		["67"] = true,
		["68"] = true,
		["69"] = true,
		["71"] = true,
		["72"] = true,
		["73"] = true,
		["74"] = true,
		["75"] = true,
		["76"] = true,
		["77"] = true,
		["78"] = true,
		["79"] = true,
		["80"] = true,
		["82"] = true,
		["83"] = true,
		["84"] = true,
		["85"] = true,
		["86"] = true,
		["88"] = true,
		["89"] = true,
		["90"] = true,
		["93"] = true,
		["94"] = true,
		["95"] = true,
		["97"] = true,
		["98"] = true,
		["99"] = true,
		["100"] = true,
		["102"] = true,
		["103"] = true,
		["105"] = true,
		["106"] = true,
		["108"] = true,
		["109"] = true,
		["110"] = true,
		["113"] = true,
	}
	-- 此单结算金额=(99-99*4%-99*16.67%)*85%*【0.011*(1-1.5%)】-10*【0.011*(1-1.5%)】=0.61 USD（四舍五入小数点保留后两位）
	local rate = 0.7
	if Time:getServerTime() >= 1740787200 then
		rate = 0.85
	end
	if way1[wayCode] then
		finalPrice = (price * (1 - 0.07 - 0.1667) * rate - 10) * (0.011 * 0.985)
	elseif way2[wayCode] then
		finalPrice = (price * (1 - 0.025 - 0.1667) * rate - 10) * (0.011 * 0.985)
	elseif way3[wayCode] then
		finalPrice = (price * (1 - 0.1 - 0.1667) * rate - 10) * (0.011 * 0.985)
	elseif way4[wayCode] then
		finalPrice = (price * (1 - 0.04 - 0.1667) * rate - 10) * (0.011 * 0.985)
	else
		callback(finalPrice)
		return
	end
	finalPrice = math.floor(finalPrice * 1000)
	local a = finalPrice % 10
	if a >= 5 then
		finalPrice = ((finalPrice + 10) // 10) / 100
	else
		finalPrice = (finalPrice // 10) / 100
	end
	callback(finalPrice)
end
--@endregion

return PayManager