<template>
  <v-sheet class="px-1">
    <v-expand-transition>
      <v-tabs v-show="tabsActive && tabList.length" color="blue">
        <v-tab
          v-for="(item, i) in tabList"
          :key="item.name"
          :to="item.path"
          @contextmenu="showMenu($event, i)">
          {{ item.title }}
          <v-icon v-if="item.title != '工作台'" size="14" @click.stop.prevent="closeTab(i)" @contextmenu.stop.prevent>
            mdi-close
          </v-icon>
        </v-tab>
      </v-tabs>
    </v-expand-transition>
    <v-menu v-model="tabMenu" absolute :position-x="x" :position-y="y" min-width="100">
      <v-list density="compact">
        <v-list-item @click="closeTab(index)">
          <v-list-item-title>关闭当前</v-list-item-title>
        </v-list-item>
        <v-list-item @click="closeOther(index)">
          <v-list-item-title>关闭其他</v-list-item-title>
        </v-list-item>
        <v-list-item @click="closeAll">
          <v-list-item-title>关闭所有</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </v-sheet>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSettingsStore } from '@/stores/settings'

const route = useRoute()
const router = useRouter()
const store = useSettingsStore()

const tabList = ref([])
const tabMenu = ref(false)
const x = ref(0)
const y = ref(0)
const index = ref(0)

const tabsActive = computed(() => store.getTabsActive)

onMounted(() => {
  tabList.value.push({
    name: route.name,
    path: route.path,
    title: route.meta,
  })
})

const showMenu = (e, i) => {
  e.preventDefault()
  index.value = i
  tabMenu.value = false
  x.value = e.clientX
  y.value = e.clientY
  setTimeout(() => {
    tabMenu.value = true
  })
}

const closeTab = (idx) => {
  tabList.value.splice(idx, 1)
  if (tabList.value.length > 0) {
    router.push(tabList.value[tabList.value.length - 1].path)
  }
}

const closeOther = (idx) => {
  const list = tabList.value[idx]
  tabList.value = [list]
  router.push(list.path)
}

const closeAll = () => {
  tabList.value = []
  router.push("/home")
}

watch(route, (to) => {
  const isCover = tabList.value.some((val) => val.name == to.name)
  if (!isCover) {
    tabList.value.push({
      name: to.name,
      path: to.path,
      title: to.meta,
    })
  }
})
</script>
