local SDKPayGoogleManager = {}

local PAY_TYPE_IN_APP = "inapp"
local PAY_TYPE_SUBS = "subs"

function SDKPayGoogleManager:init()
end

function SDKPayGoogleManager:needInit()
	return true
end

function SDKPayGoogleManager:initPay(callback)
	self.products = {}
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:SetGoogleDelayPayCallback(SDKPayGoogleManager.onGooglePayDelayCallback)
	if callback then
		callback()
	end
end

-- 这里定义的时候不能使用冒号，否则参数不对
function SDKPayGoogleManager.onGooglePayDelayCallback(code, msg)
	if code == 0 and msg and msg ~= "" then
		Logger.log("延迟支付到账:%s", msg)
		local result = json.decode(msg)
		local purchaseToken = result.purchaseToken
		if purchaseToken == nil or purchaseToken == "" then
			return
		end
		if result.obfuscatedAccountId then
			PayManager:requestRewards(purchaseToken, result.obfuscatedAccountId, result.orderId, result.productId)
		end
	end
end

-- 查询付费产品信息
function SDKPayGoogleManager:queryProducts(callback)
	if self.queryProductsOver then -- 已经查询成功过了
		if callback then
			callback()
		end
	else
		local rechargeCfg = ConfigManager:getConfig("recharge")
		if rechargeCfg then
			local inAppList = {} -- 内购类
			local subsList = {} -- 订阅list
			for _, rechargeInfo in ipairs(rechargeCfg) do
				if rechargeInfo.subscribe then
					table.insert(subsList, rechargeInfo.payId)
				else
					table.insert(inAppList, rechargeInfo.payId)
				end
			end
			self.products = {}
			self:queryProductInfo(PAY_TYPE_IN_APP, json.encode(inAppList), function(code, msg)
				if code == 0 then
					if msg and msg ~= "" then -- 更新products
						Logger.logHighlight(msg)
						local jData = json.decode(msg)
						if jData and #jData > 0 then
							for i = 1, #jData do
								table.insert(self.products, jData[i])
							end
						end
					end
					if #subsList > 0 then
						self:queryProductInfo(PAY_TYPE_SUBS, json.encode(subsList), function(code, msg)
							if code == 0 then
								self.queryProductsOver = true
								if msg and msg ~= "" then -- 更新products
									local jData = json.decode(msg)
									if jData and #jData > 0 then
										for i = 1, #jData do
											table.insert(self.products, jData[i])
										end
									end
								end
								if callback then
									callback()
								end
							end
						end)
					else
						self.queryProductsOver = true
						if callback then
							callback()
						end
					end
				end
			end)
		end
	end
end

-- 商品数据
function SDKPayGoogleManager:queryProductInfo(payType, json, callback)
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:QueryProductInfo(payType, json, function(code, msg)
		SDKManager:doNextFrame(function()
			callback(code, msg)
		end)
	end)
end

-- 未完成的订单请求服务器 completeOrderState状态:
-- 0表示未完成订单消耗完成
-- 1表示存在和指定productId相同的支付中的订单
-- 2表示存在和指定productId相同的无法成功消耗的订单
-- 3表示存在无法成功消耗的订单，但是其中没有和指定productId相同
function SDKPayGoogleManager:reqPayReward(uncompleteList, productId, callback)
	local index = 1
	local completeOrderState = 0
	local function handleOrder(uncompleteOrder)
		if uncompleteOrder == nil then
			if callback then
				callback(completeOrderState)
			end
			return
		end
		if uncompleteOrder.purchaseState == "2" then
			-- 处理中的订单
			index = index + 1
			if uncompleteOrder.productId and uncompleteOrder.productId ~= "" and uncompleteOrder.productId == productId then
				-- 存在和指定productId相同的支付中的订单
				completeOrderState = 1
			end
			handleOrder(uncompleteList[index])
		elseif uncompleteOrder.purchaseToken then
			-- 去服务器验证
			if uncompleteOrder.obfuscatedAccountId then
				PayManager:requestRewards(uncompleteOrder.purchaseToken, uncompleteOrder.obfuscatedAccountId, uncompleteOrder.orderId, uncompleteOrder.productId, true, function()
					index = index + 1
					handleOrder(uncompleteList[index])
				end)
			else
				self:consumePurchase(uncompleteOrder.purchaseToken, function()
					index = index + 1
					handleOrder(uncompleteList[index])
				end)
			end
		else
			index = index + 1
			handleOrder(uncompleteList[index])
		end
	end
	handleOrder(uncompleteList[index])
