local this = class("moduleProduct", G_UIModuleBase)
local _productsTpl = L_GameTpl:getProductsTpl()
local _homeBuildingProductionTpl = L_GameTpl:getHomeBuildingProductionTpl()
local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()
local _accessoryTpl = L_GameTpl:getAccessoryTpl()
local _accessoryMainTpl = L_GameTpl:getAccessoryMainTpl()
local _battleInfoTpl = L_GameTpl:getBattleInfoTpl()
local _homeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
local _buildingTypeTpl = L_GameTpl:getHomeBuildingTypeTpl()
local _homeLaborCapacityTpl = L_GameTpl:getHomeLaborCapacityTpl()
local _petHomeSizeTpl = L_GameTpl:getPetHomeSizeTpl()
local _homeDecorationSeriesTpl = L_GameTpl:getHomeDecorationSeriesTpl()
local _foodTpl = L_GameTpl:getFoodTpl()
local _foodMaterialTpl = L_GameTpl:getFoodMaterialGroupTpl()
local _foodGroupTpl = L_GameTpl:getFoodGroupTpl()
local showType = {detail = "detail", queue = "queue"}
local columnNum = L_DeviceTpl:getIsPc() and 8 or 6
local minLineNum = 4

function this:ctor(...)
  this.super.ctor(self, ...)
  self.data = {
    productNum = 1,
    productId = nil,
    selectPlanId = nil,
    selectPlanTab = nil,
    buildingId = nil,
    buildingGuid = nil,
    buildingType = nil,
    selectMasterId = nil,
    isWorking = false,
    showStaus = showType.queue,
    currentTab = nil
  }
end

function this.bind()
  return {
    switchBtnActive = false,
    produceTargetList = {
      moduleName = "pages/product/cellProduceTarget"
    },
    module_num = {
      moduleName = "modulePages/moduleSelectNum"
    },
    modulePetInfo = {
      moduleName = "pages/product/modulePetInfo"
    },
    materialList = {
      moduleName = "pages/product/cellProductMaterial"
    },
    tagrgetItemDesc = "",
    targetItemSpeicalDesc = "",
    petIconActive = false,
    txt_time = "",
    buildingNameText = "",
    buildingLevelText = "",
    targetItem = L_Const.ModuleInfo.CellIconBag,
    buildTagActive = false,
    shortDesActive = true,
    chooseTipActive = false,
    produceList = {
      moduleName = "pages/product/cellProduceItem"
    },
    detailActive = false,
    queueActive = false,
    equipeDesScrollActive = false,
    longDesScrollActive = true,
    module_suit = {
      moduleName = "pages/accessory/moduleAccessorySuit"
    },
    moduleCommonTab = {
      moduleName = "modulePages/tabList/moduleCommonTabList"
    },
    decorationList = {
      moduleName = "pages/product/cellDecorationItem"
    },
    petTagActive = false,
    buildTypeText = "",
    petSizeText = "",
    laborTypeIcon = "",
    produceTargetListActive = true,
    decorationListActive = false,
    tabBgActive = false,
    emptyBgActive = true,
    maxNodeAcitve = false,
    upgradeBtnActive = true,
    active_foodAutoSelect = false,
    txt_foodAutoSelect = "",
    longDesNoralizeY = 1,
    equipeNormalizeY = 1
  }
end

function this.methods()
  return {
    onClick_switch = function(self)
      if self.data.showStaus == showType.detail then
        self.data.showStaus = showType.queue
      else
        self.data.showStaus = showType.detail
      end
      self:refreshRightContent(false, true)
    end,
    onClick_start = function(self)
      self:onClickStart()
    end,
    onClick_upgrade = function(self)
      if self.data.isBuildingMax then
        L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_home_manage_13"))
        return
      end
      L_UI:open("pageBuildingUpgrade", {
        guid = self.data.buildingGuid
      })
    end,
    produceTargetList = {
      onClick_select = function(self, bind)
        self:dealTargetClick(bind, true)
      end
    },
    decorationList = {
      onClick_select = function(self, bindItem)
        self:setProduceTargetListActive(bindItem.seriesId)
      end,
      onClick_selectTarget = function(self, bind)
        self:dealTargetClick(bind)
      end
    },
    onClick_foodAutoSelect = function(self)
      self:onClickFoodAutoSelect()
    end
  }
end

