local this = class("cellProductQueue", G_UIModuleBase)
local _productsTpl = L_GameTpl:getProductsTpl()
local CellMode = {
  NORMAL = 1,
  NONE = 2,
  LOCK = 3
}
local CellMode2AnimationOnBindComponentName = {
  [CellMode.NORMAL] = "animation_normal_on",
  [CellMode.NONE] = "animation_none_on",
  [CellMode.LOCK] = "animation_lock_on"
}
local rarityepColorMap = {
  [-1] = "#ffffff80",
  [0] = "#a0aeb780",
  [1] = "#27ae8980",
  [2] = "#3ab3ff80",
  [3] = "#a264ff80",
  [4] = "#ffbf3580"
}
local _commonItemTpl = L_GameTpl:getCommonItemTpl()

function this.bind()
  return {
    tab_mode = -1,
    img_product = "",
    img_iconFilter = "",
    color_rarityep = nil,
    active_timeImg = false,
    txt_time = "",
    color_time = C_Color(1, 1, 1, 1),
    txt_finishNum = "",
    txt_totalNum = "",
    toggle_isEating = false,
    active_pause = false,
    toggle_finish = false,
    img_icon_getIcon = "",
    img_iconFilter_getIcon = "",
    color_rarityep_getIcon = nil,
    finish_FX = false,
    get_FX = false
  }
end

function this.methods()
  return {
    onClick_delete = function(self)
      if self._isFastQueue then
        self:onClickDelete_fastProduct()
      else
        self:onClickDelete_normalProduct()
      end
    end,
    onClick_reward = function(self)
      if self._isFastQueue then
        return
      end
      self:emit("onClickPageProductReward", self.bind)
    end,
    onClick_icon = function(self)
      if self._isFastQueue then
        return
      end
      self:emit("onClickPageProductReward", self.bind)
    end
  }
end

function this:close()
  L_TimerManager:clearTimer(self)
end

function this:open()
  self.hasSetNormalProductQueue = false
  self.hasSetFastProductQueue = false
  self:refresh()
  self.setNormalProductQueueTaskCount = 0
  self.setFastProductQueueTaskCount = 0
  L_TimerManager:newOrResetTimer(self, "setNormalProductQueueTask", function()
    if self.setNormalProductQueueTaskCount == 0 then
      return
    end
    if self:checkIsPlayingAnyAnimationOfNormalProduct() then
      return
    end
    self:setNormalProductQueue()
  end, 0.01, -1)
  L_TimerManager:newOrResetTimer(self, "setFastProductQueueTask", function()
    if self.setFastProductQueueTaskCount == 0 then
      return
    end
    if self:checkIsPlayingAnyAnimationOfFastProduct() then
      return
    end
    self:setFastProductQueue()
  end, 0.01, -1)
end

function this:refresh()
  self._isFastQueue = self.bind.queueData.isFastQueue and true or false
  if self._isFastQueue then
    if self:checkIsPlayingAnimProductQueueCompleteOfNormalProduct() and self.bind.queueData.isEmpty == true then
      self.setFastProductQueueTaskCount = 1
    else
      self:setFastProductQueue()
    end
  elseif self:checkIsPlayingAnyAnimationOfNormalProduct() then
    self.setNormalProductQueueTaskCount = 1
  else
    self:setNormalProductQueue()
  end
end

function this:onTimer()
  if self._isFastQueue then
    self:onTimer_fastProductQueue()
  else
    self:onTimer_normalProductQueue()
  end
end

function this:setFastProductQueue()
  L_TimerManager:stopTimer(self, "refresh")
  if not self.isBind then
    return
  end
  local productInfo = self.bind.queueData.product
  self._productInfo = productInfo
  if table.isEmpty(productInfo) then
    self:setTabMode(CellMode.NONE)
  else
    self:setTabMode(CellMode.NORMAL)
    local productId = productInfo.product_id
    local tpl = _productsTpl:getTplById(productId)
    if tpl == nil then
      return
    end
    local reward = _productsTpl:getRewardId(tpl)
    local itemData = L_DataUtil.parseRewardConfigItem(reward[1])
    local conf = L_ItemTplManager:getItemConfig(itemData.itemType, itemData.itemId)
    self.bind.img_product = conf.icon
    self.bind.img_icon_getIcon = conf.icon
    local commonItemTpl = _commonItemTpl:getTplById(conf.itemId)
    self.bind.img_iconFilter = commonItemTpl and _commonItemTpl:getFilterIcon(commonItemTpl) or ""
    self.bind.img_iconFilter_getIcon = commonItemTpl and _commonItemTpl:getFilterIcon(commonItemTpl) or ""
    local _, color = C_ColorUtility.TryParseHtmlString(rarityepColorMap[conf.quality])
    self.bind.color_rarityep = color
    self.bind.color_rarityep_getIcon = color
    local startTime = self._productInfo.start_time or 0
    local endTime = self._productInfo.finish_time or 0
    if 0 < startTime and 0 < endTime then
      L_TimerManager:newOrResetTimer(self, "refresh", function()
        self:onTimer()
      end, 0.5, -1)
      self:onTimer()
    else
      self.bind.txt_time = L_WordsTpl:getValue("ui_cellFastProductQueue_01")
      self.bind.color_time = C_Color(1, 1, 1, 0.8)
      self.bind.txt_finishNum = "0"
      self.bind.txt_totalNum = string.format("/%s", self._productInfo.total_count)
    end
  end
  self.hasSetFastProductQueue = true
  self.setFastProductQueueTaskCount = 0
