local this = class("modulePetCatalogDetail", G_UIModuleBase)
local _petTpl = L_GameTpl:getPetTpl()
local _petHomeTalentTpl = L_GameTpl:getPetHomeTalentTpl()
local _homeTalentTpl = L_GameTpl:getHomeTalentTpl()
local _mountTpl = L_GameTpl:getMountTpl()
local _petRaceTpl = L_GameTpl:getPetRaceTpl()
local _iconographyLevelTpl = L_GameTpl:getIconographyLevelTpl()
local _iconographyTypeTpl = L_GameTpl:getIconographyTypeTpl()
local _battleTpl = L_GameTpl:getBattleInfoTpl()
local _elementTpl = L_GameTpl:getElementTypeTpl()
local _petDetailTpl = L_GameTpl:getPetDetailUiParamTpl()
local _unitTpl = L_GameTpl:getUnitTpl()
local C_TDPetHomeTalentTable = CS.Azur.Gameplay.Table.TDPetHomeTalentTable
local PETSCENEPATH = "Program/UIScene/petCatalogScene.prefab"
local PETGETBLACKPATH = "Program/UIScene/pre_KiboCatalogAddBlack.prefab"
local BGNORMAL = "PetCatalog/tex_petillustrative_bg_15"
local BGFULL = "PetCatalog/tex_petillustrative_bg_16"
local colorNml = "#9BAABD"
local colorFull = "#BFA98E"
local mountType = {
  [1] = "\233\153\134\232\161\140",
  [2] = "\233\163\158\232\161\140",
  [3] = "\230\176\180\233\157\162",
  [4] = "\230\189\156\232\161\140"
}

function this:ctor(...)
  this.super.ctor(self, ...)
  self._is3D = true
end

function this.bind()
  return {
    petSceneActive = true,
    modulePetCard = {
      moduleName = "pages/pet/new/modulePetCard"
    },
    petCardActive = false,
    active_flashNone = true,
    active_flashSelect = false,
    color_flash = C_Color(0.7411765, 0.7921569, 0.7764706, 1),
    active_specialNone = true,
    active_specialSelect = false,
    color_special = C_Color(0.7411765, 0.7921569, 0.7764706, 1),
    txtIs3D = "2D",
    obtainActive = false,
    unObtainActive = false,
    txtPetIndex = "",
    txtPetName = "",
    modulePetTags = {
      moduleName = "pages/pet/new/modulePetNewSimpleTags"
    },
    list_homeTalent = {
      moduleName = "pages/petCatalogue/cellCatalogTalent"
    },
    list_attrTag = {
      moduleName = "pages/pet/new/cellNewTagItem"
    },
    active_mountType = true,
    active_bg2 = false,
    list_mountType = {
      moduleName = "pages/pet/new/cellPetMoveType"
    },
    list_drop = {
      moduleName = "pages/petCatalogue/cellPetDrop"
    },
    txtPetRace = "",
    txtPetStage = "",
    txtPetSize = "",
    txtPetDesc = "",
    list_skill = {
      moduleName = "pages/petCatalogue/cellPetCatalogSkill"
    },
    img_taskLevel = "",
    txtTaskLevel = "",
    txtLevelTip = "",
    sliderLevelExpValue = 0,
    active_lockTip = true,
    txtLockTip = "",
    listReward = {
      moduleName = "pages/petCatalogue/cellPetTaskRewardTag"
    },
    color_itemTitle = C_Color(1, 1, 1, 1),
    color_lineTitle = C_Color(1, 1, 1, 1),
    listTaskItem = {
      moduleName = "pages/petCatalogue/cellCatalogTaskItem"
    },
    redDotActive = false,
    taskBorderBg = "",
    txtRewardActive = true,
    txtFullActive = false,
    colorTip = C_Color(1, 1, 1),
    colorTask = C_Color(1, 1, 1),
    titleNmlActive = true,
    titleFullActive = false,
    txtFull = "",
    txtFullReward = L_Lang:get(L_WordsTpl:getValue("ui_iconography_upgrade"))
  }
end

