local this = class("pagePlayerCard", G_UIPageBase)
local _playerTitleTpl = L_GameTpl:getPlayerTitleTpl()
local _playerLevelTpl = L_GameTpl:getPlayerLevelTpl()
local DisplayHeroCount = 3
local DisplayPetsCount = 4
local bottomWidth = 4231
local bottomHeight = 294
local bottomImgRatio = bottomHeight / bottomWidth
local bottomRatio = 1.343
local QUALITYTOIMG = {
  [L_Const.quality.n] = "Atlas/PlayerCardPage/tex_card_icon_chenjiuton",
  [L_Const.quality.r] = "Atlas/PlayerCardPage/tex_card_icon_chenjiuyin",
  [L_Const.quality.sr] = "Atlas/PlayerCardPage/tex_card_icon_chenjiujin"
}

function this.bind()
  return {
    moduleCommonTop = {
      moduleName = "modulePages/moduleCommonTop"
    },
    txt_name = nil,
    go_editName = false,
    txt_uid = nil,
    go_editMod = false,
    txt_level = nil,
    fill_exp = 1,
    txt_exp = nil,
    txt_nextExp = nil,
    txt_createTime = nil,
    txt_birthday = nil,
    go_editBirthday = false,
    txt_sign = nil,
    go_editSign = false,
    toggle_isEmptySign = false,
    list_hero = {
      moduleName = "pages/playerCard/cellSlotDisplay"
    },
    isOn_addFriend = false,
    list_pets = {
      moduleName = "pages/playerCard/cellPlayerCardPetPixelDisplay"
    },
    moduleCharacterStandee = {
      moduleName = "pages/playerCard/moduleCharacterStandee"
    },
    isActive_title = true
  }
end

function this.methods()
  return {
    onClick_copyUid = function(self)
      L_PlayerManager:copyUid(self._playerUid)
    end,
    onClick_editSign = function(self)
      L_SystemBreakManager:jumpTo(L_SystemConst.enum.playerDisplayText)
    end,
    onClick_editHead = function(self)
      L_FlyMsgManager:showNormalMsgByKey("ui_pagePlayerCard_02")
    end,
    onClick_editName = function(self)
      L_SystemBreakManager:jumpTo(L_SystemConst.enum.playerRename)
    end,
    onClick_addFriend = function(self)
      L_FriendManager:addFriend(self._playerUid)
    end,
    onClick_editBirth = function()
      L_UI:open("pageEditBirthday")
    end,
    onClick_editMod = function(self)
      local canMod = L_GameUtil.checkCanMod()
      if not canMod then
        return
      end
      self.bindComponents.anim_playerCard:Play("anim_playercard_gotoMod")
      L_LoadingManager:openSaveFormationLoading(nil, function()
        L_UI:open("pageMOD", {
          callback = function()
            L_TimerManager:newOrResetTimer(self, "closeLoading", function()
              L_LoadingManager:closeLoading()
            end, 0.2)
          end
        })
      end)
    end,
    list_hero = {
      onClick_add = function(self)
        L_UI:open("pageDisplayHero")
      end,
      onClick_select = function(self)
        if self._isSelfPlayer then
          L_UI:open("pageDisplayHero")
        end
      end
    },
    list_pets = {
      onClick_select = function(self)
        self:onClick_pets()
      end
    },
    onClick_bg = function(self)
    end
  }
end

function this:check(options, callback)
  local result = L_SystemUnlockManager:checkAndTip(L_SystemConst.enum.playerCard)
  callback(result)
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  self._playerUid = options.uid or L_PlayerStore:getPlayerId()
  self._isSelfPlayer = self._playerUid == L_PlayerStore:getPlayerId()
  if self._isSelfPlayer then
    L_PlayerStore:listenCallFunc(L_PlayerStore.event.refreshBaseInfo, self.onEvent_refreshBaseInfo, self)
    L_PlayerDisplayStore:buildRedDotTree()
    L_PlayerDisplayStore:listenCallFunc(L_PlayerDisplayStore.event.dressItemSync, self.onEvent_dressItemSync, self)
  else
    L_FriendStore:listenCallFunc(L_FriendStore.event.refreshIdList, self.onEvent_refreshIdList, self)
  end
  self:initPage()
  self:syncBottomRect()
