local this = class("pageBagUseGift", G_UIPageBase)
local _commonItemTpl = L_GameTpl:getCommonItemTpl()

function this:ctor(...)
  this.super.ctor(self, ...)
end

function this.bind()
  return {
    img_icon = nil,
    img_qualityCircle = nil,
    txt_num = nil,
    txt_title = nil,
    list_gift = L_Const.ModuleInfo.CellIconBag,
    module_selectNum = L_Const.ModuleInfo.SelectNum
  }
end

function this.methods()
  return {
    onClick_close = function(self)
      L_UI:close(self.pageName)
    end,
    onClick_use = function(self)
      L_BagManager:reqUseItem(self._itemId, self._selectNum, {
        self._selectGiftType,
        self._selectGiftId
      })
      L_UI:close(self.pageName)
    end
  }
end

function this:created(...)
  this.super.created(self, ...)
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self._itemId = options.itemId
  self._selectNum = 1
  self:initPage()
end

function this:close()
  this.super.close(self)
end

function this:initPage()
  self:initModuleNum()
  local tpl = _commonItemTpl:getTplById(self._itemId)
  self.bind.img_icon = _commonItemTpl:getIcon(tpl)
  self.bind.img_qualityCircle = string.format("UI/Atlas/Bag/tex_bag_rarity_tips_w_%s.png", _commonItemTpl:getRarity(tpl))
  self.bind.txt_num = tostring(L_BagStore:getItemNum(self._itemId))
  local bagUseType = _commonItemTpl:getUseType(tpl)
  if bagUseType == L_BagConst.bagUseType.selectGift then
    self.bind.txt_title = L_WordsTpl:getValue("notice_bag_useChooseBox")
  elseif bagUseType == L_BagConst.bagUseType.randomGift then
    self.bind.txt_title = L_WordsTpl:getValue("notice_bag_useRandomBox")
  elseif bagUseType == L_BagConst.bagUseType.fixGift then
    self.bind.txt_title = L_WordsTpl:getValue("notice_bag_useCommonBox")
  end
  local rewards = L_DataUtil.parseRewardConfig(_commonItemTpl:getGiftBagReward(tpl))
  local tmp = {}
  for i, v in ipairs(rewards) do
    local callback
    if bagUseType == L_BagConst.bagUseType.selectGift then
      function callback()
        self._selectGiftType = v.itemType
        
        self._selectGiftId = v.itemId
        self:setGiftListActive()
      end
    end
    table.insert(tmp, {
      itemType = v.itemType,
      itemId = v.itemId,
      itemNum = v.itemNum,
      callback = callback
    })
  end
  self.bind.list_gift:clear()
  self.bind.list_gift:insert_array(tmp)
  if bagUseType == L_BagConst.bagUseType.selectGift then
    self._selectGiftType = tmp[1].itemType
    self._selectGiftId = tmp[1].itemId
    self:setGiftListActive()
  end
end

function this:initModuleNum()
  local max = L_BagStore:getItemNum(self._itemId)
  local func = function(num)
    self._selectNum = num
  end
  self.modules.module_selectNum:initModule(func, max)
  func(self._selectNum)
end

function this:setGiftListActive()
  for i, v in pairs(self.modules.list_gift) do
    v:setActive(self._selectGiftId == v.bind.itemId and self._selectGiftType == v.bind.itemType)
  end
end

return this