function this:dealTargetClick(bind, refreshTargetList)
  if bind.selectIconActive then
    return
  end
  local isDQSwitch = math.isEmpty(self.data.selectPlanId) or self.data.showStaus == showType.queue
  self.data.showStaus = showType.detail
  local needFreshRight = self.data.selectPlanId ~= bind.id
  self.data.selectPlanId = bind.id
  self:refreshRightContent(needFreshRight, isDQSwitch)
  if refreshTargetList then
    self:setProduceTargetListActive()
  end
end

function this:open()
  this.super.open(self)
  
  function self._initHandler()
    self:initModule()
  end
  
  L_ProductStore:listenCallFunc(L_ProductStore.event.refreshHomeProduct, self._initHandler)
  L_PetStore:listenCallFunc(L_PetStore.event.refreshBuildingPet, self.onEvent_refreshProduct, self)
end

function this:close()
  this.super.close(self)
  L_ProductStore:unListenCallFunc(L_ProductStore.event.refreshHomeProduct, self._initHandler)
  L_PetStore:unListenCallFunc(L_PetStore.event.refreshBuildingPet, self.onEvent_refreshProduct)
end

function this:preOpen(options)
  self.super.preOpen(self, options)
  self.data.showStaus = showType.queue
end

function this:initModule(buildingGuid)
  self.data.buildingGuid = buildingGuid or self.data.buildingGuid
  local serverData = L_HomeStore:getHomeBuildingByGuid(self.data.buildingGuid)
  if not serverData then
    return
  end
  self.data.buildingId = serverData.build_id
  local tpl = _homeBuildingTpl:getTplById(self.data.buildingId)
  local groupTpl = _homeBuildingGroupTpl:getTplById(_homeBuildingTpl:getGroupId(tpl))
  self.data.buildingType = _homeBuildingGroupTpl:getType(groupTpl)
  self.data.isWorking = L_ProductManager:isBuildingOnProducing(self.data.buildingGuid)
  self:refreshBuildingInfo()
  self:initProduceTab()
  self:initProduceTargetList()
  self:initPetWorker()
  self:refreshRightContent(true, false)
end

function this:refreshBuildingInfo()
  if not self.data.buildingGuid or not self.data.buildingId then
    return
  end
  local tpl = _homeBuildingTpl:getTplById(self.data.buildingId)
  local groupId = _homeBuildingTpl:getGroupId(tpl)
  local homeBuildingGroupTpl = L_GameTpl:getHomeBuildingGroupTpl()
  local tpl_buildingGroup = homeBuildingGroupTpl:getTplById(groupId)
  self.bind.buildingNameText = homeBuildingGroupTpl:getName(tpl_buildingGroup)
  local isMax = math.isEmpty(_homeBuildingTpl:getNextLevel(tpl))
  local levelStr = string.concat("Lv.", _homeBuildingTpl:getLevel(tpl))
  self.bind.upgradeBtnActive = not isMax
  self.bind.maxNodeAcitve = isMax
  self.bind.buildingLevelText = levelStr
  self.data.isBuildingMax = isMax
end

function this:refreshRightContent(needRefreshData, isQDSwitch)
  local serverData = L_HomeStore:getHomeBuildingByGuid(self.data.buildingGuid)
  if not serverData then
    return
  end
  self.bind.longDesNoralizeY = 1
  self.bind.equipeNormalizeY = 1
  local isShowDetail = self.data.showStaus == showType.detail
  local isShowQueue = self.data.showStaus == showType.queue
  self.bind.detailActive = isShowDetail
  self.bind.queueActive = isShowQueue
  if needRefreshData then
    if isShowDetail then
      self.bind.active_foodAutoSelect = self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK
      if self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK then
        self:initCookGroup()
      else
        self:initNormalProduce()
      end
    end
    if isShowQueue then
      self:initProduceQueue()
    end
    self.bind.switchBtnActive = not math.isEmpty(self.data.selectPlanId)
  end
end

function this:initCookGroup()
  self._curSelectRars = {
    0,
    0,
    0,
    0
  }
  if not math.isEmpty(self.data.selectPlanId) then
    local foodList = _foodTpl:getTplsByGroup(self.data.selectPlanId)
    local foodTpl = foodList[1]
    local materials = _foodTpl:getNeedMaterial(foodTpl)
    for i = 1, 4 do
      local material = materials[i]
      if material then
        self._curSelectRars[i] = material[3]
      end
    end
  end
  self:initCookProduct()
end

