local this = class("canteenManager")
local _productsTpl = L_GameTpl:getProductsCanteenTpl()
local _homeBuildingProductionTpl = L_GameTpl:getHomeBuildingCanteenTpl()
local _homeBuildingTpl = L_GameTpl:getHomeBuildingTpl()

function this:getMaxCanProductNum(productId)
  local tpl = _productsTpl:getTplById(productId)
  local material = _productsTpl:getMaterial(tpl)
  local minCanNum = math.maxinteger
  for i, v in pairs(material) do
    local hasNum = L_BagStore:getItemNum(v[2])
    minCanNum = math.min(minCanNum, math.floor(hasNum / v[3]))
  end
  return math.min(minCanNum, math.maxinteger)
end

function this:reqStartCanteen(param, callback)
  L_CanteenStore:req_CSProtoStartCanteen(param, function(errCode)
    if errCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:reqStopCanteen(buildingGuid, callback)
  L_CanteenStore:req_CSProtoStopCanteen(buildingGuid, function(errCode)
    if errCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:reqAddCanteen(param, callback)
  L_CanteenStore:req_CSProtoOperateCanteenItem(param, function(errCode)
    if errCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:checkProduct(planId, num, buildingGuid, isAdd)
  local num_tem = num == 0 and 1 or num
  local building = L_HomeStore:getHomeBuildingByGuid(buildingGuid)
  local buildingId = building.build_id
  local tpl_building = _homeBuildingTpl:getTplById(buildingId)
  local groupId = _homeBuildingTpl:getGroupId(tpl_building)
  local level = _homeBuildingTpl:getLevel(tpl_building)
  local data = _homeBuildingProductionTpl:getUnlockMap(groupId)
  if level < data[planId] then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("ui_moduleCanteenFree_02"))
    return false
  end
  local tpl = _productsTpl:getTplById(planId)
  local material = _productsTpl:getMaterial(tpl)
  for i, v in pairs(material) do
    local reward = L_DataUtil.parseRewardConfigItem(v)
    local hasNum = L_BagStore:getItemNum(reward.itemId)
    local needNum = num_tem * reward.itemNum
    if hasNum < needNum then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_shortageMaterial"))
      return false
    end
  end
  if not isAdd then
    local resident_need = _productsTpl:getNeedLabor(tpl)
    local resident_have = L_HomeResidentStore:getRestResidentNum()
    if resident_need > resident_have then
      L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_homeProduction_01"))
      return false
    end
  end
  if num < 1 then
    L_FlyMsgManager:showNormalMsg(L_WordsTpl:getValue("notice_homeProduction_02"))
    return false
  end
  return true
end

return this
