local SummonShopBoxUI = class("SummonShopBoxUI", BaseUI)
local REWARD_BOX_CELL = "app/ui/tips/cell/reward_box_cell"

function SummonShopBoxUI:isFullScreen()
	return false
end
function SummonShopBoxUI:currencyParams()
	local params = {}
	params.showType = GConst.CURRENCY_TYPE.HORIZONTAL
	params.itemIds = {
		self.shopItemId,
	}
	return params, true
end
function SummonShopBoxUI:showCommonBG()
	return false
end

function SummonShopBoxUI:getPrefabPath()
	return "assets/prefabs/ui/summon/summon_shop_box_ui.prefab"
end

function SummonShopBoxUI:onPressBackspace()
	self:closeUI()
end

function SummonShopBoxUI:onClose()
end

function SummonShopBoxUI:ctor(params)
	self.shopType = params.shopType
	if self.shopType == 1 then
		self.shopItemId = GConst.ItemConst.ITEM_ID_SUMMON_SHOP_GOLD_COMMON
	elseif self.shopType == 2 then
		self.shopItemId = GConst.ItemConst.SUMMON_SHOP_GOLD_ACT
	elseif self.shopType == 3 then
		self.shopItemId = GConst.ItemConst.SOUL_SHOP_GOLD
	end

	self.cfg = params.cfg

	self.curCount = 1
	local cost = GFunc.getRewardNum(self.cfg.cost)               --原价
	if self.cfg.discount ~= nil then
		self.discount = GFunc.getRewardNum(self.cfg.discount)      --折扣价
	end
	self.costId = GFunc.getRewardId(self.cfg.cost)

	self.discountLimit = self.cfg.discount_limit       --折扣次数

	local haveItemNum = DataManager.BagData.ItemData:getItemNumById(self.costId)     --拥有货币
	local exchangesCount = DataManager.SummonData:getExchangesCount(self.cfg.id)    --购买次数

	 -- 计算剩余折扣次数
	self.remainingDiscount = 0
	if self.discountLimit ~= nil then
		self.remainingDiscount = math.max(0, self.discountLimit - exchangesCount)
	end
	-- 计算最大可购买数量
	self.maxCount = 0
	if haveItemNum > 0 then
		local remainingMoney = haveItemNum  -- 剩余货币
		-- 1. 优先用折扣价购买（如果还有折扣次数）
		if self.remainingDiscount > 0 and self.discount then
			local canBuyWithDiscount = math.min(math.floor(remainingMoney / self.discount), self.remainingDiscount)
			self.maxCount = self.maxCount + canBuyWithDiscount
			remainingMoney = remainingMoney - canBuyWithDiscount * self.discount
		end

		-- 2. 如果还有钱，继续用原价购买
		if remainingMoney >= cost then
			self.maxCount = self.maxCount + math.floor(remainingMoney / cost)
		end
	end
	self.maxCount = math.max(1, self.maxCount)
end

