local this = class("moduleHeroGift", require("ui.pages.HeroPanel.moduleHeroBase"))
local giftTpl = L_GameTpl:getStargiftTpl()
local battleInfoTpl = L_GameTpl:getBattleInfoTpl()
local talentRankTpl = L_GameTpl:getTalentRankTpl()
local starGiftNum = 3
local property = {
  L_Const.battleAtt.MAXHP,
  L_Const.battleAtt.ATK,
  L_Const.battleAtt.DEF,
  L_Const.battleAtt.MDEF
}
local heroGiftLevelIcon = {
  "UI/Atlas/HeroGift/tex_herostargift_frame_cw_sz1.png",
  "UI/Atlas/HeroGift/tex_herostargift_frame_cw_sz2.png",
  "UI/Atlas/HeroGift/tex_herostargift_frame_cw_sz3.png"
}

function this.bind()
  return {
    currentLv = "",
    advanceLv = "",
    requireLv = "",
    gold = "",
    heroName = "",
    heroIcon = "",
    heroInfo = true,
    heroInfo_advanceBtn = true,
    heroInfo_confirmBtn = true,
    go_giveLevelArea = false,
    go_advancedLevelArea = false,
    giveLevelText = "",
    unlockDesText = "",
    unlockDesTextActive = false,
    moduleCurrency = {
      moduleName = "modulePages/moduleCurrency"
    },
    go_giftPropList = true,
    go_giftPropVX = true,
    giftPropList = {
      moduleName = "pages/HeroPanel/gift/cellGiFtProp"
    },
    ordinaryList = {
      moduleName = "pages/HeroPanel/hero/heroProperty"
    },
    specialList = {
      moduleName = "pages/HeroPanel/hero/heroProperty"
    },
    moduleHeroShowRank = {
      moduleName = "pages/HeroPanel/moduleHeroShowRank"
    }
  }
end

function this.methods()
  return {
    onClick_equipAllStarGift = function(self)
      if self:isPreviewMode() then
        return
      end
      local rankData = talentRankTpl:getHeroRankTpls(self.heroConfigId)
      local hero = self:getHero(self.heroGuid)
      local rankBreakthroughItem = rankData[hero.hero_rank].rankBreakthroughItem
      if #hero.starGifts == starGiftNum then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_stargift_equipall"))
        return
      end
      local starGifts = {}
      for i, v in ipairs(rankBreakthroughItem) do
        local equipped = false
        for m, n in pairs(hero.starGifts) do
          if n == v then
            equipped = true
            break
          end
        end
        if L_StarGiftStore:getStarGiftNum(v) > 0 and not equipped then
          table.insert(starGifts, v)
        end
      end
      if table.isEmpty(starGifts) then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_moduleHeroGift"))
        return
      end
      local data = {
        star_ids = starGifts,
        hero_id = self.heroGuid
      }
      L_StarGiftStore:req_changeCSProtoStarGiftEquip(data, function()
        for i = 1, #starGifts do
          local attribute = giftTpl:getAttribute(giftTpl:getTplById(starGifts[i]))
          for i, v in pairs(attribute) do
            local showText = battleInfoTpl:getName(battleInfoTpl:getTplById(i)) .. "  +  " .. battleInfoTpl:getShowTxt(i, v)
            L_FlyMsgManager:showNormalMsg(showText)
          end
        end
        self:refreshGiftList()
      end)
    end,
    onClick_advance = function(self)
      if self:isPreviewMode() then
        return
      end
      if not self.boolGold then
        L_HeroManager:heroHintInfo(1)
        return
      end
      if not self.boolLv then
        local data_tip = {
          txtContent = L_WordsTpl:getValue("notice_stargift_jump"),
          confirmCallback = handler(self, self.changeToProperty)
        }
        L_GameUtil.showCommonTip(data_tip)
        return
      end
      if not self:checkGiftIsFull(self.heroGuid) then
        L_HeroManager:heroHintInfo(7)
        return
      end
      local data = {
        u32 = self.heroGuid
      }
    end,
    giftPropList = {
      openGiftsBg = function(self, id, allow)
        if self:isPreviewMode() then
          return
        end
        L_UI:open("pageHeroGiftTip", {
          heroId = self.heroGuid,
          starGift = id,
          equip = allow
        })
      end
    }
  }
end

