local this = class("pageReward", G_UIPageBase)
local closeAudio = "Play_SFX_System_HUD_General_Item_Detail_Close"

function this.bind()
  return {
    text_title = L_WordsTpl:getValue("ui_pageReward"),
    goMask = false,
    scrollRectReward = L_Const.ModuleInfo.CellIconBag,
    size_scroll = C_Vector2(1595, 250)
  }
end

function this.methods()
  return {
    onClick_close = function(self)
      L_UI:close(self.pageName)
    end
  }
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self._onEvent_storyStartHandle = handler(self, self.onEvent_storyStartHandle)
  C_StoryEvent.instance:Listen(C_EStoryEvent.StoryStart, self._onEvent_storyStartHandle)
  self.lastTog = nil
  self.curItemID = nil
  self.rewardTitle = nil
  self.callback = options.callback
  self.bind.goMask = true
  L_TimerManager:newOrResetTimer(self, "mask", function()
    self.bind.goMask = false
  end, 0.8)
  if options.itemList then
    self:refreshReward(options.itemList)
  end
  if options.title then
    self.bind.text_title = options.title
  end
end

function this:close(options)
  this.super.close(self, options)
  L_TimerManager:clearTimer(self)
  if self._onEvent_storyStartHandle ~= nil then
    C_StoryEvent.instance:Cancel(C_EStoryEvent.StoryStart, self._onEvent_storyStartHandle)
    self._onEvent_storyStartHandle = nil
  end
  C_AudioManager.Play(closeAudio)
  if self.callback then
    self.callback()
  end
end

function this:refreshReward(itemList)
  self.bind.size_scroll = C_Vector2(math.min(1595, 212 * #itemList), 250)
  self.bind.scrollRectReward:clear()
  local list = {}
  for i = 1, #itemList do
    local cell = self:parseCellItemData(itemList[i])
    cell.enlarge = true
    cell.blight = true
    table.insert(list, cell)
  end
  self.bind.scrollRectReward:insert_array(list)
end

function this:onEvent_storyStartHandle()
  L_UI:close(self.pageName)
end

function this:parseCellItemData(data)
  local cell = {
    guid = data.guid,
    itemId = data.itemId,
    itemType = data.itemType,
    itemNumTxt = data.txt_count,
    noReddot = true
  }
  return cell
end

return this