function SummonShopBoxUI:onLoadRootComplete()
	local uiMap = self.root:genAllChildren()
	self.btnMaskClose = uiMap["summon_shop_box_ui.btn_mask_close"]
	self.content = uiMap["summon_shop_box_ui.content"]
	self.btnClose = uiMap["summon_shop_box_ui.content.btn_close"]
	self.txTitle = uiMap["summon_shop_box_ui.content.tx_title"]
	self.infoNode = uiMap["summon_shop_box_ui.content.info_node"]
	self.rewardCell = uiMap["summon_shop_box_ui.content.info_node.reward_cell"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.REWARD_CELL)
	self.txName = uiMap["summon_shop_box_ui.content.info_node.data_node.tx_name"]
	self.txCount = uiMap["summon_shop_box_ui.content.info_node.data_node.tx_count"]
	self.dataLayout = uiMap["summon_shop_box_ui.content.info_node.data_node"]:getComponent(GConst.TYPEOF_UNITY_CLASS.BF_HORIZONTAL_OR_VERTICAL_LAYOUT)

	self.scrollRectObj = uiMap["summon_shop_box_ui.content.info_node.data_node.scrollrect"]
	self.scrollRect = uiMap["summon_shop_box_ui.content.info_node.data_node.scrollrect"]:addLuaComponent(GConst.TYPEOF_LUA_CLASS.SCROLL_RECT_BASE)
	self.select = uiMap["summon_shop_box_ui.content.select"]
	self.txSelect = uiMap["summon_shop_box_ui.content.select.tx_select"]
	self.btnSub = uiMap["summon_shop_box_ui.content.select.btn_sub"]
	self.btnAdd = uiMap["summon_shop_box_ui.content.select.btn_add"]
	self.btnMax = uiMap["summon_shop_box_ui.content.select.btn_max"]
	self.btnMin = uiMap["summon_shop_box_ui.content.select.btn_min"]
	self.btnBuy = uiMap["summon_shop_box_ui.content.btn_buy"]
	self.txBuy = uiMap["summon_shop_box_ui.content.btn_buy.tx_buy"]
	self.iconCost = uiMap["summon_shop_box_ui.content.btn_buy.icon_cost"]

	self.discount = uiMap["summon_shop_box_ui.content.btn_buy.discount"]
	self.txDiscount = uiMap["summon_shop_box_ui.content.btn_buy.discount.tx_discount"]

	self.txTitle:setText(I18N:getGlobalText(I18N.GlobalConst.SUMMON_DESCR_4))


	self.btnSub:addClickListener(function()
		if self.curCount <= 1 then
			return
		end
		self.curCount = self.curCount - 1
		self:refreshCount()
	end)
	self.btnAdd:addClickListener(function()
		if self.curCount >= self.maxCount then
			return
		end
		self.curCount = self.curCount + 1
		self:refreshCount()
	end)
	self.btnMax:addClickListener(function()
		if self.curCount >= self.maxCount then
			return
		end
		self.curCount = self.maxCount
		self:refreshCount()
	end)
	self.btnMin:addClickListener(function()
		if self.curCount <= 1 then
			return
		end
		self.curCount = 1
		if self.curCount > self.maxCount then
			self.curCount = self.maxCount
		end
		self:refreshCount()
	end)
	self.btnBuy:addClickListener(function()
		local haveItemNum = DataManager.BagData.ItemData:getItemNumById(self.costId)
		if haveItemNum < self.totalCost then
			GFunc.showItemNotEnough(self.costId)
			return
		end
		ModuleManager.SummonManager:reqForceSummonShopExchange(self.cfg.id, self.curCount)
		self:closeUI()
	end)
	self.btnMaskClose:addClickListener(function()
		self:closeUI()
	end)
	self.btnClose:addClickListener(function()
		self:closeUI()
	end)
end

function SummonShopBoxUI:onRefresh()
	self.rewardCell:refreshByConfig(self.cfg.hero)
	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_1, self.ownCount))
	if self.remainingDiscount > 0 and self.discountLimit ~= nil then
		self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.SUMMON_DESCR_7, self.remainingDiscount, self.discountLimit))
		self.txName:setAnchoredPositionY(33)
	else
		self.txCount:setText(GConst.EMPTY_STRING)
		self.txName:setAnchoredPositionY(0)
	end
	self.rewardId = GFunc.getRewardId(self.cfg.hero)
	self.itemType = ModuleManager.ItemManager:getItemType(self.rewardId)
	self.rewards = nil
	-- if self.itemType == GConst.ItemConst.ITEM_TYPE.BOX_RANDOM then
	-- 	-- 随机宝箱
	-- 	self.rewards = cfg and cfg.box_drop
	-- 	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_5))
	-- elseif self.itemType == GConst.ItemConst.ITEM_TYPE.FORCE_RANDOM then
	-- 	-- 随机宝箱
	-- 	self.rewards = cfg and cfg.box_drop
	-- 	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_5))
	-- elseif self.itemType == GConst.ItemConst.ITEM_TYPE.BOX_EQUIP then
	-- 	self.rewards = cfg and cfg.box_select
	-- 	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_4))
	-- elseif self.itemType == GConst.ItemConst.ITEM_TYPE.BOX_SELECT then
	-- 	-- 自选宝箱
	-- 	self.rewards = cfg and cfg.box_select
	-- 	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_4))
	-- elseif self.itemType == GConst.ItemConst.ITEM_TYPE.BOX_RANDOM_MERGE then
	-- 	-- 随机合成宝箱
	-- 	self.rewards = cfg and cfg.box_drop
	-- 	self.txCount:setText(I18N:getGlobalText(I18N.GlobalConst.ITEM_DESC_5))
	-- end
	if self.itemType == GConst.ItemConst.ITEM_TYPE.HERO_FRAGMENT then
		local heroCfg = ConfigManager:getConfig("hero")[self.rewardId]
		local str = GFunc.colorText(GConst.QUALITY_TYPE[heroCfg.qlt], ModuleManager.ItemManager:getItemName(self.rewardId))
		self.txName:setText(str)
	else
		local itemCfg = ConfigManager:getConfig("item")[self.rewardId]
		local str = GFunc.colorText(GConst.QUALITY_TYPE[itemCfg.qlt], ModuleManager.ItemManager:getItemName(self.rewardId))
		self.txName:setText(str)
	end
	if self.rewards ~= nil then
		self.scrollRectObj:setActive(true)
		self:_refreshScrollrect()
	else
		self.scrollRectObj:setActive(false)
	end
	self.dataLayout:RefreshLayout()
	self:refreshCount()
