local this = class("moduleAccessory", require("ui.pages.HeroPanel.moduleHeroBase"))
local _battleInfoTpl = L_GameTpl:getBattleInfoTpl()
local _accessoryTpl = L_GameTpl:getAccessoryTpl()
local _spiritronTpl = L_GameTpl:getSpiritronTpl()
local quality_color = L_Const.accessoryQualityColor
local accessory = {
  L_AccessoryConst.accessoryType.earring,
  L_AccessoryConst.accessoryType.pants,
  L_AccessoryConst.accessoryType.weapon,
  L_AccessoryConst.accessoryType.coat,
  L_AccessoryConst.accessoryType.ring
}

function this.bind()
  return {
    list_slot = {
      moduleName = "pages/heroPanel/accessory/cellAccessorySlot"
    },
    module_accessory = {
      moduleName = "pages/accessory/moduleAccessoryBagContent"
    },
    go_accessory = false,
    go_acclist = true,
    list_accAtt = {
      moduleName = "pages/pet/cellAttrItem"
    },
    go_infoMask = false,
    propetyPanel = {
      moduleName = "pages/propertyPanel/modulePropertyPanel"
    },
    go_emptyTips = false,
    go_spiritSkill = false,
    txt_spiritInfo = "",
    color_quality = C_Color(1, 1, 1, 1),
    list_star = {}
  }
end

function this.methods()
  return {
    onClick_mask = function(self)
      self:moduleAccessoryClose()
    end,
    onClick_detail = function(self)
      self:moduleAccessoryClose()
      self.modules.propetyPanel:initModule({
        heroData = self:getHero(self._heroGuid),
        detailId = L_Const.propertyDetail.equipment
      })
      self.modules.propetyPanel:setPanelActive(true)
    end,
    list_slot = {
      onClick_item = function(self, show)
      end,
      on_click_accessory = function(self, option)
        self:moduleAccessoryOpen(option.selectHeroGuid, option.accessoryType)
      end
    },
    onClick_spiritronNode = function(self)
      self.modules.propetyPanel:initModule({
        heroData = self:getHero(self._heroGuid),
        detailId = L_Const.propertyDetail.equipment
      })
      self.modules.propetyPanel:setPanelActive(true)
    end,
    onClick_quickEquipAccessory = function(self)
      self:moduleAccessoryClose()
      self:onClickQuickEquipAccessory()
    end,
    onClick_replaceAccessory = function(self)
      self:onClickReplaceAccessory()
    end
  }
end

function this:open()
  L_HeroStore:listenCallFunc(L_HeroStore.event.setCurHeroGuid, self.onEvent_setCurHeroID, self)
  self._ESyncHeroServerDataHandler = handler(self, self.onEvent_refreshAccessory)
  AzurWorld.heroMgr:RegisterEvent(C_EHeroEvent.ESyncHeroServerDataList, self._ESyncHeroServerDataHandler)
  L_AccessoryStore:listenCallFunc(L_AccessoryStore.event.refreshAccessory, self.onEvent_refreshAccessory, self)
  L_AccessoryStore:listenCallFunc(L_AccessoryStore.event.refreshAccessoryList, self.onEvent_refreshAccessory, self)
  L_AccessoryStore:listenCallFunc(L_AccessoryStore.event.changeLock, self.onChangeLock, self)
  L_SpiritronStore:listenCallFunc(L_SpiritronStore.event.refreshWeapon, self.refreshPage, self)
  L_SpiritronStore:listenCallFunc(L_SpiritronStore.event.switchSpirit, self.onEvent_refreshSpirit, self)
end

