local this = class("pageActivitySevenDaySign", G_UIPageBase)
local _unitTpl = L_GameTpl:getUnitTpl()
local _gameEventsTpl = L_GameTpl:getGameEventsTpl()
local _gameEventsDayAttendanceTpl = L_GameTpl:getGameEventsDayAttendanceTpl()
local PETSCENEPATH = "Program/UIScene/pre_chaluluhouse_night_ui_01.prefab"

function this:ctor(...)
  this.super.ctor(self, ...)
  self.data = {}
  self:initCharactorSceneAsync()
end

function this.bind()
  return {
    text_time = "",
    text_name = L_WordsTpl:getValue("ui_game_events_day_attendance_name"),
    text_desc = L_WordsTpl:getValue("ui_game_events_day_attendance_dialogue"),
    list_itemSign = {
      moduleName = "pages/gameAct/ActivitySevenDaySign/cellItemSign"
    }
  }
end

function this.methods()
  return {
    onClick_close = function(self)
      L_UI:close("pageActivitySevenDaySign")
    end,
    onClick_help = function(self)
      L_UI:open("pageCommonIntroduction", {
        groupId = self.introGroupId
      })
    end,
    list_itemSign = {
      onClick_sign = function(self, params)
        local hadReceiveCount = self.eventData.rewardCount
        local canReceiveCount = self.eventData.count
        if canReceiveCount >= params.indexItem and hadReceiveCount < params.indexItem then
          self.gameEventCls:req_activityDailySign(function(rsp_data)
            local rewards = rsp_data.rewards
            rewards.ignoreQueueCheck = true
            L_RewardManager:showPage(rewards, rsp_data.src, L_Const.pageRewardType.normal)
          end)
          return
        end
        local isClickReward = params.isClickReward
        if isClickReward then
          local itemType = params.itemType
          local itemId = params.itemId
          L_ItemTplManager:showInfoTip(itemType, itemId)
        end
      end
    }
  }
end

function this:preOpen(options)
  this.super.preOpen(self, options)
  options = options or {}
  self.gameEventType = options.gameEventType
  self.gameId = L_GameEventStore:getIdByType(self.gameEventType)
  if self.gameId == nil then
    L_UI:close("pageActivitySevenDaySign")
    errorf(string.format("\230\178\161\230\156\137\230\173\164\230\180\187\229\138\168\231\177\187\229\158\139 %d \231\154\132\230\149\176\230\141\174", self.gameEventType))
  end
  L_GameEventStore:listenCallFunc(L_GameEventStore.event.gameEventSync, self.refreshPage, self)
  L_GameEventStore:req_gameEventDatas()
  self:initPage()
end

function this:initCharactorSceneAsync()
  L_ResPool:asyncGameObject(PETSCENEPATH, function(go)
    self.sceneGo = go
    local sceneTrans = self.sceneGo.transform
    self.sceneCameraTrans = sceneTrans:Find("camera")
    sceneTrans:SetParent(C_LuaUtility.GetRootNode())
    L_Vector3.setPos(sceneTrans, L_Vector3.zero)
    L_Vector3.setRot(sceneTrans, L_Vector3.zero)
    local charactorUnitId = 104004
    local charactorModelPath = _unitTpl:getModel(_unitTpl:getTplById(charactorUnitId), L_Const.avatarModelIndex.UnitModel)
    C_LuaUtility.InstantiateAsync(charactorModelPath, function(go)
      local charactorGo = go
      self.charactorGo = charactorGo
      charactorGo.name = "charactor"
      local transPointCharactor = sceneTrans:Find("point_charactor")
      charactorGo.transform:SetParent(transPointCharactor)
      L_Vector3.setLocalPos(charactorGo.transform, L_Vector3.zero)
      local quaternion = Unity.Quaternion.Euler(0, 0, 0)
      charactorGo.transform.localRotation = quaternion
      local charactorEntity = require(L_EcsConst.aliveType.previewNpc).new(L_EcsConst.aliveType.previewNpc)
      charactorEntity:initPreview(charactorUnitId, charactorGo)
      charactorEntity.playableAnimator:Play("SignShow")
      self.canShowUiAndCamera = true
      self.canInitUiAndCamera = true
    end)
  end)
end

function this:initPage()
  self:initGameEventConfigData()
  self:getGameEventData()
  self:initTimer()
  self:initSignItems()
end

function this:initGameEventConfigData()
  self.eventTplIds = _gameEventsDayAttendanceTpl:getEventTplIdsByEventId(self.gameId)
  local gameEventsTpl = _gameEventsTpl:getTplById(self.gameId)
  self.introGroupId = _gameEventsTpl:getHelp(gameEventsTpl)
end

function this:getGameEventData()
  local gameEventData = L_GameEventStore:getGameEventData(self.gameId)
  self.gameEventStartTime = gameEventData:getStartTime()
  self.gameEventEndTime = gameEventData:getEndTime()
  self.gameEventCls = gameEventData:getGameEvent()
  self.eventData = self.gameEventCls:getData()
end

function this:initTimer()
  self:setTime()
  self:waitForShowingUiAndCamera()
  self.timer = Timer.new(function()
    self:setTime()
    self:waitForShowingUiAndCamera()
  end, 1, -1)
  self.timer:start()
end

function this:waitForShowingUiAndCamera()
  if self.sceneCameraTrans == nil then
    return
  end
  if self.canInitUiAndCamera == true then
    L_SceneManager:setSceneActive(false)
    self.sceneCameraTrans.gameObject:SetActive(true)
    self.canInitUiAndCamera = false
  end
end

function this:setTime()
  local timeNow = L_TimeUtil.getServerTime()
  local restTime = math.ceil(self.gameEventEndTime - timeNow)
  if restTime <= 0 then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_game_events_day_attendance_end"))
    L_UI:close("pageActivitySevenDaySign")
  end
  self.bind.text_time = L_WordsTpl:getValue("ui_game_events_day_attendance_time") .. L_TimeUtil.getLeftTimeString2(self.gameEventEndTime)
end

function this:initSignItems()
  local itemConfigList = {}
  local itemDate = 0
  local hadReceiveCount = self.eventData.rewardCount
  local canReceiveCount = self.eventData.count
  for _, eventTplId in pairs(self.eventTplIds) do
    itemDate = itemDate + 1
    local itemConfig = {}
    itemConfig.indexItem = itemDate
    itemConfig.eventTplId = eventTplId
    itemConfig.go_lock = hadReceiveCount >= itemDate
    itemConfig.go_glow = canReceiveCount >= itemDate and hadReceiveCount < itemDate
    table.insert(itemConfigList, itemConfig)
  end
  self.bind.list_itemSign:clear()
  self.bind.list_itemSign:insert_array(itemConfigList)
end

function this:refreshPage()
  self:getGameEventData()
  self.refreshSignItems = self.initSignItems
  self:refreshSignItems()
end

function this:show()
  if L_CommonUtil.isValid(self.sceneGo) and self.canShowUiAndCamera == true then
    self.sceneCameraTrans.gameObject:SetActive(true)
  end
end

function this:hide()
  if L_CommonUtil.isValid(self.sceneGo) then
    L_SceneManager:setSceneActive(true)
    self.sceneCameraTrans.gameObject:SetActive(false)
  end
end

function this:close()
  L_GameEventStore:unListenCallFunc(L_GameEventStore.event.gameEventSync, self.refreshPage)
  if self.timer ~= nil then
    self.timer:stop()
    self.timer = nil
  end
  if L_CommonUtil.isValid(self.sceneGo) then
    C_GameObject.Destroy(self.sceneGo)
  end
end

return this