end

function this:onTimer_fastProductQueue()
  if table.isEmpty(self._productInfo) then
    return
  end
  local productId = self._productInfo.product_id
  local totalNum = self._productInfo.total_count
  local finishNum = 0
  local startTime = self._productInfo.start_time
  local endTime = self._productInfo.finish_time
  if startTime == nil or startTime <= 0 and endTime == nil and endTime <= 0 then
    return
  end
  if self.hasSetFastProductQueue == true and self.isFinish == false and totalNum == 0 then
    self:playAnimProductQueueCompleteOfNormalProduct()
  end
  if totalNum == 0 then
    self.isFinish = true
    self.bind.txt_time = L_WordsTpl:getValue("notice_cellProductQueueNew_03")
    self.bind.color_time = C_Color(1.0, 0.7490196078431373, 0.20392156862745098, 1.0)
  else
    self.isFinish = false
    self.bind.color_time = C_Color(1, 1, 1, 1)
  end
  local nowTime = L_TimeUtil.getServerTimeWithFloor()
  local leftTime = math.ceil(endTime - nowTime)
  if leftTime <= 0 then
    leftTime = 0
  end
  self.bind.txt_time = L_TimeUtil.secondToLangString(leftTime)
  self.bind.txt_finishNum = string.format("%s", finishNum)
  self.bind.txt_totalNum = string.format("/%s", totalNum)
end

function this:onClickDelete_fastProduct()
  if table.isEmpty(self._productInfo) then
    return
  end
  self:hideFinishFX()
  self.isClose = true
  local guid = self._productInfo.product_guid
  L_ProductStore:req_CSProtoSimpleProductCancel(guid)
end

function this:checkIsPlayingAnimProductQueueCompleteOfNormalProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation and animation.isPlaying then
    return true
  end
  return false
end

function this:checkIsPlayingAnyAnimationOfFastProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation and animation.isPlaying then
    return true
  end
  animation = self.bindComponents[CellMode2AnimationOnBindComponentName[self.bind.tab_mode]]
  if animation and animation.isPlaying then
    return true
  end
  return false
end

function this:playAnimProductQueueCompleteOfFastProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation == nil then
    return
  end
  if animation.isPlaying then
    animation:Stop()
  end
  if not self.isClose then
    animation:Play("anim_product_queue_complete")
  end
  self.isClose = false
end

function this:hideFinishFX()
  local animation = self.bindComponents.animation_tab1_normal
  if animation == nil then
    return
  end
  if animation.isPlaying then
    animation:Stop()
  end
  self.bind.finish_FX = false
end

function this:setNormalProductQueue()
  L_TimerManager:stopTimer(self, "refresh")
  local isUnlock = self.bind.queueData.isUnlock
  local unlockLevel = self.bind.queueData.unlockLevel
  local csHomeBuildProductData = self.bind.queueData.csHomeBuildProductData
  local isEmpty = self.bind.queueData.isEmpty
  local buildingGuid = self.bind.queueData.buildingGuid
  self._csHomeBuildProductData = csHomeBuildProductData
  self._buildingGuid = buildingGuid
  local buildType = L_HomeUtil.getBuildingType(buildingGuid)
  if not isUnlock then
    self:setTabMode(CellMode.LOCK)
    self.bind.txt_condition = L_WordsTpl:getValue("ui_product_unlock_tip", {
      [0] = unlockLevel
    })
  elseif isEmpty then
    self:setTabMode(CellMode.NONE)
  else
    self:setTabMode(CellMode.NORMAL)
    local productId = self._csHomeBuildProductData.productId
    local tpl = _productsTpl:getTplById(productId)
    if buildType == L_Const.WorldMapBuildType.WMBT_HATCH then
      local petEggData = L_PetStore:getPetEggItem(self._csHomeBuildProductData.specialGuid)
      local petEggConf = L_ItemTplManager:getPetEggItem(petEggData.configId, self._csHomeBuildProductData.specialGuid)
      self.bind.img_product = petEggConf.icon
      self.bind.img_icon_getIcon = petEggConf.icon
      local _, color = C_ColorUtility.TryParseHtmlString(rarityepColorMap[petEggConf.quality])
      self.bind.color_rarityep = color
      self.bind.color_rarityep_getIcon = color
    else
      local reward = _productsTpl:getRewardId(tpl)
      local itemData = L_DataUtil.parseRewardConfigItem(reward[1])
      local conf = L_ItemTplManager:getItemConfig(itemData.itemType, itemData.itemId)
      local commonItemTpl = _commonItemTpl:getTplById(conf.itemId)
      self.bind.img_iconFilter = commonItemTpl and _commonItemTpl:getFilterIcon(commonItemTpl) or ""
      self.bind.img_iconFilter_getIcon = commonItemTpl and _commonItemTpl:getFilterIcon(commonItemTpl) or ""
      self.bind.img_product = conf.icon
      self.bind.img_icon_getIcon = conf.icon
      local _, color = C_ColorUtility.TryParseHtmlString(rarityepColorMap[conf.quality])
      self.bind.color_rarityep = color
      self.bind.color_rarityep_getIcon = color
    end
    L_TimerManager:newOrResetTimer(self, "refresh", function()
      self:onTimer()
    end, 0.5, -1)
    self:onTimer()
  end
  self.hasSetNormalProductQueue = true
  self.setNormalProductQueueTaskCount = 0