function this.methods()
  return {
    onClickFlash = function(self)
      self._isFlash = not self._isFlash
      self.bind.active_flashSelect = self._isFlash
      self.bind.active_flashNone = not self._isFlash
      if self._isFlash then
        self.bind.color_flash = C_Color(1, 1, 1, 1)
        local _, topColor = C_ColorUtility.TryParseHtmlString("#DCD9C6")
        local _, bottomColor = C_ColorUtility.TryParseHtmlString("#FBDF9A")
        self.bindComponents.flashTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
      else
        self.bind.color_flash = C_Color(0.7411765, 0.7921569, 0.7764706, 1)
        local _, topColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
        local _, bottomColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
        self.bindComponents.flashTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
      end
      self:set3DMode()
    end,
    onClickSpecial = function(self)
      local tpl = _petTpl:getTplById(self._petId)
      local unitId = _petTpl:getUnitID(tpl)
      local specialParm = _unitTpl:getSpecialParm(_unitTpl:getTplById(unitId))
      if string.isEmpty(specialParm[1]) then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_iconography_not_have_special"))
        return
      end
      self._isSpecial = not self._isSpecial
      self.bind.active_specialSelect = self._isSpecial
      self.bind.active_specialNone = not self._isSpecial
      if self._isSpecial then
        self.bind.color_special = C_Color(1, 1, 1, 1)
        local _, topColor = C_ColorUtility.TryParseHtmlString("#CBFADF")
        local _, bottomColor = C_ColorUtility.TryParseHtmlString("#9BD1F8")
        self.bindComponents.specialTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
      else
        self.bind.color_special = C_Color(0.7411765, 0.7921569, 0.7764706, 1)
        local _, topColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
        local _, bottomColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
        self.bindComponents.specialTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
      end
      self:set3DMode()
      self:setDetailInfo()
    end,
    onClickModel = function(self)
      self._is3D = not self._is3D
      if self._is3D then
        self.bind.txtIs3D = "2D"
      else
        self.bind.txtIs3D = "3D"
      end
      self:set3DMode()
    end,
    onClickTaskPreview = function(self)
      self.bind.redDotActive = false
      L_CatalogStore:setNotTask(self._petId)
      self.parent:refreshTaskRedDot()
      L_UI:open("pagePetCatalogReward", {
        petId = self._petId
      })
    end
  }
end

function this:open()
end

function this:close(options)
  this.super.close(self, options)
  if L_CommonUtil.isValid(self.petGo) then
    C_GameObject.Destroy(self.petGo)
  end
  if L_CommonUtil.isValid(self.petFlashObj) then
    C_GameObject.Destroy(self.petFlashObj)
  end
end

function this:setSceneGo(go)
  self.sceneGo = go
end

function this:showPet(petId)
  self._petId = petId
  self._isSpecial = false
  self._isFlash = false
  self.bind.color_flash = C_Color(0.7411765, 0.7921569, 0.7764706, 1)
  local _, topColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
  local _, bottomColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
  self.bindComponents.flashTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
  self.bind.color_special = C_Color(0.7411765, 0.7921569, 0.7764706, 1)
  _, topColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
  _, bottomColor = C_ColorUtility.TryParseHtmlString("#FFFFFF")
  self.bindComponents.specialTxt:SetColorGradient(topColor, topColor, bottomColor, bottomColor)
  local isGet = L_CatalogStore:isGetPet(petId)
  if isGet then
    self.bind.obtainActive = true
    self.bind.unObtainActive = false
    self:set3DMode()
    self:setDetailInfo()
    self:setTaskInfo()
    self.bind.redDotActive = L_CatalogStore:getIsTaskRedDot(petId)
  else
    self:refreshBlackPet(petId)
    self.bind.obtainActive = false
    self.bind.unObtainActive = true
  end
end

function this:set3DMode()
  if self._is3D then
    self.bind.petCardActive = false
    self:removePet()
    self:setPet(self._petId, self._isSpecial, self._isFlash)
  else
    self.bind.petCardActive = true
    self:removePet()
    self.modules.modulePetCard:setPidWithAnim(self._petId, self._isSpecial and 1 or 0, self._isFlash)
    self.modules.modulePetCard:setInitRdy()
  end
end