function this:initCookProduct()
  self.bind.txt_foodAutoSelect = self._isFoodAutoReverse and L_WordsTpl:getValue("ui_moduleProduct_01") or L_WordsTpl:getValue("ui_moduleProduct_02")
  self._targetFoodTpl = _foodTpl:getCanDoTpl(self.data.selectPlanId, self._curSelectRars)
  self.data.productId = _foodTpl:getProductId(self._targetFoodTpl)
  self.data.productNum = _foodTpl:getCanDoMaxNum(_foodTpl:getId(self._targetFoodTpl), self._curSelectRars) == 0 and 0 or 1
  self:initModuleNum()
end

function this:initNormalProduce()
  self.data.productId = self.data.selectPlanId
  self.data.productNum = L_ProductManager:getMaxCanProductNum(self.data.productId) == 0 and 0 or 1
  self:initModuleNum()
end

function this:initProduceTargetList()
  local isDeco = self.data.currentTab == tonumber(L_Config:getConfig("game", "HOME_SPECIALTABID_DECORATION"))
  self.bind.produceTargetListActive = not isDeco
  self.bind.decorationListActive = isDeco
  if isDeco then
    self:initBuildingProductTargetList()
  elseif self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK then
    self:initCookProductTargetList()
  else
    self:initNormalProductTargetList()
  end
end