end

function this:onTimer_normalProductQueue()
  if self:checkIsPlayingAnimProductQueueGetOrCompleteOfNormalProduct() then
    return
  end
  local nowTime = L_TimeUtil.getServerTimeWithFloor()
  local state, petIsEating = L_ProductManager:getProductStateWithoutLuaData(self._buildingGuid, self._csHomeBuildProductData.guid)
  self.bind.active_pause = state == L_HomeConst.ProductQueueState.PAUSE
  local isHatch = L_HomeUtil.getBuildingType(self._buildingGuid) == L_Const.WorldMapBuildType.WMBT_HATCH
  if state == L_HomeConst.ProductQueueState.PAUSE then
    self.bind.active_timeImg = true
    if petIsEating then
      self.bind.txt_time = L_GameUtil.fillColor(L_WordsTpl:getValue("notice_cellProductQueueNew_01"), "#ffffff80")
    else
      self.bind.txt_time = L_GameUtil.fillColor(L_WordsTpl:getValue("notice_cellProduceItem_02"), "#ffffff80")
    end
    self.bind.toggle_isEating = petIsEating
  elseif state == L_HomeConst.ProductQueueState.FINISH then
    self.bind.active_timeImg = false
    self.bind.txt_time = L_GameUtil.fillColor(isHatch and L_WordsTpl:getValue("notice_cellProductQueueNew_02") or L_WordsTpl:getValue("notice_cellProductQueueNew_03"), "#ffbf35")
    self.bind.active_eggFinish = isHatch
  elseif state == L_HomeConst.ProductQueueState.WAITING then
    self.bind.active_timeImg = true
    self.bind.txt_time = L_WordsTpl:getValue("ui_cellFastProductQueue_01")
  else
    local leftTime = math.ceil(self._csHomeBuildProductData.totalFinishTime - nowTime)
    leftTime = leftTime <= 0 and 0 or leftTime
    self.bind.active_timeImg = leftTime ~= 0
    self.bind.txt_time = L_TimeUtil.secondToLangString(leftTime)
  end
  local finishCount = self._csHomeBuildProductData.finishCount
  local totalCount = self._csHomeBuildProductData.totalCount
  local allCount = finishCount + totalCount
  if self.hasSetNormalProductQueue == true and self.bind.toggle_finish == false and totalCount == 0 then
    self:playAnimProductQueueCompleteOfNormalProduct()
  end
  self.bind.toggle_finish = totalCount == 0
  self.bind.txt_finishNum = string.format("%s", finishCount)
  self.bind.txt_totalNum = string.format("/%s", allCount)
end

function this:onClickDelete_normalProduct()
  local data_tip = {
    txtTitle = L_WordsTpl:getValue("ui_product_cancle"),
    txtContent = L_WordsTpl:getValue("ui_product_cancle_tip"),
    confirmCallback = function()
      L_ProductManager:reqCancelProduct(self._buildingGuid, self._csHomeBuildProductData.guid)
    end
  }
  L_GameUtil.showCommonTip(data_tip)
end

function this:playAnimProductQueueCompleteOfNormalProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation == nil then
    return
  end
  if animation.isPlaying then
    animation:Stop()
  end
  animation:Play("anim_product_queue_complete")
end

function this:playAnimProductQueueGetOfNormalProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation == nil then
    return
  end
  if animation.isPlaying then
    animation:Stop()
  end
  animation:Play("anim_product_queue_get")
end

function this:checkIsPlayingAnimProductQueueGetOrCompleteOfNormalProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation and animation.isPlaying then
    return true
  end
  return false
end

function this:checkIsPlayingAnyAnimationOfNormalProduct()
  local animation = self.bindComponents.animation_tab1_normal
  if animation and animation.isPlaying then
    return true
  end
  animation = self.bindComponents[CellMode2AnimationOnBindComponentName[self.bind.tab_mode]]
  if animation and animation.isPlaying then
    return true
  end
  return false
end

function this:getCsHomeBuildProductData()
  return self._csHomeBuildProductData
end

function this:setTabMode(tabMode)
  local oldTabMode = self.bind.tab_mode
  self.bind.tab_mode = tabMode
  if oldTabMode ~= nil and oldTabMode ~= tabMode then
    local animation = self.bindComponents[CellMode2AnimationOnBindComponentName[self.bind.tab_mode]]
    if animation ~= nil then
      if animation.isPlaying then
        animation:Stop()
        return
      end
      animation:Play("anim_product_queue_normal_in")
    end
  end
end

return this