function this:setDetailInfo()
  local petData = _petTpl:getTplById(self._petId)
  if self._isSpecial then
    self.bind.txtPetIndex = tostring(petData.iconographyNum) .. "B"
  else
    self.bind.txtPetIndex = tostring(petData.iconographyNum)
  end
  self.bind.txtPetName = _petTpl:getName(petData, self._isSpecial and 1 or 0)
  self.modules.modulePetTags:setConfigId(self._petId, true)
  local params = {
    pointTo = 2,
    borderDistance = C_Vector2(30, 27),
    transSize = C_Vector2(100, 10)
  }
  self.modules.modulePetTags:setConfigId(self._petId, true, params)
  local C_TDPetHomeTalent = C_TDPetHomeTalentTable.GetData(self._petId)
  local lTalent = {}
  if C_TDPetHomeTalent then
    local C_LaborConfigInfoList = C_TDPetHomeTalent:GetLaborConfigInfoList()
    for i = 0, C_LaborConfigInfoList.Count - 1 do
      local C_LaborConfigInfo = C_LaborConfigInfoList[i]
      table.insert(lTalent, {
        id = C_LaborConfigInfo.laborTypeId
      })
    end
  end
  self.bind.list_homeTalent:clear()
  self.bind.list_homeTalent:insert_array(lTalent)
  local petHomeTalentTpl = _petHomeTalentTpl:getTplById(self._petId)
  local petSize = _petHomeTalentTpl:getSizeType(petHomeTalentTpl)
  self.bind.list_attrTag:clear()
  local tagData = {}
  local kiboFeatureSkill = L_PetManager:getFPropertySkillList(self._petId)
  for i, v in ipairs(kiboFeatureSkill) do
    table.insert(tagData, {
      type = i % 3 == 0 and 3 or i % 3,
      label = string.format("%s", v.skillName)
    })
  end
  self.bind.list_attrTag:insert_array(tagData)
  self.bind.list_mountType:clear()
  local tmp = {}
  if _mountTpl.data[self._petId] then
    local tpl_mount = _mountTpl:getTplById(self._petId)
    local moveType = _mountTpl:getMoveType(tpl_mount)
    if moveType then
      for i, v in pairs(moveType) do
        table.insert(tmp, {
          moveType = v,
          img_icon = string.format("UI/Atlas/PetSaddlePage/tex_petsaddle_icon_%s.png", v),
          txt_moveType = mountType[v]
        })
      end
    end
  end
  self.bind.active_mountType = 0 < #tmp
  self.bind.active_bg2 = 0 < #tmp
  self.bind.list_mountType:insert_array(tmp)
  local dropItem = {}
  self.bind.list_drop:clear()
  for _, id in ipairs(petData.iconographyDrop) do
    table.insert(dropItem, {id = id})
  end
  self.bind.list_drop:insert_array(dropItem)
  local stage = _petTpl:getPetStage(petData)
  self.bind.txtPetStage = L_GameTpl:getWordsTpl():getTplById("ui_pet_stage" .. stage)
  local race = _petTpl:getRace(petData)
  local txt_race = ""
  for i = 1, #race do
    local raceTpl = _petRaceTpl:getTplById(race[i])
    if i == 1 then
      txt_race = _petRaceTpl:getRaceType(raceTpl)
    else
      txt_race = string.format("%s\194\183%s", txt_race, _petRaceTpl:getRaceType(raceTpl))
    end
  end
  self.bind.txtPetRace = txt_race
  local size = _petTpl:getSize(petData)
  if math.isEmpty(size) then
    self.bind.txtPetSize = "???"
  else
    local integer, float = math.modf(tonumber(string.format("%.1f", size / 10000)))
    if float == 0 then
      self.bind.txtPetSize = string.format("%dcm", integer)
    else
      self.bind.txtPetSize = string.format("%.1fcm", size / 10000)
    end
  end
  self.bind.txtPetDesc = _petTpl:getDesc(petData)
  local skillList = _petTpl:getSignatureSkillList(petData)
  local sList = {}
  for _, skill in ipairs(skillList) do
    table.insert(sList, {
      id = skill[2],
      ele = _petTpl:getFirstElement(petData)
    })
  end
  self.bind.list_skill:clear()
  self.bind.list_skill:insert_array(sList)
end