function this:initCookProductTargetList()
  local tmp = L_ProductManager:getTargetFoodForBuilding(self.data.buildingId)
  local lineNum = math.ceil(#tmp / columnNum)
  lineNum = math.clamp(lineNum, minLineNum, lineNum)
  self.bindComponents.verGridView_plan.disableScroll = lineNum <= minLineNum - 1
  local needAddEmptyNum = lineNum * columnNum - #tmp
  for i = 1, needAddEmptyNum do
    table.insert(tmp, {})
  end
  if #tmp ~= #self.bind.produceTargetList then
    self.bind.produceTargetList:clear()
    self.bind.produceTargetList:insert_array(tmp)
  else
    for i = 1, #self.bind.produceTargetList do
      self.bind.produceTargetList:change(i, tmp[i])
    end
  end
  self:setProduceTargetListActive()
end

function this:initBuildingProductTargetList()
  local tmp = {}
  local products = L_ProductManager:getTargetProductForBuilding(self.data.buildingId, self.data.currentTab)
  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.decorationList:clear()
  self.bind.decorationList:insert_array(serialData)
end

function this:initNormalProductTargetList()
  local tmp = L_ProductManager:getTargetProductForBuilding(self.data.buildingId, self.data.currentTab)
  local lineNum = math.ceil(#tmp / columnNum)
  lineNum = math.clamp(lineNum, minLineNum, lineNum)
  self.bindComponents.verGridView_plan.disableScroll = lineNum <= minLineNum
  local needAddEmptyNum = lineNum * columnNum - #tmp
  for i = 1, needAddEmptyNum do
    table.insert(tmp, {})
  end
  if #tmp ~= #self.bind.produceTargetList then
    self.bind.produceTargetList:clear()
    self.bind.produceTargetList:insert_array(tmp)
  else
    for i = 1, #self.bind.produceTargetList do
      self.bind.produceTargetList:change(i, tmp[i])
    end
  end
  self:setProduceTargetListActive()
end

function this:initProduceTab()
  local tpl = _homeBuildingProductionTpl:getTplById(self.data.buildingId)
  local tabs = _homeBuildingProductionTpl:getTab(tpl)
  if 0 < #tabs then
    self.data.currentTab = tabs[1]
  end
  self.modules.moduleCommonTab:setData(tabs, handler(self, self.handleTabClick))
  self.bind.emptyBgActive = #tabs == 0
  self.bind.tabBgActive = 0 < #tabs
end

function this:handleTabClick(id)
  if self.data.currentTab == id then
    return
  end
  self.data.currentTab = id
  self.data.showStaus = showType.queue
  self.data.selectPlanId = nil
  self.data.productId = nil
  self:initProduceTargetList()
  self:refreshRightContent(true, false)
end

function this:initPetWorker()
  self.modules.modulePetInfo:initModule(self.data.buildingGuid)
end

function this:initProduceQueue()
  local queueData = L_ProductManager:getProduceQueueForBuilding(self.data.buildingGuid)
  table.sort(queueData, function(a, b)
    return a.weight < b.weight
  end)
  for k, v in ipairs(queueData) do
    v.index = k
  end
  self.bind.produceList:clear()
  self.bind.produceList:insert_array(queueData)
end

function this:initMasterInfo()
  local func = function(masterId)
    self.data.selectMasterId = masterId
  end
  self.modules.module_master:initModule(func)
end

function this:initModuleNum()
  local max
  if self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK then
    max = _foodTpl:getCanDoMaxNum(_foodTpl:getId(self._targetFoodTpl), self._curSelectRars)
  else
    max = L_ProductManager:getMaxCanProductNum(self.data.productId)
  end
  local func = function(num)
    self.data.productNum = num
    self:initCostInfo()
  end
  local min = 1
  if max < min then
    min = max
  end
  self.modules.module_num:initModule(func, max, min, min)
  func(self.data.productNum)
end

function this:initCostInfo()
  self:initMaterialList()
  local tpl = _productsTpl:getTplById(self.data.productId)
  local onceTime = L_ProductManager:getProduceOnceTime(self.data.buildingGuid, self.data.productId)
  self.bind.txt_time = string.format("%s", L_TimeUtil.secondToLangString(onceTime * self.data.productNum))
  self.reward = L_DataUtil.parseRewardConfigItem(_productsTpl:getRewardId(tpl)[1])
  local item = L_ItemTplManager:getItemConfig(self.reward.itemType, self.reward.itemId)
  self.modules.targetItem:setGeneralContent(self.reward.itemType, self.reward.itemId, {
    itemNumTxt = item.name
  })
  self.bind.longDesScrollActive = false
  self.bind.buildTagActive = false
  self.bind.equipeDesScrollActive = false
  if item.itemType == L_Const.resType.accessory then
    self:initEquipmentDes()
  elseif item.itemType == L_Const.resType.homeBuilding then
    self:setBuildDes(self.reward.itemId)
  else
    self.bind.longDesScrollActive = true
    local itemTpl = L_GameTpl:getCommonItemTpl():getTplById(self.reward.itemId)
    self.bind.tagrgetItemDesc = item.desc
    self.bind.targetItemSpeicalDesc = L_GameTpl:getCommonItemTpl():getSpecialDesc(itemTpl)
  end
  self.bind.petIconActive = _productsTpl:getIsNeedPet(tpl)
end

function this:setBuildDes(buildingId)
  self.bind.buildTagActive = true
  self.bind.longDesScrollActive = true
  local conf = L_ItemTplManager:getBuildingItem(buildingId)
  self.bind.tagrgetItemDesc = ""
  self.bind.targetItemSpeicalDesc = conf.desc
  local buildingTpl = _homeBuildingTpl:getTplById(buildingId)
  local productTpl = _homeBuildingProductionTpl:getTplById(buildingId)
  if productTpl and not math.isEmpty(_homeBuildingProductionTpl:getPetHomeAttribute(productTpl)) then
    local laborId = _homeBuildingProductionTpl:getPetHomeAttribute(productTpl)
    local petSize = _homeBuildingProductionTpl:getPetSize(productTpl)
    self.bind.petTagActive = true
    local txt = ""
    for i, v in ipairs(petSize) do
      local tpl_size = _petHomeSizeTpl:getTplById(v)
      txt = string.concat(txt, _petHomeSizeTpl:getSizeName(tpl_size))
      if i < #petSize then
        txt = string.concat(txt, "/")
      end
    end
    self.bind.petSizeText = txt
    local tpl_capacity = _homeLaborCapacityTpl:getTplById(laborId)
    self.bind.laborTypeIcon = _homeLaborCapacityTpl:getIconLight(tpl_capacity)
  else
    self.bind.petTagActive = false
  end
  local groupTpl = _homeBuildingGroupTpl:getTplById(_homeBuildingTpl:getGroupId(buildingTpl))
  local typeTpl = _buildingTypeTpl:getTplById(_homeBuildingGroupTpl:getType(groupTpl))
  self.bind.buildTypeText = _buildingTypeTpl:getTypeName(typeTpl)
end

function this:initEquipmentDes()
  self.bind.equipeDesScrollActive = true
  local tpl_accessory = _accessoryTpl:getTplById(self.reward.itemId)
  local mainAttr = _accessoryTpl:getMainAttr(tpl_accessory)
  local attrList = {}
  for i, v in ipairs(mainAttr) do
    table.insert(attrList, v[1])
  end
  local accessoryMaintpl = _accessoryMainTpl:getTplByGroupIdAndLevel(attrList[1], 0)
  local attId = _accessoryMainTpl:getBattleInfo(accessoryMaintpl)
  local value = _accessoryMainTpl:getValue(accessoryMaintpl)
  local showName = _accessoryMainTpl:getBattleInfoName(accessoryMaintpl)
  self.bind.tagrgetItemDesc = showName .. _battleInfoTpl:getShowTxt(attId[1], value)
  self.modules.module_suit:setNormalSuitPreview(self.reward.itemId)
end

function this:initMaterialList()
  local num_tmp = self.data.productNum == 0 and 1 or self.data.productNum
  local tpl = _productsTpl:getTplById(self.data.productId)
  local data = _productsTpl:getMaterial(tpl)
  local tmp = {}
  local index = #tmp
  for _, v in pairs(data) do
    local reward = L_DataUtil.parseRewardConfigItem(v)
    local item_tmp = L_ItemTplManager:getItemConfig(reward.itemType, reward.itemId)
    local hadNum = L_BagStore:getItemNum(reward.itemId)
    local needNum = reward.itemNum * num_tmp
    if hadNum < needNum then
      hadNum = L_GameUtil.fillColor(L_GameUtil.itemShowNum(hadNum), L_Const.colorHtml.red005)
    end
    table.insert(tmp, {
      txt_num = string.format("%s/%s", hadNum, needNum),
      img_icon = item_tmp.icon,
      isEmpty = false,
      itemType = reward.itemType,
      itemId = reward.itemId
    })
    index = index + 1
  end
  if self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK then
    local materials = _foodTpl:getNeedMaterial(self._targetFoodTpl)
    for i, material in ipairs(materials) do
      local itemId = _foodMaterialTpl:getItemId(material[1], self._curSelectRars[i])
      local item_tmp = L_ItemTplManager:getCommonItem(itemId)
      local hadNum = L_BagStore:getItemNum(itemId)
      local oneNum = material[2]
      local needNum = oneNum * num_tmp
      if hadNum < needNum then
        hadNum = L_GameUtil.fillColor(L_GameUtil.itemShowNum(hadNum), L_Const.colorHtml.red005)
      end
      local itemIds = _foodMaterialTpl:getGroupItemIds(material[1])
      table.insert(tmp, {
        txt_num = string.format("%s/%s", hadNum, needNum),
        img_icon = item_tmp.icon,
        color = item_tmp.quality,
        isEmpty = false,
        itemType = L_Const.resType.commonItem,
        itemId = itemId,
        changeCallback = 1 < #itemIds and function()
          L_UI:open("pageCookSelectMaterial", {
            groupId = material[1],
            callback = function(selectIndex)
              self._curSelectRars[i] = selectIndex
              self:initCookProduct()
            end,
            select = self._curSelectRars[i]
          })
        end or nil
      })
      index = index + 1
    end
  end
  for _ = index + 1, 4 do
    table.insert(tmp, {isEmpty = true})
  end
  self.bind.materialList:clear()
  self.bind.materialList:insert_array(tmp)
end

function this:setProduceTargetListActive(id)
  if self.data.currentTab == tonumber(L_Config:getConfig("game", "HOME_SPECIALTABID_DECORATION")) then
    self:setBuildingTargetListActive(id)
  else
    self:setNormalTargetListActive()
  end
end

function this:setBuildingTargetListActive(id)
  for i = 1, #self.bind.decorationList do
    if self.bind.produceTargetList:getValue(i, "seriesId") ~= id then
      self.bind.produceTargetList:change(i, {isOpen = false})
    end
  end
end

function this:setNormalTargetListActive()
  for i = 1, #self.bind.produceTargetList do
    self.bind.produceTargetList:change(i, {
      selectIconActive = self.bind.produceTargetList:getValue(i, "id") == self.data.selectPlanId
    })
  end
end

function this:checkProduct()
  if self.data.productNum < 1 then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_product_produce_atleast_one"))
    return false
  end
  local num_tem = self.data.productNum
  local tpl_building = _homeBuildingTpl:getTplById(self.data.buildingId)
  local groupId = _homeBuildingTpl:getGroupId(tpl_building)
  local level = _homeBuildingTpl:getLevel(tpl_building)
  local productTpl = _productsTpl:getTplById(self.data.productId)
  if level < _productsTpl:unlockBuildingLevel(productTpl) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_product_resolution_lock"))
    return false
  end
  if not L_ProductManager:checkProduceQueueAvaliable(self.data.buildingGuid) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_product_lack_produce_queue"))
    return false
  end
  local tpl = _productsTpl:getTplById(self.data.productId)
  local isNeedPet = _productsTpl:getIsNeedPet(tpl)
  if isNeedPet and not L_ProductManager:isBuildingHasPet(self.data.buildingGuid) then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_product_need_pet"))
    return
  end
  local material = _productsTpl:getMaterial(tpl)
  for _, v in pairs(material) do
    local hasNum = L_BagStore:getItemNum(v[2])
    local needNum = num_tem * v[3]
    if hasNum < needNum then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_product_lack_material"))
      return false
    end
  end
  local count, limitCnt = L_ProductManager:getLimitForBuildingItem(self.data.productId)
  if limitCnt ~= nil and limitCnt <= count then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_home_building_reach_limit"))
    return false
  end
  return true
end

function this:onClickStart()
  if self:checkProduct() then
    if self.data.buildingType == L_Const.WorldMapBuildType.WMBT_COOK then
      self:checkDoCook()
    else
      local data = {
        guid = self.data.buildingGuid,
        productId = self.data.productId,
        count = self.data.productNum
      }
      self.data.showStaus = showType.queue
      L_ProductManager:reqStartProduct(data, function()
        self.data.selectPlanId = nil
        self.data.productId = nil
        self:refreshRightContent(true, true)
        self:setProduceTargetListActive()
      end)
    end
  end
end

function this:checkDoCook()
  local groupTpl = _foodGroupTpl:getTplById(self.data.selectPlanId)
  local serverData = L_HomeStore:getHomeBuildingByGuid(self.data.buildingGuid)
  if _foodGroupTpl:getIsNeedPet(groupTpl) and math.isEmpty(serverData.station_pet_guid) then
    L_FlyMsgManager:showNormalMsgByKey("notice_pageHomeCook_01")
    return
  end
  local targetTpl = self._targetFoodTpl
  local guid = self.data.buildingGuid
  local cookId = _foodTpl:getId(targetTpl)
  local count = self.data.productNum
  local materials = _foodTpl:getNeedMaterial(targetTpl)
  local items = {}
  for i = 1, 4 do
    local material = materials[i]
    if material then
      local itemId = _foodMaterialTpl:getItemId(material[1], self._curSelectRars[i])
      local oneNum = material[2]
      local needNum = oneNum * count
      if needNum > L_BagStore:getItemNum(itemId) then
        L_FlyMsgManager:showNormalMsgByKey("notice_pageHomeCook_02", {
          [0] = L_ItemTplManager:getCommonItem(itemId).name
        })
        return
      end
      table.insert(items, {item_id = itemId, item_num = oneNum})
    end
  end
  L_CookStore:req_cook(guid, cookId, count, items, function(rspData, errorcode)
    if errorcode == L_Const.errorCode.ErrCodeSucc then
      self.data.showStaus = showType.queue
      self.data.selectPlanId = nil
      self.data.productId = nil
      self:refreshRightContent(true, true)
      self:setProduceTargetListActive()
      if not table.isEmpty(rspData) then
        local itemList = rspData.rewards
        if not table.isEmpty(itemList) then
          L_UI:open("pageCookAnim")
          Timer.once(3.5, function()
            L_RewardManager:showPage(itemList, rspData.src)
          end)
        end
      end
    end
  end)
end

function this:onEvent_refreshProduct()
  self:refreshRightContent(true, false)
end

function this:onClickFoodAutoSelect()
  self._curSelectRars = {
    0,
    0,
    0,
    0
  }
  if not math.isEmpty(self.data.selectPlanId) then
    local foodList = _foodTpl:getTplsByGroup(self.data.selectPlanId)
    local foodTpl = foodList[1]
    local materials = _foodTpl:getNeedMaterial(foodTpl)
    for x = 1, 4 do
      local material = materials[x]
      if material then
        local itemIds = _foodMaterialTpl:getGroupItemIds(material[1])
        local needNum = material[2]
        self._curSelectRars[x] = material[3]
        if self._isFoodAutoReverse then
          for i = 5, 1, -1 do
            if i >= material[3] and itemIds[i] and needNum < L_BagStore:getItemNum(itemIds[i]) then
              self._curSelectRars[x] = i
              break
            end
          end
        else
          for i = 1, 5 do
            if i >= material[3] and itemIds[i] and needNum < L_BagStore:getItemNum(itemIds[i]) then
              self._curSelectRars[x] = i
              break
            end
          end
        end
      end
    end
  end
  printf("\233\128\137\230\139\169\231\187\147\230\158\156", self._curSelectRars)
  self._isFoodAutoReverse = not self._isFoodAutoReverse
  self:initCookProduct()
end

return this
