local ShopManager = class("ShopManager", BaseModule)

ShopManager.COMMERCE_TYPE = {
	CHAPTER_GIFT = 1,
	DAILY_STORE = 2,
	GEM_STORE = 3,
	GOLD_STORE = 4,
}

ShopManager.SUMMON_ID = {
	NORMAL = 1,
	EPIC = 2,
	SSR = 3,
}

function ShopManager:showBuyGemUI()
	UIManager:showUI("app/ui/shop/buy_gem_ui")
end

function ShopManager:showFirstRechargeUI()
	UIManager:showUI("app/ui/shop/first_recharge_ui")
end

function ShopManager:showFundUI(showPage)
    UIManager:showUI("app/ui/fund/fund_main_ui", {showPage = showPage})
end

function ShopManager:showFundRewardUI(params)
    UIManager:showUI("app/ui/fund/fund_reward_ui", params)
end

function ShopManager:showThirdGiftPopUI()
	UIManager:showUI("app/ui/shop/third_gift_pop_ui")
end

function ShopManager:showVoucherReceiveUI()
	UIManager:showUI("app/ui/shop/voucher_receive_ui")
end

-- 展示竞技场ad宝箱
function ShopManager:showArenaAdBoxUI(isWin)
    local params = {
        isWin = isWin
    }
	UIManager:showUI("app/ui/shop/box_hero_ui", {arena = params})
end

-- 宝箱奖励开箱界面 type,params,rewards
function ShopManager:showBoxOpenUI(params)
    return UIManager:showUI("app/ui/shop/open_box_ui", params)
end

-- 宝箱奖励展示界面
function ShopManager:showBoxRewardUI(params)
    UIManager:showUI("app/ui/shop/box_reward_ui", params)
end

-- 章节礼包
function ShopManager:reqBuyChapterGift(id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.MallChapterBuyReq, {id = id}, self.rspBuyChapterGift, BIReport.ITEM_GET_TYPE.SHOP_CHAPTER)
end

function ShopManager:rspBuyChapterGift(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	DataManager.ShopData:onBuyChapterGiftSuccess(result.reqData.id)
end

-- 魂芯商店
function ShopManager:reqBuyCoreSoulBox(id, free, times)
    self:sendMessage(ProtoMsgType.FromMsgEnum.SoulSummonReq, {id = id, free = free, times = times}, self.rspBuyCoreSoulBox, BIReport.ITEM_GET_TYPE.SHOP_CORE_SOUL)
end

function ShopManager:rspBuyCoreSoulBox(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	DataManager.ShopData:onBuyCoreSoulBoxSuccess(result.reqData.id, result.reqData.free, result.reqData.times, result.trigger_count)
	local rewards = {}
	for _, reward in ipairs(result.rewards) do
		if reward.type == GConst.REWARD_TYPE.SOUL then
			table.insert(rewards, reward)
		end
	end
	table.sort(rewards, function(a, b)
		return a.soul.uid < b.soul.uid
	end)
	EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.CLOSE_BOX_REWARD_UI)
	local goldKeyCost = 0
	if result.reqData.id == GConst.ShopConst.CORE_SOUL_TYPE.ELITE then
		if result.costs then
			for _, cost in ipairs(result.costs) do
				if cost.item and cost.item.id == GConst.ItemConst.GOLD_KEY then
					goldKeyCost = cost.item.count
				end
			end
		end
	end

	ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.OPEN_CORE_SOUL_BOX, result.reqData, goldKeyCost)
	if result.reqData.id then
		local uiObj = self:showBoxOpenUI({type = GConst.ShopConst.BOX_REWARD_TYPE.SUMMON, openType = result.reqData.id, count = result.reqData.times, rewards = rewards})
		uiObj:addEnterAniCompleteListener(function()
			DataManager.ShopData:setDirty()
		end)
	end
	-- bi
	if result.reqData.id == GConst.ShopConst.CORE_SOUL_TYPE.NORMAL then
		BIReport:postBoxReward(BIReport.BOX_TYPE.NORMAL_BOX, result.rewards, nil, result.reqData.free, result.reqData.times)
	elseif result.reqData.id == GConst.ShopConst.CORE_SOUL_TYPE.ELITE then
		BIReport:postBoxReward(BIReport.BOX_TYPE.EPIC_BOX, result.rewards, nil, result.reqData.free, result.reqData.times)
	end
