local this = class("moduleProductNormal", G_UIModuleBase)
local _ProductsTpl = L_GameTpl:getProductsTpl()
local _HomeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _HomeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
local _HomeBuildingProductTpl = L_GameTpl:getHomeBuildingProductionTpl()
local columnNum = L_DeviceTpl:getIsPc() and 7 or 6
local minLineNum = 3

function this.bind()
  return {
    list_product = {
      moduleName = "pages/product/cellProduceTarget"
    },
    list_decoration = {
      moduleName = "pages/product/cellDecorationItem"
    },
    produceTargetListActive = true,
    decorationListActive = false,
    module_top = {
      moduleName = "pages/product/moduleProductTop"
    },
    module_commonTab = {
      moduleName = "modulePages/tabList/moduleCommonTabList"
    },
    toggle_tabEmpty = false
  }
end

function this.methods()
  return {
    onClick_upgrade = function(self)
      if self.bind.toggle_lvMax then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_home_manage_13"))
        return
      end
      L_UI:open("pageBuildingUpgrade", {
        guid = self._guid
      })
    end,
    list_product = {
      onClick_selectId = function(self, id)
        self:onSelectTarget(id)
      end
    },
    list_decoration = {
      onClick_select = function(self, seriesId)
        self:setBuildingTargetListActive(seriesId)
      end,
      onClick_selectTarget = function(self, bind)
        self:onSelectTarget(bind.id)
      end
    }
  }
end

function this:open()
  function self._refreshView()
    self:refreshList()
  end
  
  L_HomeStore:listenCallFunc(L_HomeStore.event.syncWorldMapHomeItem, self._refreshView)
  L_ProductStore:listenCallFunc(L_ProductStore.event.refreshHomeProduct, self._refreshView)
end

function this:close()
  L_HomeStore:unListenCallFunc(L_HomeStore.event.syncWorldMapHomeItem, self._refreshView)
  L_ProductStore:unListenCallFunc(L_ProductStore.event.refreshHomeProduct, self._refreshView)
end

function this:initModule(guid)
  if not guid then
    return
  end
  self._guid = guid
  self._data = L_HomeStore:getHomeBuildingByGuid(guid)
  self._tpl = _HomeBuildingProductTpl:getTplById(self._data.build_id)
  self._type = L_HomeUtil.getBuildingType(guid)
  local tabs = _HomeBuildingProductTpl:getTab(self._tpl)
  self.bind.toggle_tabEmpty = #tabs <= 0
  if 0 < #tabs then
    self.modules.module_commonTab:setData(tabs, function(tabId)
      self._selectedId = 0
      self._seriesId = nil
      self._currTabId = tabId
      self:refreshList()
    end)
  else
    self:refreshList()
  end
  self.modules.module_top:initModule(guid)
end

function this:refreshList()
  if not self._guid then
    return
  end
  local isDeco = self._currTabId == tonumber(L_Config:getConfig("game", "HOME_SPECIALTABID_DECORATION"))
  self.bind.produceTargetListActive = not isDeco
  self.bind.decorationListActive = isDeco
  if isDeco then
    self:refreshBuildingProductTargetList()
  elseif self._type == L_Const.WorldMapBuildType.WMBT_COOK then
    self:setProductList(L_ProductManager:getTargetFoodForBuilding(self._data.build_id))
  else
    self:setProductList(L_ProductManager:getTargetProductForBuilding(self._data.build_id, self._currTabId))
  end
end

function this:setProductList(datas)
  local lineNum = math.ceil(#datas / columnNum)
  lineNum = math.max(lineNum, minLineNum)
  self.bindComponents.produceTargetList.disableScroll = lineNum <= minLineNum
  for i = 1, lineNum * columnNum - #datas do
    table.insert(datas, {isFood = false, itemData = false})
  end
  if #datas ~= #self.bind.list_product then
    self.bind.list_product:clear()
    self.bind.list_product:insert_array(datas)
  else
    for i = 1, #self.bind.list_product do
      self.bind.list_product:change(i, datas[i])
    end
  end
  if math.isEmpty(self._selectedId) and #self.bind.list_product > 0 then
    self:onSelectTarget(self.modules.list_product[1].bind.id)
  elseif math.isEmpty(self._selectedId) then
    self:onSelectTarget(0)
  end
end

function this:refreshBuildingProductTargetList(force)
  if not self._initedBuild or force then
    self._initedBuild = true
    local tmp = {}
    local _homeDecorationSeriesTpl = L_GameTpl:getHomeDecorationSeriesTpl()
    local products = L_ProductManager:getTargetProductForBuilding(self._data.build_id, self._currTabId)
    for _, product in pairs(products) do
      local productId = product.id
      local tpl_pro = _ProductsTpl:getTplById(productId)
      local reward = _ProductsTpl:getRewardId(tpl_pro)
      local itemData = L_DataUtil.parseRewardConfigItem(reward[1])
      local tpl_building = _HomeBuildingTpl:getTplById(itemData.itemId)
      local groupId = _HomeBuildingTpl:getGroupId(tpl_building)
      local tpl_buildingGroup = _HomeBuildingGroupTpl:getTplById(groupId)
      local seriesId = _HomeBuildingGroupTpl:getSeriesId(tpl_buildingGroup)
      local seriesTpl = _homeDecorationSeriesTpl:getTplById(seriesId)
      local lockString
      if seriesTpl then
        local unlockCondition = _homeDecorationSeriesTpl:getUnlockCondition(seriesTpl)
        local conditionDescs = L_ConditionManager:getDescs(unlockCondition)
        local isSatisfy, conditionRess = L_ConditionManager:isComplete(unlockCondition)
        if not isSatisfy then
          lockString = conditionDescs[1]
        end
      end
      if not tmp[seriesId] then
        tmp[seriesId] = {}
        tmp[seriesId].products = {}
        tmp[seriesId].seriesId = seriesId
        tmp[seriesId].isOpen = false
        tmp[seriesId].lockString = lockString
      end
      table.insert(tmp[seriesId].products, product)
    end
    local serialData = {}
    for _, v in pairs(tmp) do
      table.insert(serialData, v)
    end
    table.sort(serialData, function(a, b)
      return a.seriesId < b.seriesId
    end)
    for _ = 1, 4 - #serialData do
      table.insert(serialData, {isEmpty = true})
    end
    self.bind.list_decoration:clear()
    self.bind.list_decoration:insert_array(serialData)
  end
  self:setBuildingTargetListActive(self._seriesId or 0)
end

function this:setBuildingTargetListActive(id)
  if self._seriesId == id then
    return
  end
  self._seriesId = id
  for i = 1, #self.bind.list_decoration do
    self.bind.list_decoration:change(i, {
      isOpen = self.bind.list_decoration:getValue(i, "seriesId") == id
    })
  end
  Unity.UI.LayoutRebuilder.ForceRebuildLayoutImmediate(self.bindComponents.decorationListContent)
end

function this:onSelectTarget(id)
  self._selectedId = id
  for i = 1, #self.bind.list_product do
    self.bind.list_product:change(i, {
      selectIconActive = self.bind.list_product:getValue(i, "id") == id
    })
  end
  self.parent:onSelectId(id)
end

return this
