local SDKPayiOSManager = {}

function SDKPayiOSManager:init()
	self.iosPayInfos = LocalData:getIosPayInfo()
	self.iosOrders = LocalData:getIosOrders()
end

function SDKPayiOSManager:needInit()
	return true
end

function SDKPayiOSManager:initPay(callback)
	self.products = {}
	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr.initCallback = function (isSuccess, products, errorStr)
		if isSuccess then
			-- GFunc.showToast("初始化成功")
			if callback then
				callback()
			end
			BIReport:postPayInitSuccess()
		else
			Logger.log(errorStr)
			BIReport:postPayInitFailed(errorStr)
		end
	end

	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr.buyCallback = function(isSuccess, result, errorStr)
		if isSuccess then
			if self.handleUncompleteIosOrder then
			    local payParams = self.iosPayInfos[result.transactionID]
			    local needConsumePurchase = true
			    if payParams ~= nil and payParams.order then
					PayManager:requestRewards(result.receipt, payParams.order, result.transactionID, payParams.productId)
					needConsumePurchase = false
			    end
			    if needConsumePurchase then
			        self:delIosPayInfo(result.transactionID)
			        self:delIosOrder(result.definition.id)
			        self:consumePurchase(result.definition.id)
					local giftId = tonumber(payParams.giftId)
					local purchaseType = tonumber(payParams.purchaseType)
					local giftType = PayManager:getGiftType(purchaseType, giftId)
					local rechargeId = PayManager:getPackageRechargeId(purchaseType, giftId)
			        BIReport:postPayFailed(result.definition.id, result.transactionID, rechargeId, "error order", giftType, giftId)
			    end
			else
			    -- 回调时机太早的话，就先保存起来，等后续补单的时候一起补
			    local order = self.iosOrders[result.definition.id]
			    if order then
			        self:saveIosPayInfo(result.transactionID, result.receipt, order.order, result.definition.id, order.purchaseType, order.giftId)
			        self:delIosOrder(result.definition.id)
			    else
			        -- 之前没有记录只能算掉单了
			        self:delIosPayInfo(result.transactionID)
			        self:delIosOrder(result.definition.id)
			        self:consumePurchase(result.definition.id)
			        BIReport:postPayFailed(result.definition.id, result.transactionID, nil, "not have order")
			    end
			end
		else
			if errorStr and errorStr ~= "" then
			    BIReport:postPayFailed(result.definition.id, result.transactionID, nil, errorStr)
			else
			    BIReport:postPayFailed(result.definition.id, result.transactionID, nil, "1")
			end
		end
	end

	local rechargeCfg = ConfigManager:getConfig("recharge")
	local products = {}
	for i,v in ipairs(rechargeCfg) do
		table.insert(products, {productId = v.payId, type = CS.UnityEngine.Purchasing.ProductType.Consumable})
	end
	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr:Init(products)
end

function SDKPayiOSManager:queryProducePrice()
	if self.products and #self.products > 0 then
		return self.products
	end
	local rechargeCfg = ConfigManager:getConfig("recharge")
	self.products = {}
	for _, v in ipairs(rechargeCfg) do
		local price = CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr:GetLocalizedPrice(v.payId)
		if price and price ~= "" then
			Logger.log("product = %s, price = %s", v.payId, price)
			table.insert(self.products, {sku = v.payId, price = price})
		end
	end
	return self.products
end

function SDKPayiOSManager:queryProducts()
end

-- 处理未完成的订单
function SDKPayiOSManager:doUncompleteOrder(callback, productId)
	self.handleUncompleteIosOrder = true
	if self.handleUncompleteOrder then
		return callback and callback(1)
	end
	self.handleUncompleteOrder = true
	local orders = self.iosPayInfos
	if orders == nil then
		self.handleUncompleteOrder = false
		return callback and callback()
	end
	local uncompleteList = {}
	for _, v in pairs(orders) do
		table.insert(uncompleteList, v)
	end
	if #uncompleteList <= 0 then
		self.handleUncompleteOrder = false
		return callback and callback()
	end
	local index = 1
	local function handleOrder(uncompleteOrder)
		if uncompleteOrder == nil then
			self.handleUncompleteOrder = false
			return callback and callback()
		end
		-- 去服务器验证
		if uncompleteOrder.order then
			PayManager:requestRewards(uncompleteOrder.receipt, uncompleteOrder.order, uncompleteOrder.transactionID, uncompleteOrder.productId, true, function()
				index = index + 1
				handleOrder(uncompleteList[index])
			end)
		else
			SDKManager:delIosPayInfo(uncompleteOrder.transactionID)
			SDKManager:delIosOrder(uncompleteOrder.productId)
			self:consumePurchase(uncompleteOrder.productId, function()
				index = index + 1
				handleOrder(uncompleteList[index])
			end)
		end
	end
	handleOrder(uncompleteList[index])
end

-- 查询未完成的订单
function SDKPayiOSManager:queryUncompleteOrder(callback)
end

-- 订阅到期查询订阅状态
function SDKPayiOSManager:querySubscribeInfo()
end

function SDKPayiOSManager:gotProduct()
	if self.products and #self.products > 0 then
		return true
	end
	return false
end

-- sdk接口 得到商品的price
function SDKPayiOSManager: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 SDKPayiOSManager: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 SDKPayiOSManager: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 SDKPayiOSManager:getSDKPayType()
	return SDKManager.PAY_TYPE.DEPRECATED_APPLE