end

function this:show()
  self:initPets()
end

function this:close(options)
  this.super.close(self, options)
  if self._isSelfPlayer then
    L_PlayerStore:unListenCallFunc(L_PlayerStore.event.refreshBaseInfo, self.onEvent_refreshBaseInfo)
    L_PlayerDisplayStore:unListenCallFunc(L_PlayerDisplayStore.event.dressItemSync, self.onEvent_dressItemSync)
  else
    L_FriendStore:unListenCallFunc(L_FriendStore.event.refreshIdList, self.onEvent_refreshIdList)
  end
  L_PhotoManager:clearPhotoEntity(self.bindComponents.img_head)
  L_PhotoManager:clearPhotoEntity(self.bindComponents.img_playerHalf)
  L_TimerManager:clearTimer(self)
end

function this:initPage()
  self:initMenu()
  self:initTopBar()
  self:initInfo()
end

function this:initTopBar()
  local data = {
    name = L_WordsTpl:getValue("ui_pagePlayerCard_01"),
    helpBtnBool = false,
    mainBtnBool = true,
    closeCurPage = function()
      L_UI:close(self.pageName)
    end,
    helpBtn = function()
    end,
    mainBtn = function()
      L_UI:backToRoot()
    end
  }
  self.modules.moduleCommonTop:initModule(data)
end

function this:initMenu()
end

function this:initInfo()
  local baseInfo = self._isSelfPlayer and L_PlayerStore:getPlayerBaseInfo() or L_FriendStore:getPlayerBaseInfo(self._playerUid)
  self.bind.go_editTitle = self._isSelfPlayer
  self.bind.txt_name = L_FriendStore:getPlayerName(baseInfo)
  self.bind.go_editName = self._isSelfPlayer
  self.bind.txt_uid = string.format("UID:%s", self._playerUid)
  local unlockMod = L_SystemUnlockManager:check(L_SystemConst.enum.mod)
  self.bind.go_editMod = unlockMod and self._isSelfPlayer
  local lv, isMaxLv = L_FriendStore:getPlayerLevel(baseInfo)
  local exp = L_FriendStore:getPlayerExp(baseInfo)
  self.bind.txt_level = string.format("Lv.%s", lv)
  local tpl_level = _playerLevelTpl:getTplById(lv)
  local totalExp = _playerLevelTpl:getExp(tpl_level)
  self.bind.fill_exp = isMaxLv and 1 or exp / totalExp
  self.bind.txt_exp = isMaxLv and "MAX" or tostring(exp)
  self.bind.txt_nextExp = isMaxLv and "/MAX" or "/" .. totalExp
  L_PhotoManager:newOrBindPhotoEntity(self.bindComponents.img_head, self.bindComponents.img_head, L_FriendStore:getPlayerAvatarsFormationHead(baseInfo))
  self.bind.txt_createTime = L_TimeUtil.getDisplayTime(L_FriendStore:getPlayerRegisterTime(baseInfo), L_TimeUtil.TimeFormat.YMD)
  local birthday = L_FriendStore:getPlayerBirthday(baseInfo)
  local notSetBirth = table.isEmpty(birthday)
  self.bind.txt_birthday = notSetBirth and (self._isSelfPlayer and "" or L_WordsTpl:getValue("notice_friend_unknown")) or L_WordsTpl:getValue("notice_playercard_birthday", {
    month = birthday.month,
    day = birthday.day
  })
  self.bind.go_editBirthday = self._isSelfPlayer and notSetBirth
  self.bind.go_editSign = self._isSelfPlayer
  local sign = L_FriendStore:getPlayerSign(baseInfo)
  self.bind.toggle_isEmptySign = string.isEmpty(sign)
  self.bind.txt_sign = sign
  self.bind.isOn_addFriend = not self._isSelfPlayer and not L_FriendStore:getIsFriend(self._playerUid)
  local tmp = {}
  local hero = L_FriendStore:getPlayerDisplayHero(baseInfo)
  for i = 1, DisplayHeroCount do
    local dataSrc = {}
    local headUrl
    if hero[i] then
      dataSrc.guid = hero[i].id
      dataSrc.configId = hero[i].config
      dataSrc.lv = hero[i].lv
      if dataSrc.configId == L_GameConstTpl:getMaleDefaultHeroConfigId() or dataSrc.configId == L_GameConstTpl:getFemaleDefaultHeroConfigId() then
        headUrl = L_FriendStore:getPlayerAvatars(baseInfo, L_Const.avatarTextureIndex.head_talk)
        dataSrc.type = L_Const.HeroType.HT_MAIN
      end
    end
    table.insert(tmp, {
      isEdit = self._isSelfPlayer,
      dataSrc = dataSrc,
      headUrl = headUrl
    })
  end
  local isInit = #self.modules.list_hero ~= DisplayHeroCount
  if isInit then
    self.bind.list_hero:clear()
    self.bind.list_hero:insert_array(tmp)
  else
    for i, v in pairs(self.modules.list_hero) do
      local cell = v
      cell:refreshView(tmp[i])
    end
  end
  self:initPets()
  self:initStandee(baseInfo)
