import { defineStore } from 'pinia'
import router from '@/router'
export const useAppStore = defineStore('app', {
  state: () => {
    return {
      tagNavList: [],
      fromWhere: ''
    }
  },
  getters: {

  },
  actions: {
    addTag (page) {
      if (!this.tagNavList.some(i => i.path === page.path)) { this.tagNavList.push(page) }
    },
    removeTag (path) {
      const idx = this.tagNavList.findIndex(r => r.path === path)
      const currPath = router.currentRoute.value.path.split('/')[router.currentRoute.value.path.split('/').length - 1]
      if (this.tagNavList.length > 1 && this.tagNavList[idx].path === currPath) {
        router.push({
          name: this.tagNavList[idx + (!idx ? 1 : -1)].path,
          query: this.tagNavList[idx + (!idx ? 1 : -1)].query || {},
          params: this.tagNavList[idx + (!idx ? 1 : -1)].params || {}
        })
      }
      this.tagNavList.splice(idx, 1)
    },
    clearTag () {
      this.tagNavList = []
    },
    writeDownLocation (location) {
      this.fromWhere = location
    }
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'app',
        storage: localStorage,
        paths: ['tagNavList']
      }
    ]
  }
})