function this:close()
  L_HeroStore:unListenCallFunc(L_HeroStore.event.setCurHeroGuid, self.onEvent_setCurHeroID)
  AzurWorld.heroMgr:UnregisterEvent(C_EHeroEvent.ESyncHeroServerDataList, self._ESyncHeroServerDataHandler)
  L_AccessoryStore:unListenCallFunc(L_AccessoryStore.event.refreshAccessory, self.onEvent_refreshAccessory)
  L_AccessoryStore:unListenCallFunc(L_AccessoryStore.event.refreshAccessoryList, self.onEvent_refreshAccessory)
  L_AccessoryStore:unListenCallFunc(L_AccessoryStore.event.changeLock, self.onChangeLock)
  L_SpiritronStore:unListenCallFunc(L_SpiritronStore.event.refreshWeapon, self.refreshPage)
  L_SpiritronStore:unListenCallFunc(L_SpiritronStore.event.switchSpirit, self.onEvent_refreshSpirit)
end

function this:onChangeLock(isLock)
  self.isChangeLock = isLock
end

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

function this:refreshPage()
  self._heroGuid = self:getModeController():getSelectGuid()
  self:initAccessorySlotList()
  self:initAttBase()
  self._spiritGuid = L_HeroStore:getHeroSpiritronGuid(self:getHero(self._heroGuid))
  self:initSpiritInfoText()
  self.bind.go_emptyTips = not self.bHasEquipSuit and math.isEmpty(self._spiritGuid)
end

function this:initAccessorySlotList()
  local tmp = {}
  for i, v in ipairs(accessory) do
    table.insert(tmp, {
      type = v,
      index = v,
      heroId = self._heroGuid,
      go_empty = true,
      go_equipped = false
    })
  end
  local accessoryList = self:dealAccessoryData(L_HeroStore:getHeroAccessoryGuidList(self:getHero(self._heroGuid)))
  for i, v in ipairs(accessoryList) do
    if not math.isEmpty(v) then
      local serverData = L_AccessoryStore:getAccessory(v)
      local configData = L_ItemTplManager:getAccessoryItem(serverData.accessoryId)
      local tpl = _accessoryTpl:getTplById(serverData.accessoryId)
      tmp[i].go_equipped = true
      tmp[i].go_empty = false
      tmp[i].guid = v
      tmp[i].accessoryId = serverData.accessoryId
      tmp[i].isPreview = self:isPreviewMode()
      tmp[i].go_btnStrength = not L_AccessoryStore:getIsMaxLevel(v)
      tmp[i].img_quality_angle = string.format("UI/Atlas/EquipmentRarityep/tex_icon_equipment_rarityep_%s.png", configData.quality + 1)
      tmp[i].img_icon = _accessoryTpl:getSlotIcon(tpl)
      tmp[i].txt_level = tostring(serverData.level)
      local headRank = _accessoryTpl:getHeadRank(tpl)
      tmp[i].go_headRank = 0 < headRank
      if 0 < headRank then
        tmp[i].img_headRank = L_AccessoryStore:getAccessoryHeadRankIcon(headRank)
      end
    end
  end
  self.bind.list_slot:freshAll(tmp)
  self.accessoryData = tmp
  self:setAccessoryType(self._accessoryType)
end

function this:initSpiritInfoText()
  local isEmpty = math.isEmpty(self._spiritGuid)
  self.bind.go_spiritSkill = not isEmpty
  if isEmpty then
    return
  end
  local serverData = L_SpiritronManager:getSpiritronItem(self._spiritGuid, false)
  local spiritronCfg = _spiritronTpl:getTplById(serverData.spiritronId)
  self.bind.txt_spiritInfo = L_WordsTpl:getValue("ui_heroRole_23") .. _spiritronTpl:getName(spiritronCfg)
  local rarity = _spiritronTpl:getRarity(spiritronCfg)
  local _, color = C_ColorUtility.TryParseHtmlString(quality_color[rarity])
  self.bind.color_quality = color
  local startList = {}
  for i = 1, serverData.star - 1 do
    table.insert(startList, {})
  end
  self.bind.list_star:clear()
  self.bind.list_star:insert_array(startList)
end

