local this = class("moduleBuyGoodsInfo", G_UIModuleBase)
local _goodsTpl = L_GameTpl:getGoodsTpl()
local _commonItemTpl = L_GameTpl:getCommonItemTpl()

function this.bind()
  return {
    name = "",
    holdNum = "",
    info = "",
    storeNumText = "",
    storeBox = true,
    cost = "",
    costIcon = "",
    buy = false,
    exchange = false,
    numberFiledActive = true,
    unlockListActive = true,
    costListActive = true,
    costActive = false,
    freeGet = false,
    infoScrollVerticalNormalized = 1,
    costList = {
      moduleName = "pages/shop/cellCostItem"
    },
    unlockList = {
      moduleName = "modulePages/cellGoodUnlockItem"
    },
    moduleInputNum = {
      moduleName = "modulePages/moduleSelectNum"
    },
    itemRarity = "",
    itemIcon = ""
  }
end

function this.methods()
  return {
    onClick_buy = function(self)
      self:onButBtnClicked()
    end,
    onClick_exchange = function(self)
    end
  }
end

function this:open()
  this.super.open(self)
  L_BagStore:listenCallFunc(L_BagStore.event.refreshBag, self.onEvent_refreshResHandle, self)
  L_PlayerStore:listenCallFunc(L_PlayerStore.event.refreshAttr, self.onEvent_refreshResHandle, self)
end

function this:close()
  this.super.close(self)
  L_BagStore:unListenCallFunc(L_BagStore.event.refreshBag, self.onEvent_refreshResHandle)
  L_PlayerStore:unListenCallFunc(L_PlayerStore.event.refreshAttr, self.onEvent_refreshResHandle)
end

function this:onEvent_refreshResHandle()
  local text = L_WordsTpl:getValue("ui_shopinfo_hasitemnumber")
  self.bind.holdNum = text .. self:getHoldNum(self.itemType, self.itemId)
  Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.num)
end

function this:refresh(options)
  if not options then
    return
  end
  self.bind.infoScrollVerticalNormalized = 1
  self.bind.buy = true
  self.slotId = options.slotId
  self.shopId = options.shopId
  local goodsItem = L_ShopStore:getGoodsItem(self.shopId, self.slotId)
  local isLimit = L_ShopStore:getIsLimitGoods(self.shopId, self.slotId)
  self.bind.storeBox = isLimit == true
  self.goodsId = goodsItem.goodsId
  local tpl = _goodsTpl:getTplById(goodsItem.goodsId)
  local itemType = _goodsTpl:getItem(tpl)[1][1]
  local itemId = _goodsTpl:getItem(tpl)[1][2]
  self.itemId = itemId
  self.itemType = itemType
  local item = L_ItemManager:parseItem(itemType, itemId)
  self.bind.name = item.name
  self.bind.itemIcon = item.icon
  self.bind.itemRarity = string.format("UI/Atlas/Bag/tex_bag_rarity_tips_w_%s.png", item.quality)
  local text = L_WordsTpl:getValue("ui_shopinfo_hasitemnumber")
  self.bind.holdNum = text .. L_ItemTplManager:getItemNum(itemType, itemId)
  Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.num)
  self.bind.info = _goodsTpl:getGoodsDesc(tpl)
  self:updateMaxValue(tpl)
  if self.maxValue == 0 then
    self.buyNum = 1
  else
    self.buyNum = 1
  end
  self:refreshBuyNum()
  self:refreshUnlockCondition()
end

function this:getHoldNum(type, id)
  if type == L_Const.resType.currency then
    return L_PlayerStore:getCurrencyNum(id)
  else
    return L_BagStore:getItemNum(id)
  end
end

function this:refreshUnlockCondition()
  local goodsItem = L_ShopStore:getGoodsItem(self.shopId, self.slotId)
  local tpl = _goodsTpl:getTplById(goodsItem.goodsId)
  local conditions = _goodsTpl:getCommonCondition(tpl)
  local isComplete = L_ConditionManager:isComplete(conditions)
  self.bind.numberFiledActive = isComplete
  self.bind.unlockListActive = not isComplete
  self.bind.buy = isComplete
  self.bind.costListActive = isComplete
  if not isComplete then
    local unlockData = {}
    for k, condition in ipairs(conditions) do
      local target = condition[2]
      local current = 0
      if goodsItem.unlockProgress and goodsItem.unlockProgress[k] ~= nil then
        current = goodsItem.unlockProgress[k]
      end
      local unlockTip = L_Config:provider(_goodsTpl:getUnlockDesc(tpl)[k])
      table.insert(unlockData, {
        progressText = string.format("(<color=#EF5743>%s</color>/%s)", current, target),
        unlockTip = L_Lang:get(_goodsTpl:getUnlockDesc(tpl)[k], {
          [0] = target
        })
      })
    end
    self.bind.unlockList:clear()
    self.bind.unlockList:insert_array(unlockData)
  end
