<template>
  <a-tabs
    type="editable-card"
    v-model:activeKey="activeKey"
    @edit="handleTabEdit"
    @tabClick="handleTabClick"
    hide-add
  >
    <a-tab-pane
      v-for="tab in tabsList"
      :key="tab.key"
      :tab="tab.title"
      :closable="tab.closable"
    >
    </a-tab-pane>
  </a-tabs>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();

// 标签页列表
const tabsList = ref([
  {
    key: "/home",
    title: "首页",
    closable: false,
  },
]);

// 当前激活的标签页
const activeKey = ref(route.path);

// 初始化处理
onMounted(() => {
  addTab(route);
});

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    activeKey.value = newPath;
    addTab(route);
  }
);

// 添加标签页
const addTab = (route) => {
  const exists = tabsList.value.some((tab) => tab.key === route.path);
  if (!exists) {
    tabsList.value.push({
      key: route.path,
      title: route.name || "",
      closable: route.path !== "/home", //首页不能关闭
    });
  }
};

// 处理标签页点击
const handleTabClick = (key) => {
  router.push(key);
};

// 处理标签页编辑（关闭）
const handleTabEdit = (targetKey, action) => {
  if (action === "remove") {
    removeTab(targetKey);
  }
};

// 移除标签页
const removeTab = (targetKey) => {
  if (targetKey === "/home") return; // 阻止关闭首页

  const tabs = tabsList.value;
  let newActiveKey = activeKey.value;

  if (targetKey === activeKey.value) {
    tabs.forEach((tab, index) => {
      if (tab.key === targetKey) {
        const nextTab = tabs[index + 1] || tabs[index - 1];
        newActiveKey = nextTab?.key || "/home";
      }
    });
  }

  tabsList.value = tabs.filter((tab) => tab.key !== targetKey);
  activeKey.value = newActiveKey;
  router.push(newActiveKey);
};
</script>
