const lastSavedTags = localStorage.getItem('tags') ? JSON.parse(localStorage.getItem('tags')) || [] : []
let tagId = lastSavedTags.reduce(
  (a, c) => Math.max(a, c.id),
  0,
)
console.log(lastSavedTags)
/**
 * @type {import('vuex').StoreOptions}
 */
const tags = {
  namespaced: true,
  state: {
    tags: lastSavedTags || [],
    activeTag: undefined,
  },
  getters: {
    currentTag(state) {
      return state.tags.find(
        (e) => e.name === state.activeTag,
      )
    },
  },
  mutations: {
    add(state, tag) {
      const item = {
        ...tag,
        id: ++tagId,
      }
      const index = state.tags.findIndex(
        (t) => t.name === tag.name,
      )
      if (index === -1) {
        state.tags.push(item)
      }
      localStorage.setItem(
        'tags',
        JSON.stringify(state.tags),
      )
      return item.id
    },
    setActive(state, name) {
      if (!state.tags.some((e) => e.name === name)) return
      state.activeTag = name
    },
    remove(state, name) {
      const index = state.tags.findIndex(
        (e) => e.name === name,
      )
      if (index === -1) return
      state.tags.splice(index, 1)

      // 如果关闭的是当前的 tag，就转到前一个标签
      if (state.activeTag === name) {
        let prevIndex = index - 1
        if (prevIndex < 0) prevIndex = 0
        if (state.tags.length === 0) {
          state.activeTag = undefined
        } else {
          state.activeTag = state.tags[prevIndex].name
        }
      }

      localStorage.setItem(
        'tags',
        JSON.stringify(state.tags),
      )
    },
    removeAllTags(state) {
      state.tags = []
    },
  },
}

export default tags