function this:setTaskInfo()
  local petCatalogData = L_CatalogStore:getPetCatalogByPetId(self._petId) or {}
  local taskLevel = petCatalogData.lv or 1
  local tpl = L_GameTpl:getIconographyLevelTpl():getTplByLvPetId(taskLevel, self._petId)
  local nextTpl = tpl
  self.bind.img_taskLevel = tpl.iconparticulars or "PetCatalog/tex_petillustrative_icon_dw1"
  self.bind.txtTaskLevel = tpl.text
  self.bind.txtFull = tpl.text
  if taskLevel == 10 then
    self.bind.txtLevelTip = L_WordsTpl:getValue("ui_modulePetCatalogDetail_05")
    self.bind.taskBorderBg = BGFULL
    self.bind.titleNmlActive = false
    self.bind.titleFullActive = true
    self.bind.colorTip = C_LuaUtility.ParseHtmlStringColor(colorFull)
    self.bind.txtRewardActive = false
    self.bind.txtFullActive = true
    self.bind.color_itemTitle = C_Color(0.7490196, 0.6627451, 0.5568628, 1)
    self.bind.color_lineTitle = C_Color(0.854902, 0.7686275, 0.6666667, 1)
    self.bind.listReward:clear()
  else
    nextTpl = L_GameTpl:getIconographyLevelTpl():getTplByLvPetId(taskLevel + 1, self._petId)
    local curExp = petCatalogData.exp or 0
    local nextExp = tpl.exp
    self.bind.txtLevelTip = L_WordsTpl:getValue("ui_modulePetCatalogDetail_06", {
      [0] = curExp,
      [1] = nextExp
    })
    self.sliderLevelExpValue = curExp / tpl.exp
    self.bind.taskBorderBg = BGNORMAL
    self.bind.titleNmlActive = true
    self.bind.titleFullActive = false
    self.bind.colorTip = C_LuaUtility.ParseHtmlStringColor(colorNml)
    self.bind.txtRewardActive = true
    self.bind.txtFullActive = false
    self.bind.color_itemTitle = C_Color(0.6078432, 0.6666667, 0.7411765, 1)
    self.bind.color_lineTitle = C_Color(0.7686275, 0.8078431, 0.8352941, 1)
    local rewardInfo = L_DataUtil.parseRewardConfig(nextTpl.reward)
    self.bind.listReward:clear()
    self.bind.listReward:insert_array(rewardInfo)
  end
  if taskLevel == L_GameTpl:getGameConstTpl():getValue("ICONOGRAPHYLEVEL_UNLOCK_HABITAT") - 1 then
    self.bind.active_lockTip = true
    self.bind.txtLockTip = L_WordsTpl:getValue("ui_modulePetCatalogDetail_07")
  else
    self.bind.active_lockTip = false
    self.bind.txtLockTip = ""
  end
  local tasks = {}
  local taskGroup = _petTpl:getTplById(self._petId).iconographyTaskId
  for i = 1, #taskGroup do
    local taskId = taskGroup[i]
    local taskCnt = 0
    local isComplete = false
    if petCatalogData.tasks and petCatalogData.tasks[i] then
      taskId = petCatalogData.tasks[i].task_id or taskGroup[i]
      taskCnt = petCatalogData.tasks[i].count or 0
      isComplete = petCatalogData.tasks[i].complete
    end
    table.insert(tasks, {
      idx = i,
      taskId = taskId,
      taskCnt = taskCnt,
      isComplete = isComplete
    })
  end
  self.bind.listTaskItem:clear()
  self.bind.listTaskItem:insert_array(tasks)
end

function this:refreshBlackPet(petId)
  local setPetCallback = function()
    local blackObj = L_ResPool:syncGameObject(PETGETBLACKPATH)
    blackObj.transform:Reset(self.petGo.transform)
    blackObj.transform.localScale = L_Vector3.one
    blackObj.transform.localPosition = L_Vector3.zero
    blackObj.name = "blackRoot"
    local EffectMaterialHelperCom = blackObj.transform:GetComponent(typeof(CS.EffectMaterialHelper))
    if EffectMaterialHelperCom then
      EffectMaterialHelperCom.characterRoot = self.petGo
    end
    local EffectAutoMultiColCom = blackObj.transform:GetComponent(typeof(CS.EffectAutoMultiCol))
    if EffectAutoMultiColCom then
      EffectAutoMultiColCom.characterRoot = self.petGo
    end
    self:_setPetBlackColor(blackObj, C_Color(0, 0, 0, 1))
    blackObj:SetActive(false)
    blackObj:SetActive(true)
  end
  self:removePet()
  self:setPet(petId, false, false, true, setPetCallback)
end

function this:_setPetBlackColor(blackObj, color)
  local effectMaterialHelper = blackObj.transform:GetComponent(typeof(CS.EffectMaterialHelper))
  local EffectAutoMultiColCom = blackObj.transform:GetComponent(typeof(CS.EffectAutoMultiCol))
  local material = effectMaterialHelper.material
  material:SetColor("_IB_Color", color)
  local percent = 1 - color.a
  EffectAutoMultiColCom.effectMultiColor = C_Color(percent, percent, percent, 1)
  local cullings = effectMaterialHelper.curllings
end