end

--刷新滑动列表
function SummonShopBoxUI:_refreshScrollrect()
	if not self.initScrollrect then
		self.initScrollrect = true

		self.scrollRect:addInitCallback(function()
			return GConst.TYPEOF_LUA_CLASS.REWARD_CELL
		end)
		self.scrollRect:addRefreshCallback(function(index, cell)
			cell:refreshByConfig(self.rewards[index])
		end)
		self.scrollRect:clearCells()
		self.scrollRect:refillCells(#self.rewards)
	else
		if self.scrollRect:getTotalCount() == #self.rewards then
			self.scrollRect:updateAllCell()
		else
			self.scrollRect:refillCells(#self.rewards)
		end
	end
end

function SummonShopBoxUI:refreshCount()
	self.txSelect:setText(self.curCount)
	 -- 计算总价格（考虑折扣次数）
	self.totalCost = 0
	local remainingDiscount = self.remainingDiscount  -- 剩余折扣次数（已在ctor中初始化）
	local remainingCount = self.curCount             -- 需要购买的数量

	-- 1. 优先使用折扣价购买
	if remainingDiscount > 0 then
		local useDiscountTimes = math.min(remainingCount, remainingDiscount)
		self.totalCost = self.totalCost + useDiscountTimes * GFunc.getRewardNum(self.cfg.discount)
		remainingCount = remainingCount - useDiscountTimes

		if self.cfg.discount_display ~= nil then
			self.discount:setActive(true)
			self.txDiscount:setText(I18N:getGlobalText(I18N.GlobalConst.SUMMON_DESCR_8, self.cfg.discount_display // 1000))
		end
	else
		self.discount:setActive(false)
	end
	-- 2. 剩余次数用原价购买
	if remainingCount > 0 then
		self.totalCost = self.totalCost + remainingCount * GFunc.getRewardNum(self.cfg.cost)
		self.discount:setActive(false)
	end
	-- 更新购买按钮的文本（显示总价）
	local haveItemNum = DataManager.BagData.ItemData:getItemNumById(self.costId)
	self.iconCost:setSprite(ModuleManager.ItemManager:getItemIcon(self.costId))
	if haveItemNum >= self.totalCost then
		-- self.btnBuy:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_yellow_3")
		-- self.txBuy:setText("<color=#FFFFFF>"..self.totalCost.."</color>")
	else
		-- self.btnBuy:setSprite(GConst.ATLAS_PATH.COMMON, "common_btn_yellow_3")
		-- self.txBuy:setText("<color=#FF4747>"..self.totalCost.."</color>")
	end
	self.txBuy:setText(self.totalCost)
	GFunc.centerImgAndTx(self.iconCost, self.txBuy)  -- 保持图标和文本居中
end

return SummonShopBoxUI