<template>
  <div class="relative whitespace-nowrap">
    <div class="flex items-center">
      <n-scrollbar>
        <n-tabs
        type="card"
        size="small"
        pane-style="padding: 0px"
        closable
        animated
        :value="currentTab"
        @update:value="goRouter"
        @close="handleClose"
      >
        <n-tab-pane
          v-for="item in tabs"
          :key="item.Url"
          closable
          :name="item.Url" :tab="item.Title"
        >
        </n-tab-pane>
        <template #suffix>
        <div class="pr-[15px] cursor">
          <n-dropdown :options="options"  @select="onDropDownSelect">
            <n-icon :size="20" >
              <Menu />
            </n-icon>
          </n-dropdown>
        </div>
        </template>
      </n-tabs>
      </n-scrollbar>
    </div>
  </div>
</template>

<script setup>
import {ref, watch, onMounted,h} from 'vue'
import { useRouter, useRoute } from 'vue-router';
import {storeToRefs} from 'pinia'
import { tabRouter } from "@/store/modules/tab-router.js";
import { NIcon } from 'naive-ui';
import { Close, ChevronBack, Refresh, ArrowBack, ArrowForward, Menu } from '@vicons/ionicons5';
const router = useRouter();
const route = useRoute();
const tabState = tabRouter()
const {tabs, currentTab} = storeToRefs(tabState)

// 监听路由变化，更新当前标签
watch(() => route.path, (newPath) => {
  if (newPath) {
    currentTab.value = newPath;
  }
}, { immediate: true });

const options=ref([
  {
    label: '刷新页面',
    key: 'refresh',
    icon() {
      return h(NIcon, null, {
        default: () => h(Refresh),
      });
    },
  },
  {
    label: '关闭所有',
    key: 'close',
    icon() {
      return h(NIcon, null, {
        default: () => h(Close),
      })
    },
  },
])
const refreshRoute=()=> {
  location.reload();
}
const closeAll=()=>{
  tabs.value=[]
  // 关闭所有后跳转到首页或者默认页面
  router.push('/');
}
const onDropDownSelect=(key)=> {
  switch (key) {
    case 'refresh':
      refreshRoute();
      break;
    case 'close':
      closeAll();
      break;
  }
}

const goRouter = (item) => {
  // 只需要路由跳转，不需要手动设置currentTab
  if (item !== route.path) {
    router.push(item);
  }
};

const handleClose = (url) => {
  const tabIndex = tabs.value.findIndex((tab) => tab.Url === url);
  if (tabIndex === -1) return;
  tabs.value.splice(tabIndex, 1);
  
  // 如果关闭的是当前活动的标签，则需要跳转到其他标签
  if (url === route.path) {
    const previousTab = tabs.value[tabIndex - 1] || tabs.value[0];
    if (previousTab) {
      router.push(previousTab.Url);
    } else {
      // 如果没有标签了，跳转到首页或者默认页面
      router.push('/');
    }
  }
};

// 初始化时确保currentTab与当前路由同步
onMounted(() => {
  if (route.path) {
    currentTab.value = route.path;
  }
});
</script>

<style lang="scss" scoped>
:deep(.flex.items-center) {
  flex-wrap: nowrap;
}
</style>