function this:initAttBase()
  local onClick_item = function(cell)
    self.modules.propetyPanel:initModule({
      heroData = self:getHero(self._heroGuid),
      detailId = L_Const.propertyDetail.equipment
    })
    self.modules.propetyPanel:setPanelActive(true)
  end
  local accessoryList = L_HeroStore:getHeroAccessoryGuidList(self:getHero(self._heroGuid))
  local brief = L_AccessoryManager:getEquipListSuitBrief(accessoryList)
  local tmp2 = {}
  for i, v in pairs(brief) do
    table.insert(tmp2, {
      attrIcon = "UI/Atlas/AccessoryPage/tex_equipment_icon_tz.png",
      value = v.txt_suitValue,
      name = v.txt_suitName,
      cbk = onClick_item
    })
  end
  self.bind.go_acclist = not table.isEmpty(tmp2)
  self.bind.list_accAtt:clear()
  self.bind.list_accAtt:insert_array(tmp2)
  self.bHasEquipSuit = 0 < #tmp2
end

function this:dealAccessoryData(accessoryList)
  local newAccessoryList = {}
  for i = 1, #accessoryList do
    if i == 1 then
      newAccessoryList[3] = accessoryList[i]
    elseif i == 2 then
      newAccessoryList[4] = accessoryList[i]
    elseif i == 3 then
      newAccessoryList[2] = accessoryList[i]
    elseif i == 4 then
      newAccessoryList[1] = accessoryList[i]
    else
      newAccessoryList[i] = accessoryList[i]
    end
  end
  return newAccessoryList
end

function this:getShowHeroAssets()
  return true
end

function this:onEvent_setCurHeroID(heroID, oldHeroID)
  self:refreshPage()
end

function this:onEvent_refreshAccessory(entity)
  if self.isChangeLock then
    return
  end
  self._heroGuid = self:getModeController():getSelectGuid()
  self:initAccessorySlotList()
  self:initAttBase()
  self.bind.go_emptyTips = not self.bHasEquipSuit and math.isEmpty(self._spiritGuid)
end

function this:onEvent_refreshSpirit()
  self:refreshPage()
end

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

function this:onClickQuickEquipAccessory()
  local targetAccessoryGuidList, accessoryNeedOpenConfirmTip = self:getQuickEquipTargetAccessoryGuidList()
  local targetSpiritronGuid, spiritronNeedOpenConfirmTip = self:getQuickEquipTargetSpiritronGuid()
  local needOpenConfirmTip = accessoryNeedOpenConfirmTip or spiritronNeedOpenConfirmTip
  if table.isEmpty(targetAccessoryGuidList) and targetSpiritronGuid == nil then
    L_FlyMsgManager:showNormalMsg(L_Lang:get(L_WordsTpl:getValue("ui_one_key_no_equip")))
    return
  end
  local requestQuickEquipAccessory = function()
    L_AccessoryStore:req_quickWearAccessory({
      heroGuid = self._heroGuid,
      accessoryGuidList = targetAccessoryGuidList
    }, function()
      if self.bind.go_accessory then
        self:moduleAccessoryOpen(self._heroGuid, self._accessoryType)
      end
    end)
  end
  if needOpenConfirmTip then
    L_GameUtil.showCommonTip({
      txtContent = L_Lang:get(L_WordsTpl:getValue("ui_notice_one_key_equip")),
      confirmCallback = requestQuickEquipAccessory
    })
  else
    requestQuickEquipAccessory()
  end
end