function this:changeToProperty()
  self.parent:onSelectionChange(L_Const.heroModuleType.Property, {openExp = true})
end

function this:checkGiftIsFull(heroId)
  local hero = self:getHero(heroId)
  return #hero.starGifts == starGiftNum
end

function this:open()
  local tpl_sys = L_GameTpl:getSystemUnlockTpl():getTplById(L_SystemConst.enum.science)
  self.modules.moduleCurrency:refreshRes(tpl_sys)
  self._ESyncHeroServerDataHandler = handler(self, self.refreshPage)
  AzurWorld.heroMgr:RegisterEvent(C_EHeroEvent.ESyncHeroServerData, self._ESyncHeroServerDataHandler)
end

function this:close()
  AzurWorld.heroMgr:UnregisterEvent(C_EHeroEvent.ESyncHeroServerData, self._ESyncHeroServerDataHandler)
end

function this:getTimelineState()
  return L_Const.heroTimelineState.Equip
end

function this:initPage()
  this.super.initPage(self)
  self:refreshPage()
end

function this:getMaxRank(heroId)
  local rankData = talentRankTpl:getHeroRankTpls(heroId)
  return #rankData - 1
end

function this:refreshPage()
  self.heroGuid = self:getModeController():getSelectGuid()
  self.heroConfigId = self:getModeController():getSelectConfigId()
  local hero = self:getHero(self.heroGuid)
  local heroRank = L_HeroStore:getHeroRank(hero)
  local item_hero = L_ItemTplManager:getHeroItem(L_HeroStore:getHeroConfigId(hero))
  self.bind.heroName = L_HeroManager:getHeroName(self.heroGuid)
  if self.heroGuid == L_HeroStore:getDefaultHeroGuid() then
    L_PhotoManager:bindPhotoEntity(self.bindComponents.heroIcon.gameObject, L_PlayerStore:getPlayerModHeadImgName())
  else
    self.bind.heroIcon = item_hero.icon
  end
  if heroRank - 1 == self:getMaxRank(self.heroGuid) then
    self.bind.heroInfo = true
  else
    self.bind.heroInfo = true
    local rankData = talentRankTpl:getHeroRankTpls(self.heroConfigId)
    local heroLevel = L_HeroStore:getHeroLevel(hero)
    local lv = L_HeroManager:lvChange(heroLevel)
    self.bind.currentLv = "Lv." .. lv .. "/" .. L_HeroManager:lvChange(rankData[heroRank].rankLevelLimit)
    self.bind.advanceLv = "Lv." .. lv .. "/" .. L_HeroManager:lvChange(rankData[heroRank + 1].rankLevelLimit)
    if heroLevel >= rankData[heroRank].rankLevelLimit then
      self.bind.requireLv = tostring(rankData[heroRank].rankLevelLimit)
      self.boolLv = true
    else
      self.bind.requireLv = L_GameUtil.fillColor(rankData[heroRank].rankLevelLimit, L_Const.colorHtml.red001)
      self.boolLv = false
    end
    if rankData[heroRank].rankBreakthroughCoin <= L_PlayerStore:getCurrencyNum(L_Const.currencyType.gold) then
      self.bind.gold = tostring(rankData[heroRank].rankBreakthroughCoin)
      self.boolGold = true
    else
      self.bind.gold = L_GameUtil.fillColor(rankData[heroRank + 1].rankBreakthroughCoin, L_Const.colorHtml.red001)
      self.boolGold = false
    end
  end
  self:refreshGiftList()
  self.modules.moduleHeroShowRank:refreshStar(heroRank - 1)
  self:refreshGiveOrAdvacnce()
  self:checkPlayerLevelSatisified(heroRank)
end

function this:checkPlayerLevelSatisified(rank)
  local giftIsFull = self:checkGiftIsFull(self.heroGuid)
  if not giftIsFull then
    self.bind.unlockDesTextActive = false
    return
  end
  local isNotMax = rank - 1 ~= self:getMaxRank(self.heroConfigId)
  if not self:isPreviewMode() and not giftIsFull and isNotMax then
    self.bind.unlockDesTextActive = false
    return
  end
  local bCompelte = true
  self.bind.heroInfo_advanceBtn = bCompelte
  self.bind.unlockDesTextActive = not bCompelte
  if not bCompelte then
    self.bind.unlockDesText = L_ConditionManager:getSingleDesc(condition)
  end