end

-- 每日商店
function ShopManager:reqBuyDailyGift(id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.MallDailyBuyReq, {id = id}, self.rspBuyDailyGift, BIReport.ITEM_GET_TYPE.SHOP_DAILY)
end

function ShopManager:rspBuyDailyGift(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	DataManager.ShopData:refreshDailyShop(result.store)
end

-- 每日商店刷新
function ShopManager:reqRefreshDailyGift(isAd)
    self:sendMessage(ProtoMsgType.FromMsgEnum.MallDailyRefreshReq, {Ad = isAd}, self.rspRefreshDailyGift, BIReport.ITEM_GET_TYPE.SHOP_DAILY_REFRESH)
end

function ShopManager:rspRefreshDailyGift(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	DataManager.ShopData:refreshDailyShop(result.store)
end

function ShopManager:reqBuyEmblemGift(id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.MallMythicBuyReq, {id = id}, self.rspBuyEmblemGift, BIReport.ITEM_GET_TYPE.SHOP_EMBLEM)
end

function ShopManager:rspBuyEmblemGift(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	DataManager.ShopData:onBuyEmblemGiftSuccess(result.reqData.id)
end

-- 金币商店
function ShopManager:reqBuyGoldGift(id)
    self:sendMessage(ProtoMsgType.FromMsgEnum.MallGoldBuyReq, {id = id}, self.rspBuyGoldGift, BIReport.ITEM_GET_TYPE.SHOP_GOLD)
end

function ShopManager:rspBuyGoldGift(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	DataManager.ShopData:onBuyGoldGiftSuccess(result.reqData.id)
end

-- 钻石商店
function ShopManager:onBuyGemGift(id, doubleType)
	PayManager:purchasePackage(id, PayManager.PURCHARSE_TYPE.SHOP_GEM, nil, doubleType)
end

-- 首冲礼包购买
function ShopManager:onBuyFirstRecharge(gear, day)
	PayManager:purchasePackage(DataManager.ShopData:getFirstRechargeGiftId(gear, day), PayManager.PURCHARSE_TYPE.ACT_GIFT, true)
end

-- 购买体力
function ShopManager:reqBuyVit(buyType)
	if buyType == GConst.VIT_BUY_TYPE.AD then
		self:sendMessage(ProtoMsgType.FromMsgEnum.EnergyByADReq, {}, self.rspBuyVit, BIReport.ITEM_GET_TYPE.BUY_VIT)
	else
		self:sendMessage(ProtoMsgType.FromMsgEnum.EnergyByDiamondReq, {}, self.rspBuyVit, BIReport.ITEM_GET_TYPE.BUY_VIT)
	end
end

function ShopManager:rspBuyVit(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	DataManager.ShopData:onVitBuySuccess(result.energy_limit)
	-- 累计购买体力X次
	ModuleManager.TaskManager:addTaskProgress(GConst.TaskConst.TASK_TYPE.BUY_VIT_NUM)
end

function ShopManager:checkWebPurchaseGift()
	if DataManager.TutorialData:getIsInTutorial() then
		return false
	end
	if DataManager.ShopData:getNeedShowGiftReceiveUI() then
		ModuleManager.ShopManager:showThirdGiftPopUI()
		return true
	end
	return false
end

--@region 领取三方支付礼包
function ShopManager:receiveWebPurchaseGiftRewards()
	local orders = DataManager.ShopData:getThirdPayGiftOrders()
	local orderIds = {}
	for k, v in ipairs(orders) do
		table.insert(orderIds,  v.order_id)
	end
	local parmas = {
		order_ids = orderIds
	}
	self:sendMessage(ProtoMsgType.FromMsgEnum.ThirdPayGiftReq, parmas, self.onReceiveWebPurchaseGiftRewards, BIReport.ITEM_GET_TYPE.WEB_PAY_GIFT)
end

function ShopManager:onReceiveWebPurchaseGiftRewards(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	if result.rewards then
		GFunc.showRewardBox(result.rewards)
	end
	local isJollyMax = false
	for k, v in ipairs(result.reqData.order_ids) do
		local orderInfo = DataManager.ShopData:getThirdPayGiftOrderInfo(v)
		if orderInfo then
			local cfg
			local rewards
			local giftId = orderInfo.gift_id
			if orderInfo.gift_type == PayManager.PURCHARSE_TYPE.ACT_GIFT then
				cfg = ConfigManager:getConfig("act_gift")[giftId]
				rewards = cfg.reward
			elseif orderInfo.gift_type == PayManager.PURCHARSE_TYPE.GIFT_ROUTINE then
				cfg = ConfigManager:getConfig("gift_routine")[giftId]
				rewards = cfg.reward
			elseif orderInfo.gift_type == PayManager.PURCHARSE_TYPE.SHOP_GEM then
				cfg = ConfigManager:getConfig("mall_treasure")[giftId]
				rewards = {}
				if cfg.reward then
					for i,v in ipairs(cfg.reward) do
						table.insert(rewards, v)
					end
					if DataManager.PaymentData:isGemStoreDouble(giftId) then
						for i,v in ipairs(cfg.reward) do
							table.insert(rewards, v)
						end
					end
				end
			elseif orderInfo.gift_type == PayManager.PURCHARSE_TYPE.GIFT_JOLLYMAX then
				cfg = ConfigManager:getConfig("gift_jollymax")[giftId]
				rewards = cfg.reward
				isJollyMax = true
			end
			if isJollyMax or VersionCompatible:getIsRUPackage() then
				-- local rCfg = ConfigManager:getConfig("recharge")[cfg.recharge_id]
				-- local productId = rCfg[VersionCompatible:getRechargePayId()]
				local productId = cfg.goods_id
				BIReport:postReceiveThirdPayJollyMaxGiftRewards(orderInfo.order_id, productId, orderInfo.gift_id, orderInfo.revenue, rewards, cfg.price)
				BIReport:postJollyMaxPurchase(orderInfo.revenue, productId, orderInfo.order_id)
			else
				local rCfg = ConfigManager:getConfig("recharge")[cfg.recharge_id]
				local productId = rCfg[VersionCompatible:getRechargePayId()]
				BIReport:postReceiveThirdPayGiftRewars(orderInfo.order_id, productId, orderInfo.gift_id, orderInfo.revenue, rewards, rCfg.price)
				BIReport:postVTCPurchase(orderInfo.revenue, productId, orderInfo.order_id)
			end
		end
	end
	-- 购买礼包后续处理
	if isJollyMax or VersionCompatible:getIsRUPackage() then
		PayManager:requestThirdJollyMaxGiftRewards(result.gifts or {})
	else
		PayManager:requestThirdGiftRewards(result.gifts or {})
	end
	DataManager.ShopData:deleteThirdPayGiftOrders(result.reqData.order_ids)
	EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.RECEIVE_WEB_PURCHASE_REWARDS_SUCCESS)
end
--@endregion

function ShopManager:checkWebPurchase()
	if DataManager.TutorialData:getIsInTutorial() then
		return false
	end
	if DataManager.ShopData:getNeedShowVoucherReceiveUI() then
		self:showVoucherReceiveUI()
		return true
	end
	return false
end

function ShopManager:receiveWebPurchaseRewards()
	local orders = DataManager.ShopData:getThirdPayOrders()
	local orderIds = {}
	for k, v in ipairs(orders) do
		table.insert(orderIds,  v.order_id)
	end
	local parmas = {
		order_ids = orderIds
	}
	self:sendMessage(ProtoMsgType.FromMsgEnum.ThirdPayClaimReq, parmas, self.onReceiveWebPurchaseRewards, BIReport.ITEM_GET_TYPE.WEB_PAY)
end

function ShopManager:onReceiveWebPurchaseRewards(result)
	if result.err_code ~= GConst.ERROR_STR.SUCCESS then
		return
	end

	GFunc.showRewardBox(result.rewards)
	for k, v in ipairs(result.reqData.order_ids) do
		local orderInfo = DataManager.ShopData:getThirdPayOrderInfo(v)
		if orderInfo then
			BIReport:postReceiveThirdPayRewars(orderInfo.order_id, orderInfo.voucher, orderInfo.product_id, orderInfo.revenue, orderInfo.price)
			BIReport:postWebPurchase(orderInfo.revenue, orderInfo.product_id, orderInfo.order_id)
		end
	end
	DataManager.ShopData:deleteThirdPayOrders(result.reqData.order_ids)
	EventManager:dispatchEvent(EventManager.CUSTOM_EVENT.RECEIVE_WEB_PURCHASE_REWARDS_SUCCESS)
end

return ShopManager