end

function SDKPayiOSManager:getPurchaseArgs(purchaseToken, uuid, channelOrderId, productId)
	local purchaseTokenObj = json.decode(purchaseToken)
	if purchaseTokenObj == nil then
		return -- 解析错误
	end
	local args = {
		channel = self:getSDKPayType(),
		params = {purchaseTokenObj.Payload, channelOrderId, uuid}
	}
	return args
end

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

function SDKPayiOSManager:getIsGoogleStoreConnected()
	return CS.BF.BFMain.Instance.SDKMgr.BFPaySDKMgr.ConnectStoreSucc
end

function SDKPayiOSManager:_getIsIosInitialized()
	return CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr:IsInitialized()
end

-- 检查是否可以支付
function SDKPayiOSManager:checkPay(productId, callback)
	if self:_getIsIosInitialized() then
		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)
	end
end

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

-- sdk将已完成的订单消耗掉
function SDKPayiOSManager:consumePurchase(productId, callback)
	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr:ConsumePurchase(productId)
	if callback then
		callback(0)
	end
end

function SDKPayiOSManager:doIosPay(productId, orderId, rechargeId, giftType, purchaseType, giftId, callback)
	self.blockTouch = true
	UIManager:showWaitPay()
	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr.buyCallback = function(isSuccess, result, errorStr)
		if self.blockTouch then
			self.blockTouch = false
			UIManager:hideWaitPay()
			if isSuccess then
				Logger.log("ios pay availableToPurchase = %s", result.availableToPurchase)
				Logger.log("ios pay transactionID = %s", result.transactionID)
				Logger.log("ios pay hasReceipt = %s", result.hasReceipt)
				Logger.log("ios pay receipt = %s", result.receipt)
				self:saveIosPayInfo(result.transactionID, result.receipt, orderId, productId, purchaseType, giftId)
				if callback then
					callback(result.receipt, orderId, result.transactionID)
				end
			else
				if errorStr and errorStr ~= "" then
					BIReport:postPayFailed(productId, orderId, rechargeId, errorStr, giftType, giftId)
				else
					BIReport:postPayFailed(productId, orderId, rechargeId, "1", giftType, giftId)
				end
			end
			self:delIosOrder(productId)
		else -- 说明是其他未完成回调
			local payParams = self.iosPayInfos[result.transactionID]
			local needConsumePurchase = true
			if payParams ~= nil and payParams.order then
				PayManager:requestRewards(result.receipt, payParams.order, result.transactionID, payParams.productId)
				needConsumePurchase = false
			end
			if needConsumePurchase then
			    local order = self.iosOrders[result.definition.id]
			    if order then
					PayManager:requestRewards(result.receipt, order.order, result.transactionID, result.definition.id)
			    else
			        self:delIosPayInfo(result.transactionID)
					self:delIosOrder(result.definition.id)
					self:consumePurchase(result.definition.id)
					local giftId = tonumber(payParams.giftId)
					local purchaseType = tonumber(payParams.purchaseType)
					local giftType = PayManager:getGiftType(purchaseType, giftId)
					local rechargeId = PayManager:getPackageRechargeId(purchaseType, giftId)
					BIReport:postPayFailed(result.definition.id, result.transactionID, rechargeId, "error order", giftType, giftId)
			    end
			end
		end
	end
	self:saveIosOrder(productId, orderId, purchaseType, giftId)
	CS.BF.BFMain.Instance.SDKMgr.IosPaySDKMgr:Buy(productId, orderId)
end

function SDKPayiOSManager:doUncompletePay(callback)
	-- 每次游戏的过程中只处理一次
	if self.alreadyFinishUncompletePay then
		return
	end
	if not DataManager:getLoginSuccess() then
		return
	end
	-- if NetManager:getIsBusy() then
	-- 	return
	-- end

	if self:_getIsIosInitialized() then
		self.alreadyFinishUncompletePay = true
		self:doUncompleteOrder()
	end
end

function SDKPayiOSManager:checkPurchaseOrder(result, productId, callback)
end

function SDKPayiOSManager:saveIosPayInfo(transactionID, receipt, order, productId, purchaseType, giftId)
	self.iosPayInfos[transactionID] = {
		order = order,
		receipt = receipt,
		transactionID = transactionID,
		productId = productId,
		purchaseType = purchaseType,
		giftId = giftId
	}
	LocalData:setIosPayInfo(self.iosPayInfos)
	LocalData:save()
end

function SDKPayiOSManager:delIosPayInfo(transactionID)
	self.iosPayInfos[transactionID] = nil
	LocalData:setIosPayInfo(self.iosPayInfos)
	LocalData:save()
end

function SDKPayiOSManager:getIosPayInfo(transactionID)
	return self.iosPayInfos[transactionID]
end

function SDKPayiOSManager:saveIosOrder(productId, order, purchaseType, giftId)
	self.iosOrders[productId] = {
		order = order,
		purchaseType = purchaseType,
		giftId = giftId
	}
	LocalData:setIosOrders(self.iosOrders)
	LocalData:save()
end

function SDKPayiOSManager:delIosOrder(productId)
	self.iosOrders[productId] = nil
	LocalData:setIosOrders(self.iosOrders)
	LocalData:save()
end

return SDKPayiOSManager