end

function this:initPets()
  local baseInfo = self._isSelfPlayer and L_PlayerStore:getPlayerBaseInfo() or L_FriendStore:getPlayerBaseInfo(self._playerUid)
  local allPetInfo = L_FriendStore:getPlayerDisplayPet(baseInfo)
  local datas = {}
  if allPetInfo ~= nil then
    for _, v in pairs(allPetInfo) do
      local temp = {
        isActive_panelNone = false,
        isActive_panelSel = true,
        petInfo = v,
        guid = v.guid
      }
      local pos = v.pos
      if pos <= DisplayPetsCount then
        datas[pos] = temp
      end
    end
  end
  for i = 1, DisplayPetsCount do
    if datas[i] == nil then
      datas[i] = {
        isActive_panelNone = true,
        isActive_panelSel = false,
        guid = -1
      }
    end
    datas[i].isActive_nextLine = i < DisplayPetsCount
  end
  self.bind.list_pets:clear()
  self.bind.list_pets:insert_array(datas)
end

function this:onClick_pets()
  if self._isSelfPlayer then
    L_UI:open("pageSelectPetDisplay")
  end
end

function this:initStandee(baseInfo)
  local stand_plates = baseInfo.stand_plates
  self.modules.moduleCharacterStandee:setStandeeByBaseInfo(baseInfo)
end

function this:onEvent_refreshBaseInfo()
  self:initInfo()
end

function this:onEvent_refreshIdList()
  self:initInfo()
end

function this:onEvent_dressItemSync(id)
  if L_PlayerDisplayStore.redDotRootNode ~= nil then
    AzurWorld.RedDotMgr:MarkDirty(id)
  end
end

function this:update()
  self:syncBottomRect()
end

function this:syncBottomRect()
  local curWidth = C_UIMgr.root.rect.size.x
  if self.preWidth ~= curWidth then
    self.preWidth = curWidth
    if C_ResolutionUtility.CheckSuperWidthScreen() then
      self.bindComponents.bottomImgRect.sizeDelta = C_Vector2(bottomWidth, bottomHeight)
    else
      local targetWidth = curWidth * bottomRatio
      local targetHeight = targetWidth * bottomImgRatio
      self.bindComponents.bottomImgRect.sizeDelta = C_Vector2(targetWidth, targetHeight)
    end
  end
end

return this
