local this = class("pageAccessoryStrength", G_UIPageBase)
local _accessoryTpl = L_GameTpl:getAccessoryTpl()
local _accessoryLevelTpl = L_GameTpl:getAccessoryLevelTpl()
local _battleInfoTpl = L_GameTpl:getBattleInfoTpl()
local _accessoryMainTpl = L_GameTpl:getAccessoryMainTpl()
local _wordTpl = L_GameTpl:getWordsTpl()

function this.bind()
  return {
    go_bg = false,
    module_currency = L_Const.ModuleInfo.Currency,
    img_icon = "",
    img_iconEft = "",
    txt_name = "",
    active_maxLvNode = true,
    active_previewLvNode = true,
    txt_levelCur = "",
    txt_levelCurPreview = "",
    txt_levelNext = "",
    img_mainAtt = nil,
    txt_mainAttName = nil,
    txt_mainAttValue = nil,
    go_mainAttValueChange = false,
    txt_mainAttValueChange = nil,
    list_subAtt = {
      moduleName = "pages/accessory/cellAccessorySubAttStrength"
    },
    active_maxLvCostNode = false,
    active_previewLvCostNode = false,
    list_cost = L_Const.ModuleInfo.CellIconBag,
    btn_levelUp = L_Const.ModuleInfo.ModuleBtn,
    go_mask = false
  }
end

function this:onEvent_upgradeAccessorySuccess(oldData)
  self:clearTimer()
  self.isPlayingAnim = true
  self.serverData = L_AccessoryStore:getAccessory(self._strengthGuid)
  self.isMaxLv = L_AccessoryStore:getIsMaxLevel(self._strengthGuid)
  self.bindComponents.anim:Play("anim_AStrength_levelup")
  L_AudioUtil.playSound("Play_SFX_System_UI_Equipment_Succeed")
  self.timer1 = Timer.once(1, function()
    self.bindComponents.animUpgrade:Play(self.isMaxLv and "anim_AStrength_uptip_max" or "anim_AStrength_uptip")
    self:refreshStrengthPreview(true)
  end, self)
  self.bind.go_mask = true
  self.timer2 = Timer.once(2.5, function()
    self.isPlayingAnim = false
    self.bind.go_mask = false
  end, self)
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self._strengthGuid = options.accessoryId
  self.newUnlockIndex = -1
  self.isPlayingAnim = false
  self:initPage()
end

function this:open(options)
  L_AccessoryStore:listenCallFunc(L_AccessoryStore.event.upgradeAccessorySuccess, self.onEvent_upgradeAccessorySuccess, self)
end

function this:initPage()
  self.bind.go_bg = not L_UI:checkPageOpen("pageHero")
  self:initCurrencyModule()
  self:initAccessoryInfo()
end

function this:initCurrencyModule()
  local tpl_sys = L_GameTpl:getSystemUnlockTpl():getTplById(L_SystemConst.enum.accessoryStrength)
  self.modules.module_currency:refreshRes(tpl_sys)
end

function this:initAccessoryInfo()
  local serverData = L_AccessoryStore:getAccessory(self._strengthGuid)
  local accessoryCfg = _accessoryTpl:getTplById(serverData.accessoryId)
  self.quality = _accessoryTpl:getRarity(accessoryCfg)
  self.type = _accessoryTpl:getType(accessoryCfg)
  self.bind.img_icon = _accessoryTpl:getLargeIconByTpl(accessoryCfg)
  self.bind.img_iconEft = _accessoryTpl:getLargeIconByTpl(accessoryCfg)
  for i = 0, self.bindComponents.bgEftRoot.childCount - 1 do
    local go = self.bindComponents.bgEftRoot:GetChild(i)
    L_CommonUtil.setObjActive(go.gameObject, 4 - self.quality == i)
  end
  self.bind.txt_name = _accessoryTpl:getName(accessoryCfg)
  self:refreshStrengthPreview(false)
end