end

function this:refreshGiveOrAdvacnce()
  local giftIsFull = self:checkGiftIsFull(self.heroGuid)
  local hero = self:getHero(self.heroGuid)
  local heroRank = L_HeroStore:getHeroRank(hero)
  local heroLevel = L_HeroStore:getHeroLevel(hero)
  local isNotMax = heroRank - 1 ~= self:getMaxRank(self.heroConfigId)
  self.bind.heroInfo_advanceBtn = not self:isPreviewMode() and giftIsFull and isNotMax
  self.bind.heroInfo_confirmBtn = not self:isPreviewMode() and not giftIsFull and isNotMax
  self.bind.go_giveLevelArea = not giftIsFull
  self.bind.go_advancedLevelArea = giftIsFull
  if giftIsFull then
  else
    local rankLv = talentRankTpl:getHeroRankTpls(self.heroConfigId)
    self.bind.currentLv = string.format("%02d", heroLevel)
    local maxLv = rankLv[heroRank].rankLevelLimit
    self.bind.giveLevelText = "Lv." .. heroLevel .. "/" .. tostring(maxLv)
  end
end

function this:refreshGiftList()
  local hero = self:getHero(self.heroGuid)
  local heroRank = L_HeroStore:getHeroRank(hero)
  local rankData = talentRankTpl:getHeroRankTpls(self.heroConfigId)
  local rankBreakthroughItem = rankData[heroRank].rankBreakthroughItem
  self.bind.go_giftPropList = heroRank - 1 ~= self:getMaxRank(self.heroConfigId)
  self.bind.go_giftPropVX = heroRank - 1 ~= self:getMaxRank(self.heroConfigId)
  self.bind.giftPropList:clear()
  local tempData = {}
  for i, v in ipairs(rankBreakthroughItem) do
    local equip = false
    for m, n in pairs(hero.starGifts) do
      if n == v then
        equip = true
        break
      end
    end
    local pos
    local itemPos = self.bindComponents["cellGiftItemPos" .. i]
    if itemPos then
      pos = itemPos.anchoredPosition
    else
      pos = L_Vector3.getTemp()
    end
    table.insert(tempData, {
      id = v,
      equip = equip,
      go_equip = equip,
      go_level = not equip,
      equipIcon = giftTpl:getTexture(giftTpl:getTplById(v)),
      classIcon = giftTpl:getClassIcon(giftTpl:getTplById(v)),
      transPosition = pos,
      levelIcon = heroGiftLevelIcon[i] or ""
    })
  end
  self.bind.giftPropList:insert_array(tempData)
  self:specialProperty()
end

function this:specialProperty()
  local heroData = self:getHero(self.heroGuid)
  local configId = L_HeroStore:getHeroConfigId(heroData)
  local rank = L_HeroStore:getHeroRank(heroData)
  local runes = L_HeroStore:getHeroRuneIds(heroData)
  local starGift, special = L_HeroManager:getHeroStarGiftByHeroIdAndRank(configId, rank, runes)
  local ordinaryList = {}
  local count = 0
  for i, v in pairs(property) do
    if starGift[v] then
      local bgBool = false
      count = count + 1
      if 0 < math.floor(count % 2) then
        bgBool = true
      end
      table.insert(ordinaryList, {
        bg = bgBool,
        curNum = true,
        num = battleInfoTpl:getShowTxt(v, starGift[v]),
        name = battleInfoTpl:getName(battleInfoTpl:getTplById(v)),
        icon = battleInfoTpl:getIcon(battleInfoTpl:getTplById(v)),
        add = false
      })
    end
  end
  self.bind.ordinaryList:clear()
  self.bind.ordinaryList:insert_array(ordinaryList)
  local specialList = {}
  count = 0
  for i, v in pairs(special) do
    local bgBool = false
    count = count + 1
    if 0 < math.floor(count % 2) then
      bgBool = true
    end
    table.insert(specialList, {
      bg = bgBool,
      curNum = true,
      num = battleInfoTpl:getShowTxt(i, v),
      name = battleInfoTpl:getName(battleInfoTpl:getTplById(i)),
      icon = battleInfoTpl:getIcon(battleInfoTpl:getTplById(i)),
      add = false
    })
  end
  self.bind.specialList:clear()
  self.bind.specialList:insert_array(specialList)
end

return this
