local this = class("collectionToolStore", G_BaseStore)
this.event = {
  dataUpdate = "dataUpdate",
  triggerCollect = "triggerCollect",
  collectStatusChange = "collectStatusChange",
  collectTriggerBtnChange = "collectTriggerBtnChange"
}
local toolItem = class("toolItem")

function toolItem:ctor(guid)
  self.guid = guid
  self.endurance = 0
  self.id = 0
  self.select = false
  self.type = 0
end

function toolItem:populate(data)
  self.endurance = data.endurance
  self.id = data.id
  self.select = data.select
end

function this:init()
  this.super.init(self)
  self.data = {
    toolMap = {},
    toolTypeMap = {},
    type2selectedGuid = {}
  }
end

function this:syncData(data)
  for _, dataItem in ipairs(data.bags or {}) do
    local guid = dataItem.guid
    self.data.toolMap[guid] = self.data.toolMap[guid] or toolItem.new(guid)
    self.data.toolMap[guid]:populate(dataItem)
  end
  for _, delId in ipairs(data.dels or {}) do
    self.data.toolMap[delId] = nil
  end
  self.data.type2selectedGuid = {}
  self.data.toolTypeMap = {}
  for guid, tool in pairs(self.data.toolMap) do
    local configTable = CS.Azur.Gameplay.Table.TDCollectionToolTable.GetData(tool.id)
    local type = configTable.type
    tool.type = type
    if self.data.toolTypeMap[type] == nil then
      self.data.toolTypeMap[type] = {}
    end
    local conf = L_ItemTplManager:getItemConfig(L_Const.resType.collectionTool, tool.id)
    table.insert(self.data.toolTypeMap[type], {
      endurance = tool.endurance,
      quality = conf.quality,
      guid = guid,
      tool = tool,
      select = tool.select and true or false
    })
    if tool.select then
      self.data.type2selectedGuid[type] = guid
    end
  end
  self:call(self.event.dataUpdate)
end

function this:getSelectTool(type)
  return self.data.type2selectedGuid[type]
end

function this:getToolsMap()
  return self.data.toolMap
end

function this:getToolsMapByType(type)
  local data = self.data.toolTypeMap[type]
  if table.isEmpty(data) then
    return {}
  end
  if 1 < #data then
    table.sort(data, function(a, b)
      if a.quality ~= b.quality then
        return a.quality > b.quality
      elseif a.endurance ~= b.endurance then
        return a.endurance > b.endurance
      else
        return a.guid < b.guid
      end
    end)
  end
  return data
end

function this:getTool(guid)
  return self.data.toolMap[guid]
end

function this:req_CSProtoSelectTool(guid, callback)
  L_Net:sendMessage(MsgGenCode.CSProtoSelectCollectTool, {u32 = guid}, function(rspData, errorCode)
    if errorCode == L_Const.errorCode.ErrCodeSucc and callback then
      callback()
    end
  end)
end

function this:getNumById(id)
  local num = 0
  for _, value in ipairs(self.data.toolMap) do
    if value.id == id then
      num = num + 1
    end
  end
  return num
end

return this
