const HOME_TAG = { name: 'home', path: '/saas/home', title: '首页', id: 0 }
const lastSavedTags = localStorage.getItem('tags')
  ? JSON.parse(localStorage.getItem('tags')) || []
  : []
let tagId = lastSavedTags.reduce((a, c) => Math.max(a, c.id), 0)
// 确保首页始终在第一位
function ensureHomeFirst(tags) {
  const filtered = tags.filter((t) => t.name !== 'home')
  return [HOME_TAG, ...filtered]
}
console.log(lastSavedTags)
/**
 * @type {import('vuex').StoreOptions}
 */
const tags = {
  namespaced: true,
  state: {
    tags: ensureHomeFirst(lastSavedTags),
    activeTag: undefined
  },
  getters: {
    currentTag(state) {
      return state.tags.find((e) => e.name === state.activeTag)
    }
  },
  mutations: {
    add(state, tag) {
      // 禁止添加重复首页tag
      if (tag.name === 'home') return HOME_TAG.id
      const item = {
        ...tag,
        id: ++tagId
      }
      const index = state.tags.findIndex((t) => t.name === tag.name)
      if (index === -1) {
        state.tags.push(item)
      }
      // 始终保证首页在第一位
      state.tags = ensureHomeFirst(state.tags)
      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) {
      // 禁止移除首页tag
      if (name === 'home') return
      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