function this:getQuickEquipTargetAccessoryGuidList()
  local accessoryList = L_AccessoryStore:getHeroAccessory()
  local accessoryType2AccessoryList = {}
  for _, accessoryType in ipairs(accessory) do
    accessoryType2AccessoryList[accessoryType] = accessoryType2AccessoryList[accessoryType] or {}
    for _, accessory in pairs(accessoryList) do
      local accessoryTpl = _accessoryTpl:getTplById(accessory.accessoryId)
      if _accessoryTpl:getType(accessoryTpl) == accessoryType and (accessory.wearHero == 0 or accessory.wearHero == self._heroGuid) then
        table.insert(accessoryType2AccessoryList[accessoryType], accessory)
      end
    end
    table.sort(accessoryType2AccessoryList[accessoryType], function(left, right)
      local leftConfigId = left.accessoryId
      local rightConfigId = right.accessoryId
      local leftAccessoryTpl = _accessoryTpl:getTplById(leftConfigId)
      local rightAccessoryTpl = _accessoryTpl:getTplById(rightConfigId)
      local leftRarity = _accessoryTpl:getRarity(leftAccessoryTpl)
      local rightRarity = _accessoryTpl:getRarity(rightAccessoryTpl)
      left.rarity = leftRarity
      right.rarity = rightRarity
      local leftLevel = left.level
      local rightLevel = right.level
      local leftGuid = left.guid
      local rightGuid = right.guid
      if leftRarity ~= rightRarity then
        return leftRarity > rightRarity
      end
      if leftLevel ~= rightLevel then
        return leftLevel > rightLevel
      end
      if leftConfigId ~= rightConfigId then
        return leftConfigId > rightConfigId
      end
      if leftGuid ~= rightGuid then
        return leftGuid > rightGuid
      end
      return false
    end)
    printf(string.format("\228\184\128\233\148\174\232\163\133\229\164\135 accessoryType:%d \230\142\146\229\186\143\229\144\142\231\154\132\232\163\133\229\164\135list", accessoryType), accessoryType2AccessoryList[accessoryType])
  end
  local accessoryType2targetAccessory = {}
  for _, accessoryType in ipairs(accessory) do
    accessoryType2targetAccessory[accessoryType] = accessoryType2AccessoryList[accessoryType][1]
  end
  local heroAccessoryGuidList = L_HeroStore:getHeroAccessoryGuidList(L_HeroStore:getHero(self._heroGuid))
  local accessoryType2HeroAccessoryGuid = {}
  for _, heroAccessoryGuid in pairs(heroAccessoryGuidList) do
    if heroAccessoryGuid ~= 0 then
      local heroAccessory = L_AccessoryStore:getAccessory(heroAccessoryGuid)
      local accessoryTpl = _accessoryTpl:getTplById(heroAccessory.accessoryId)
      local heroAccessoryType = _accessoryTpl:getType(accessoryTpl)
      accessoryType2HeroAccessoryGuid[heroAccessoryType] = heroAccessoryGuid
    end
  end
  printf("\228\184\128\233\148\174\232\163\133\229\164\135 \232\139\177\233\155\132\232\186\171\228\184\138\231\154\132\232\163\133\229\164\135guidList", accessoryType2HeroAccessoryGuid)
  local needOpenConfirmTip = false
  for _, accessoryType in ipairs(accessory) do
    local targetAccessory = accessoryType2targetAccessory[accessoryType]
    local heroAccessoryGuid = accessoryType2HeroAccessoryGuid[accessoryType]
    if targetAccessory and heroAccessoryGuid then
      if targetAccessory.guid == heroAccessoryGuid then
        accessoryType2targetAccessory[accessoryType] = nil
      else
        needOpenConfirmTip = true
      end
    end
  end
  local targetAccessoryGuidList = {}
  for _, accessoryType in ipairs(accessory) do
    local taegetAccessory = accessoryType2targetAccessory[accessoryType]
    if taegetAccessory then
      table.insert(targetAccessoryGuidList, taegetAccessory.guid)
    end
  end
  return targetAccessoryGuidList, needOpenConfirmTip
end