end

-- 处理未完成的订单
function SDKPayGoogleManager:doUncompleteOrder(callback, productId)
	self:queryUncompleteOrder(function(list)
		if list and type(list) == "table" and #list > 0 then
			self:reqPayReward(list, productId, callback)
		else -- 没有未完成的订单
			if callback then
				callback(0)
			end
		end
	end)
end

-- 查询未完成的订单
function SDKPayGoogleManager:queryUncompleteOrder(callback)
	local list  -- 查询到的数据,整合了内购
	-- 查找内购
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:QueryUncompleteOrder(PAY_TYPE_IN_APP, function(code, msg)
		-- 此查询接口没有失败的情况
		if msg and msg ~= "" then
			list = json.decode(msg)
		end

		if callback then
			callback(list)
		end
	end)
end

-- 订阅到期查询订阅状态
function SDKPayGoogleManager:querySubscribeInfo()
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:QueryUncompleteOrder(PAY_TYPE_SUBS, function(code, msg)
		-- 此查询接口没有失败的情况
		local subsList
		if msg and msg ~= "" then
			subsList = json.decode(msg)
		end
		if subsList then
			for _, order in ipairs(subsList) do
				if order.purchaseState == 1 then -- 已购买
					local args = {
						purchase_token = order.purchaseToken,
						order_id = order.obfuscatedAccountId
					}
					break
				end
			end
		end
	end)
end

function SDKPayGoogleManager:queryProducePrice()
	return self.products
end

function SDKPayGoogleManager:gotProduct()
	return true
end

-- sdk接口 得到特定商品的price
function SDKPayGoogleManager:getProductPrice(skuId)
	if self.products and #self.products > 0 then
		for _, data in ipairs(self.products) do
			if data.sku == skuId then
				return data.price
			end
		end
	end
	return nil
end

-- sdk接口 得到特定商品的priceAmountMicros
function SDKPayGoogleManager:getProductPriceAmountMicros(skuId)
	if self.products and #self.products > 0 then
		for _, data in ipairs(self.products) do
			if data.sku == skuId then
				return data.priceAmountMicros
			end
		end
	end
	return nil
end

-- sdk接口 得到特定商品的currency_code
function SDKPayGoogleManager:getPriceCurrencyCode(skuId)
	if self.products and #self.products > 0 then
		for _, data in ipairs(self.products) do
			if data.sku == skuId then
				return data.priceCurrencyCode
			end
		end
	end
	return nil
end

function SDKPayGoogleManager:getSDKPayType()
	return SDKManager.PAY_TYPE.GOOGLE
end

function SDKPayGoogleManager:getPurchaseArgs(purchaseToken, uuid, channelOrderId, productId)
	local args = {
		channel = self:getSDKPayType(),
		params = {purchaseToken, productId}
	}
	return args
end

-- 获取支付方式,目前只有google支付
function SDKPayGoogleManager:getIsSupportSDKPay()
	return true
end

function SDKPayGoogleManager:_getIsGoogleStoreConnected()
	return CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr.ConnectStoreSucc
end