function this:setPet(petId, isSpecial, isFlash, banAnim, callback)
  if math.isEmpty(petId) then
    self:removePet()
    return
  end
  local tpl = _petTpl:getTplById(petId)
  local unitId = _petTpl:getUnitID(tpl)
  local petPath = L_GameUtil.getAvatarModelPathByUnitId(unitId, L_Const.avatarModelIndex.UnitModel)
  if isSpecial then
    local specialParm = _unitTpl:getSpecialParm(_unitTpl:getTplById(unitId))
    if not string.isEmpty(specialParm[1]) then
      local replaceStr = specialParm[1]
      petPath = string.gsub(petPath, ".prefab", "_" .. replaceStr .. ".prefab")
    end
  end
  L_ResPool:asyncGameObject(petPath, function(go)
    local petGo = go
    self.petGo = petGo
    self.curPetGoId = petId
    petGo.name = string.concat("pet_", petId)
    local entity = L_EntityManager:generatePreviewPet(petId, petGo)
    local animator = L_CommonUtil.getModComponent(typeof(C_PlayableAnimator), petGo)
    if not banAnim then
      animator.enabled = true
      animator.cullingMode = C_AnimatorCullingMode.AlwaysAnimate
      animator.updateMode = C_PlayableAnimator.UpdateMode.LateUpdate
      animator.rootMotionController.selfApplyRootMotion = true
      entity.playableAnimator:Play("Idle")
    else
    end
    if not self.modelRoot then
      self.modelRoot = self.sceneGo.transform:Find("ModelRoot")
    end
    local script = self.modelRoot:GetComponent(typeof(CS.Lens.Gameplay.UI.CharacterAnchorFit))
    if L_CommonUtil.isValid(script) then
      script:SetBindObject(self.bindComponents.SceneRect)
    end
    petGo.transform:SetParent(self.modelRoot)
    local detailTpl = _petDetailTpl:getTplById(petId)
    local all_stage_scale = _petDetailTpl:getIconographyScale(detailTpl) or 10000
    local unitTpl = _unitTpl:getTplById(unitId)
    local worldScale = _unitTpl:getModelScale(unitTpl)
    local scale = all_stage_scale / 10000
    L_Vector3.setSize(petGo.transform, scale * worldScale)
    local position = _petDetailTpl:getIconographyPosition(detailTpl)
    if table.isEmpty(position) then
      L_Vector3.setLocalPos(petGo.transform, L_Vector3.zero)
    else
      L_Vector3.setLocalPos(petGo.transform, L_Vector3.new(position[1], position[2], position[3]))
    end
    L_Vector3.setLocalRot(petGo.transform, L_Vector3.new(0, 50, 0))
    self:_setPetFlashEft(isFlash, self.petGo)
    if callback then
      callback()
    end
  end)
end

function this:removePet()
  if L_CommonUtil.isValid(self.petGo) then
    C_GameObject.Destroy(self.petGo)
  end
end

function this:_setPetFlashEft(isFlash, petObj)
  if not isFlash then
    if self.petFlashObj then
      L_CommonUtil.setObjActive(self.petFlashObj, false)
      self.petFlashObj.transform:SetParent(self.modelRoot)
    end
    return
  end
  local obj
  if self.petFlashObj then
    obj = self.petFlashObj
  else
    local mediaPackTpl = L_GameTpl:getMediaPackTplTpl()
    local petFlashKey = L_Config:getConfig("game", "PET_FLASH_EFFECT_PATH")
    local path = mediaPackTpl:getPath(mediaPackTpl:getTplByKey(petFlashKey))
    obj = L_ResPool:syncGameObject(path)
  end
  local EffectMaterialHelperCom = obj.transform:GetComponentInChildren(typeof(CS.EffectMaterialHelper))
  if EffectMaterialHelperCom then
    EffectMaterialHelperCom.characterRoot = petObj
  end
  local ImmuneBuffHelperCom = obj.transform:GetComponentInChildren(typeof(CS.ImmuneBuffHelper))
  if ImmuneBuffHelperCom then
    ImmuneBuffHelperCom.characterRoot = petObj
  end
  local BindMeshEffectCom = obj.transform:GetComponentInChildren(typeof(CS.Lens.Gameplay.Modules.BigWorld.BindMeshEffect))
  if BindMeshEffectCom then
    BindMeshEffectCom:BindMeshBody(petObj)
  end
  obj.transform:SetParent(petObj.transform)
  L_CommonUtil.setObjActive(obj, false)
  L_CommonUtil.setObjActive(obj, true)
  L_Vector3.setLocalPos(obj.transform, L_Vector3.zero)
  L_Vector3.setLocalRot(obj.transform, L_Vector3.zero)
  L_Vector3.setSize(obj.transform, 1)
  self.petFlashObj = obj
end

return this