function this:getQuickEquipTargetSpiritronGuid()
  local oriSpiritronList = L_SpiritronStore:getSpiritronList()
  local spiritronList = {}
  for _, spiritronItem in pairs(oriSpiritronList) do
    if spiritronItem.spiritronHero == 0 or spiritronItem.spiritronHero == self._heroGuid then
      table.insert(spiritronList, spiritronItem)
    end
  end
  table.sort(spiritronList, function(left, right)
    local leftConfigId = left.spiritronId
    local rightConfigId = right.spiritronId
    local leftSpiritronTpl = _spiritronTpl:getTplById(leftConfigId)
    local rightSpiritronTpl = _spiritronTpl:getTplById(rightConfigId)
    local leftRarity = _spiritronTpl:getRarity(leftSpiritronTpl)
    local rightRarity = _spiritronTpl:getRarity(rightSpiritronTpl)
    left.rarity = leftRarity
    right.rarity = rightRarity
    local leftLevel = left.spiritronLv
    local rightLevel = right.spiritronLv
    local leftGuid = left.guid
    local rightGuid = right.guid
    if leftRarity ~= rightRarity then
      return leftRarity > rightRarity
    end
    if leftLevel ~= rightLevel then
      return leftLevel > rightLevel
    end
    if leftConfigId ~= rightConfigId then
      return leftConfigId > rightConfigId
    end
    if leftGuid ~= rightGuid then
      return leftGuid > rightGuid
    end
    return false
  end)
  printf("\228\184\128\233\148\174\232\163\133\229\164\135 \230\142\146\229\186\143\231\173\155\233\128\137\229\144\142\231\154\132\231\129\181\229\173\144list", spiritronList)
  local needOpenConfirmTip = false
  local targetSpirition = spiritronList[1]
  local targetSpiritronGuid = targetSpirition and targetSpirition.guid or nil
  local heroSpiritronGuid = L_HeroStore:getHeroSpiritronGuid(self:getHero(self._heroGuid))
  printf("\228\184\128\233\148\174\232\163\133\229\164\135 \232\139\177\233\155\132\232\186\171\228\184\138\231\154\132\231\129\181\229\173\144guid", heroSpiritronGuid)
  if not math.isEmpty(heroSpiritronGuid) then
    if targetSpiritronGuid == heroSpiritronGuid then
      targetSpiritronGuid = nil
    else
      needOpenConfirmTip = true
    end
  end
  return targetSpiritronGuid, needOpenConfirmTip
end

function this:onClickReplaceAccessory()
  local accessoryList = L_HeroStore:getHeroAccessoryGuidList(self:getHero(self._heroGuid))
  local targetAccessoryType = accessory[1]
  for accessoryType, accessoryGuid in pairs(accessoryList) do
    if math.isEmpty(accessoryGuid) then
      targetAccessoryType = accessoryType
      break
    end
  end
  L_UI:open("pageAccessoryBag", {
    accessoryType = targetAccessoryType,
    selectHeroGuid = self._heroGuid
  })
end

function this:getCanClose()
  if self._accessoryType ~= nil then
    self:moduleAccessoryClose()
    return false
  end
  return true
end

function this:moduleAccessoryOpen(selectHeroGuid, accessoryType)
  if self._accessoryType == nil then
    self.modules.module_accessory.isCompare = false
  end
  self.parent:setBlurActive(true)
  self.parent:setBgToggles(false)
  self:setAccessoryType(accessoryType)
  self.modules.module_accessory:setData(selectHeroGuid, accessoryType)
  self.bind.go_accessory = true
  self.bind.go_infoMask = true
end

function this:moduleAccessoryClose()
  self.bind.go_accessory = false
  self.bind.go_infoMask = false
  self.modules.module_accessory:resetData()
  self:setAccessoryType(nil)
  self.parent:setBlurActive(false)
  self.parent:setBgToggles(true)
end

function this:setAccessoryType(accessoryType)
  self._accessoryType = accessoryType
  for _, v in ipairs(self.bind.list_slot:getItemCls()) do
    v:setActive(v.bind.type == accessoryType)
  end
end

return this