function this:refreshStrengthCost()
  if self.isMaxLv then
    return
  end
  local cost = _accessoryLevelTpl:getUpgradeCostByAccessoryIdAndLevel(self.serverData.accessoryId, self.serverData.level)
  local costItemInfo = {}
  local costMoneyInfo = {}
  for _, v in ipairs(cost) do
    if v[1] == L_Const.resType.currency then
      costMoneyInfo.itemType = L_Const.resType.currency
      costMoneyInfo.itemId = v[2]
      costMoneyInfo.itemCostNum = v[3]
    else
      table.insert(costItemInfo, {
        itemType = v[1],
        itemId = v[2],
        itemCostNum = v[3]
      })
    end
  end
  self.bCanUpgrade = true
  local itemListData = {}
  for _, v in ipairs(costItemInfo) do
    local hasNum = L_ItemTplManager:getItemNum(v.itemType, v.itemId)
    local itemNumTxt
    if hasNum >= v.itemCostNum then
      itemNumTxt = string.format("%d/%d", v.itemCostNum, hasNum)
      itemNumTxt = string.format("%d/%d", hasNum, v.itemCostNum)
    else
      itemNumTxt = string.format("<color=#ff0000ff>%d</color>/%d", hasNum, v.itemCostNum)
      self.bCanUpgrade = false
    end
    table.insert(itemListData, {
      itemType = v.itemType,
      itemId = v.itemId,
      itemNumTxt = itemNumTxt
    })
  end
  self.bind.list_cost:clear()
  self.bind.list_cost:insert_array(itemListData)
  local moduleBtn = self.modules.btn_levelUp
  moduleBtn:setData({
    txtName = _wordTpl:getTplById("equipment_upgrade_btn_text"),
    callback = function()
      self:reqStrength()
    end,
    itemType = costMoneyInfo.itemType,
    itemId = costMoneyInfo.itemId,
    itemNum = costMoneyInfo.itemCostNum
  })
  if not self.bCanUpgrade then
    return
  end
  local hasMoneyNum = L_ItemTplManager:getItemNum(costMoneyInfo.itemType, costMoneyInfo.itemId)
  self.bCanUpgrade = hasMoneyNum >= costMoneyInfo.itemCostNum
end

function this:getLevelShow(level)
  if level < 10 then
    return "0" .. tostring(level)
  end
  return tostring(level)
end