end

function this:updateMaxValue(tpl)
  local goodsNum = L_ShopStore:getStock(self.shopId, self.slotId)
  self.maxValue = nil
  local costIds = _goodsTpl:getCostId(tpl)
  for _, cost in ipairs(costIds) do
    local price = cost[3]
    local item = L_ItemManager:parseItem(cost[1], cost[2])
    local maxValue = 1
    if goodsNum < math.modf(item.num / price) then
      maxValue = goodsNum
    else
      maxValue = math.modf(item.num / price)
    end
    if self.maxValue == nil or maxValue < self.maxValue then
      self.maxValue = maxValue
    end
  end
  local func = function(num)
    self.buyNum = num
    self:refreshBuyNum()
  end
  local max = 1
  if self.maxValue ~= 0 then
    max = self.maxValue
  end
  self.modules.moduleInputNum:initModule(func, max, 1)
end

function this:refreshBuyNum()
  local goodsItem = L_ShopStore:getGoodsItem(self.shopId, self.slotId)
  local tpl = _goodsTpl:getTplById(goodsItem.goodsId)
  local costIds = _goodsTpl:getCostId(tpl)
  self.bind.costList:clear()
  local costData = {}
  if not table.isEmpty(costIds) and #costIds == 1 then
    self.bind.costIcon = L_ItemManager:parseCurrencyItem(_goodsTpl:getCurrencyId(tpl)).icon
    self.bind.cost = tostring(costIds[1][3] * self.buyNum)
    self.bind.costActive = costIds[1][3] ~= 0
    self.bind.freeGet = costIds[1][3] == 0
  else
    self.bind.costActive = false
    self.bind.freeGet = false
    for _, cost in ipairs(costIds) do
      if cost[3] > 0 then
        local item = L_ItemManager:parseItem(cost[1], cost[2])
        local price = cost[3] * self.buyNum
        local costStr = tostring(price)
        local holdStr = "%s"
        local icon = item.icon
        if price > item.num then
          holdStr = "<color=#FF7E6D>%s</color>"
        end
        local itemNumTxt = string.format(holdStr .. "/%s", item.num, costStr)
        if item.num > 99 then
          itemNumTxt = string.format(holdStr .. "/%s", "99+", costStr)
        end
        table.insert(costData, {
          itemType = item.itemType,
          itemId = item.itemID,
          itemNumTxt = itemNumTxt,
          icon = icon
        })
      end
    end
    self.bind.costList:insert_array(costData)
  end
  local goodsNum = L_ShopStore:getStock(self.shopId, self.slotId)
  local stockText = L_Lang:get(_goodsTpl:getLimitTxt(tpl), {
    [0] = goodsNum
  })
  self.bind.storeNumText = stockText
  Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.stock)
  if 1 < #costData then
  elseif not self.bind.costActive then
  end
end

function this:onButBtnClicked()
  local goodsItem = L_ShopStore:getGoodsItem(self.shopId, self.slotId)
  local tpl = _goodsTpl:getTplById(goodsItem.goodsId)
  local costIds = _goodsTpl:getCostId(tpl)
  for _, cost in ipairs(costIds) do
    local price = cost[3]
    local item = L_ItemManager:parseItem(cost[1], cost[2])
    if self.buyNum * price > item.num then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_pageRogueShopPurchase"))
      return
    end
  end
  local data = {
    slot_id = self.slotId,
    times = self.buyNum,
    sign = L_ShopStore:getEndTime(self.shopId)
  }
  L_ShopManager:buyGoods(data, function()
    self:updateMaxValue(tpl)
    if self.buyNum > self.maxValue then
      self.buyNum = 1
    end
    self.modules.moduleInputNum:changeNum(self.buyNum)
    self:onEvent_refreshResHandle()
  end)
end

function this:playShowAnim()
  self.bindComponents.ani:Stop()
  self.bindComponents.ani:Play("anim_shop_info_show")
end

return this