-- 检查是否可以支付
function SDKPayGoogleManager:checkPay(productId, callback)
	if self:_getIsGoogleStoreConnected() then -- google商店是否初始化
		self:queryProducts(function()
			self:doUncompleteOrder(function(code) -- 先处理未完成的订单
				if code == 0 then
					callback(0)
				elseif code == 1 then -- 指定的productId存在支付状态中的订单
					local params = {
						content = I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_23),
						boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
						okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
					}
					GFunc.showMessageBox(params)
				elseif code == 2 then -- 指定的productId存在未完成的订单消耗失败的情况
					local params = {
						content = I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_23),
						boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
						okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
					}
					GFunc.showMessageBox(params)
				else -- 存在未完成的订单消耗失败的情况，但是因为不是当前productId，所以允许继续支付
					callback(0)
				end
			end, productId)
		end)
	else
		self:connectGoogleStore(function(code)
			if code == 0 then
				self:queryProducts(function()
					self:doUncompleteOrder(function(consumeSucc)
						if code == 0 then
							callback(0)
						elseif code == 1 then -- 指定的productId存在支付状态中的订单
							local params = {
								content = I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_23),
								boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
								okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
							}
							GFunc.showMessageBox(params)
						elseif code == 2 then -- 指定的productId存在未完成的订单消耗失败的情况
							local params = {
								content = I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_23),
								boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
								okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
							}
							GFunc.showMessageBox(params)
						else -- 存在未完成的订单消耗失败的情况，但是因为不是当前productId，所以允许继续支付
							callback(0)
						end
					end, productId)
				end)
			else
				local params = {
					content = I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_22),
					boxType = GConst.MESSAGE_BOX_TYPE.MB_OK,
					okText = I18N:getGlobalText(I18N.GlobalConst.BTN_TEXT_OK),
				}
				GFunc.showMessageBox(params)
			end
		end)
	end
end

-- 支付
function SDKPayGoogleManager:pay(productId, orderId, rechargeId, giftType, purchaseType, giftId, callback)
	self:doGooglePay(productId, orderId, rechargeId, giftType, purchaseType, giftId, callback)
end

-- 连接Google商店
function SDKPayGoogleManager:connectGoogleStore(callback)
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:ConnectGoogleStore(function(code)
		SDKManager:doNextFrame(function()
			callback(code)
		end)
	end)
end

function SDKPayGoogleManager:doGooglePay(productId, orderId, rechargeId, giftType, purchaseType, giftId, callback)
	local payType = PAY_TYPE_IN_APP
	local rechargeCfg = ConfigManager:getConfig("recharge")[rechargeId]
	if rechargeCfg.subscribe then
		payType = PAY_TYPE_SUBS
	end
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:Pay(payType, productId, orderId, function(code, msg)
		if code == 0 then
			-- 支付成功
			Logger.log("pay success:%s", msg)
			local result = json.decode(msg)
			if callback then
				callback(result.purchaseToken, result.obfuscatedAccountId, result.orderId)
			end
		elseif code == 1 then
			-- 支付取消
			GFunc.showToast(I18N:getGlobalText(I18N.GlobalConst.SETTING_DESC_25))
			BIReport:postPayCancel(productId, orderId, rechargeId, giftType, giftId)
		else
			-- 支付失败
			Logger.log("pay failed")
			BIReport:postPayFailed(productId, orderId, rechargeId, msg or GConst.EMPTY_STRING, giftType, giftId)
		end
	end)
end

-- sdk将已完成的订单消耗掉
function SDKPayGoogleManager:consumePurchase(token, callback)
	if not token then
		return
	end
	CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr:ConsumePurchase(token, function(code, msg)
		if code == 0 then
			Logger.log("consume %s success", token)
		else
			Logger.log("consume %s failed", token)
		end
		if callback then
			callback(code)
		end
	end)
end

function SDKPayGoogleManager:doUncompletePay(callback)
	-- 每次游戏的过程中只处理一次
	if self.alreadyFinishUncompletePay then
		return
	end
	if not DataManager:getLoginSuccess() then
		return
	end
	-- if NetManager:getIsBusy() then
	-- 	return
	-- end
	if self:_getIsGoogleStoreConnected() then
		-- google商店是否初始化
		self.alreadyFinishUncompletePay = true
		SDKManager:queryProducts(function()
			SDKManager:doUncompleteOrder()
		end)
	end
end

return SDKPayGoogleManager