function this:refreshStrengthPreview(bAfterUpgrade)
  if not bAfterUpgrade then
    self.serverData = L_AccessoryStore:getAccessory(self._strengthGuid)
    self.isMaxLv = L_AccessoryStore:getIsMaxLevel(self._strengthGuid)
    self.bind.active_maxLvNode = self.isMaxLv
    self.bind.active_previewLvNode = not self.isMaxLv
    if self.isMaxLv then
      self.bind.txt_levelCur = self:getLevelShow(self.serverData.level)
    else
      self.bind.txt_levelCurPreview = self:getLevelShow(self.serverData.level)
      self.bind.txt_levelNext = self:getLevelShow(self.serverData.level + 1)
    end
    self.bind.active_maxLvCostNode = self.isMaxLv
    self.bind.active_previewLvCostNode = not self.isMaxLv
    self:refreshStrengthCost()
    self.bind.go_mainAttValueChange = not self.isMaxLv
    local main_att = L_AccessoryManager:getPackAtt(self.serverData).mainAtt
    local tpl_mainAttBattleInfo = _battleInfoTpl:getTplById(main_att.attId[1])
    self.bind.img_mainAtt = _battleInfoTpl:getIcon(tpl_mainAttBattleInfo)
    self.bind.txt_mainAttName = main_att.showName
    self.bind.txt_mainAttValue = _battleInfoTpl:getShowTxt(main_att.attId[1], main_att.value)
    if not self.isMaxLv then
      local newValue = _battleInfoTpl:getShowTxt(main_att.attId[1], _accessoryMainTpl:getValue(_accessoryMainTpl:getTplByGroupIdAndLevel(main_att.groupId, self.serverData.level + 1)))
      self.bind.txt_mainAttValueChange = newValue
    end
    local nextLevel = self.serverData.level + 1
    if self.isMaxLv then
      nextLevel = self.serverData.level
    end
    local tmp = {}
    local packAtt = L_AccessoryManager:getPackAtt(self.serverData)
    local oldSubAttNum = _accessoryLevelTpl:getUnlockEntry(_accessoryLevelTpl:getTplByAccessoryIdAndLevel(self.serverData.accessoryId, self.serverData.level))
    local newSubAttNum = _accessoryLevelTpl:getUnlockEntry(_accessoryLevelTpl:getTplByAccessoryIdAndLevel(self.serverData.accessoryId, nextLevel))
    if oldSubAttNum < newSubAttNum then
      self.newUnlockIndex = newSubAttNum
    end
    local sub_att = packAtt.subAtt
    local showBg = true
    for i, v in ipairs(sub_att) do
      showBg = not showBg
      local showHighLight = oldSubAttNum < i and i <= newSubAttNum
      table.insert(tmp, {
        showBg = showBg,
        showHighLight = showHighLight,
        lock = v.lock,
        desc = v.desc,
        index = i
      })
    end
    self.bind.list_subAtt:clear()
    self.bind.list_subAtt:insert_array(tmp)
    return
  end
  self.serverData = L_AccessoryStore:getAccessory(self._strengthGuid)
  self.isMaxLv = L_AccessoryStore:getIsMaxLevel(self._strengthGuid)
  if self.isMaxLv then
    self.bind.active_maxLvNode = true
    self.bind.active_previewLvNode = true
    self.bind.active_maxLvCostNode = true
    self.bind.active_previewLvCostNode = true
    self.timer3 = Timer.once(1.5, function()
      self.bind.active_previewLvNode = false
      self.bind.active_previewLvCostNode = false
    end, self)
  else
    self.bind.active_maxLvNode = self.isMaxLv
    self.bind.active_previewLvNode = not self.isMaxLv
    self.bind.active_maxLvCostNode = self.isMaxLv
    self.bind.active_previewLvCostNode = not self.isMaxLv
  end
  if self.isMaxLv then
    self.bind.txt_levelCur = self:getLevelShow(self.serverData.level)
  else
    self.timer4 = Timer.once(0.265, function()
      self.bind.txt_levelCurPreview = self:getLevelShow(self.serverData.level)
    end, self)
    self.timer5 = Timer.once(0.495, function()
      self.bind.txt_levelNext = self:getLevelShow(self.serverData.level + 1)
    end, self)
  end
  self:refreshStrengthCost()
  self.bind.go_mainAttValueChange = not self.isMaxLv
  local main_att = L_AccessoryManager:getPackAtt(self.serverData).mainAtt
  local tpl_mainAttBattleInfo = _battleInfoTpl:getTplById(main_att.attId[1])
  self.bind.img_mainAtt = _battleInfoTpl:getIcon(tpl_mainAttBattleInfo)
  self.bind.txt_mainAttName = main_att.showName
  if not self.isMaxLv then
    self.timer6 = Timer.once(0.825, function()
      self.bind.txt_mainAttValue = _battleInfoTpl:getShowTxt(main_att.attId[1], main_att.value)
      local newValue = _battleInfoTpl:getShowTxt(main_att.attId[1], _accessoryMainTpl:getValue(_accessoryMainTpl:getTplByGroupIdAndLevel(main_att.groupId, self.serverData.level + 1)))
      self.bind.txt_mainAttValueChange = newValue
    end, self)
  else
    self.bind.txt_mainAttValue = _battleInfoTpl:getShowTxt(main_att.attId[1], main_att.value)
  end
  local nextLevel = self.serverData.level + 1
  if self.isMaxLv then
    nextLevel = self.serverData.level
  end
  local packAtt = L_AccessoryManager:getPackAtt(self.serverData)
  local oldSubAttNum = _accessoryLevelTpl:getUnlockEntry(_accessoryLevelTpl:getTplByAccessoryIdAndLevel(self.serverData.accessoryId, self.serverData.level))
  local newSubAttNum = _accessoryLevelTpl:getUnlockEntry(_accessoryLevelTpl:getTplByAccessoryIdAndLevel(self.serverData.accessoryId, nextLevel))
  local unlockNextIndex = -1
  if oldSubAttNum < newSubAttNum then
    unlockNextIndex = newSubAttNum
  end
  local sub_att = packAtt.subAtt
  local showBg = true
  for i = 1, #self.bind.list_subAtt do
    showBg = not showBg
    local showHighLight = oldSubAttNum < i and i <= newSubAttNum
    self.bind.list_subAtt:change(i, {
      showHighLight = showHighLight,
      lock = sub_att[i].lock,
      desc = sub_att[i].desc,
      newUnlockIndex = self.newUnlockIndex,
      unlockNextIndex = unlockNextIndex
    })
  end
  if oldSubAttNum < newSubAttNum then
    self.newUnlockIndex = newSubAttNum
  else
    self.newUnlockIndex = -1
  end
end

function this:reqStrength()
  if self.isPlayingAnim then
    return
  end
  if not self.bCanUpgrade then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_shortageMaterial"))
    return
  end
  local data = {
    u32 = self._strengthGuid
  }
  L_AccessoryManager:req_StrengthAccessory(data)
end

function this:clearTimer()
  if self.timer1 then
    Timer.remove(self.timer1)
    self.timer1 = nil
  end
  if self.timer2 then
    Timer.remove(self.timer2)
    self.timer2 = nil
  end
  if self.timer3 then
    Timer.remove(self.timer3)
    self.timer3 = nil
  end
  if self.timer4 then
    Timer.remove(self.timer4)
    self.timer4 = nil
  end
  if self.timer5 then
    Timer.remove(self.timer5)
    self.timer5 = nil
  end
  if self.timer6 then
    Timer.remove(self.timer6)
    self.timer6 = nil
  end
end

function this:close(options)
  self:clearTimer()
  L_AccessoryStore:unListenCallFunc(L_AccessoryStore.event.upgradeAccessorySuccess, self.onEvent_upgradeAccessorySuccess, self)
  this.super.close(self, options)
end

return this
