import type { RouteLocationNormalized } from 'vue-router';
import { defineStore } from 'pinia';
import router from '@/routers';

export interface TabItem {
  path: string;
  name: string;
  title: string;
  icon?: string;
  affix?: boolean; // 是否固定
  query?: any;
}

interface TabbarState {
  tabs: TabItem[];
  activeTab: string;
  cachedTabs: string[]; // 改用数组以支持持久化
}

const HOME_PATH = '/dashboard';

export const useTabbarStore = defineStore('tabbar', {
  state: (): TabbarState => ({
    tabs: [],
    activeTab: HOME_PATH,
    cachedTabs: [],
  }),

  hydrate(state, localState) {
    // 从持久化存储恢复数据时做校验
    if (localState) {
      state.tabs = Array.isArray(localState.tabs) ? localState.tabs : [];
      state.activeTab = typeof localState.activeTab === 'string' ? localState.activeTab : HOME_PATH;
      // cachedTabs 之前是 Set<string>，恢复时可能不是数组
      state.cachedTabs = Array.isArray(localState.cachedTabs) ? localState.cachedTabs : [];
    }
  },

  getters: {
    getTabs: (state) => state.tabs,
    getActiveTab: (state) => state.activeTab,
    getCachedTabs: (state) => state.cachedTabs,
  },

  actions: {
    /**
     * 添加标签页
     */
    addTab(route: RouteLocationNormalized) {
      const { path, name, meta, query } = route;

      // 不需要标签页的路由
      if (meta.isHide === '1' || !name) {
        return;
      }

      const title = (meta.title as string) || (name as string);
      const icon = meta.icon as string;
      const affix = meta.affix === true;

      // 检查是否已存在
      const isExist = this.tabs.some((tab) => tab.path === path);
      if (!isExist) {
        this.tabs.push({
          path,
          name: name as string,
          title,
          icon,
          affix,
          query,
        });
      }

      // 设置为活动标签
      this.activeTab = path;

      // 添加到缓存
      if (name && meta.isKeepAlive !== '0') {
        const tabName = name as string;
        if (!this.cachedTabs.includes(tabName)) {
          this.cachedTabs.push(tabName);
        }
      }
    },

    /**
     * 关闭标签页
     */
    closeTab(path: string) {
      const index = this.tabs.findIndex((tab) => tab.path === path);
      if (index === -1) return;

      const tab = this.tabs[index];

      // 固定的标签页不能关闭
      if (tab.affix) {
        ElMessage.warning('固定标签页不能关闭');
        return;
      }

      // 移除标签
      this.tabs.splice(index, 1);

      // 移除缓存
      if (tab.name) {
        this.cachedTabs = this.cachedTabs.filter(name => name !== tab.name);
      }

      // 如果关闭的是当前活动标签，切换到其他标签
      if (this.activeTab === path) {
        const nextTab = this.tabs[index] || this.tabs[index - 1];
        if (nextTab) {
          this.activeTab = nextTab.path;
          router.push(nextTab.path);
        } else {
          // 没有其他标签，跳转到首页
          this.activeTab = HOME_PATH;
          router.push(HOME_PATH);
        }
      }
    },

    /**
     * 关闭其他标签页
     */
    closeOtherTabs(path?: string) {
      const currentPath = path || this.activeTab;
      this.tabs = this.tabs.filter((tab) => tab.path === currentPath || tab.affix);

      // 更新缓存
      this.cachedTabs = [];
      this.tabs.forEach((tab) => {
        if (tab.name && !this.cachedTabs.includes(tab.name)) {
          this.cachedTabs.push(tab.name);
        }
      });

      // 如果当前活动标签被关闭，切换到第一个标签
      if (!this.tabs.find((tab) => tab.path === this.activeTab)) {
        const firstTab = this.tabs[0];
        if (firstTab) {
          this.activeTab = firstTab.path;
          router.push(firstTab.path);
        }
      }
    },

    /**
     * 关闭所有标签页（除了固定的）
     */
    closeAllTabs() {
      this.tabs = this.tabs.filter((tab) => tab.affix);
      this.cachedTabs = [];
      this.tabs.forEach((tab) => {
        if (tab.name) {
          this.cachedTabs.push(tab.name);
        }
      });

      // 跳转到第一个标签或首页
      const firstTab = this.tabs[0];
      if (firstTab) {
        this.activeTab = firstTab.path;
        router.push(firstTab.path);
      } else {
        this.activeTab = HOME_PATH;
        router.push(HOME_PATH);
      }
    },

    /**
     * 关闭右侧标签页
     */
    closeRightTabs(path?: string) {
      const currentPath = path || this.activeTab;
      const index = this.tabs.findIndex((tab) => tab.path === currentPath);
      if (index === -1) return;

      this.tabs = this.tabs.filter((tab, i) => i <= index || tab.affix);

      // 更新缓存
      this.cachedTabs = [];
      this.tabs.forEach((tab) => {
        if (tab.name && !this.cachedTabs.includes(tab.name)) {
          this.cachedTabs.push(tab.name);
        }
      });

      // 如果当前活动标签被关闭，切换到指定标签
      if (!this.tabs.find((tab) => tab.path === this.activeTab)) {
        this.activeTab = currentPath;
        router.push(currentPath);
      }
    },

    /**
     * 关闭左侧标签页
     */
    closeLeftTabs(path?: string) {
      const currentPath = path || this.activeTab;
      const index = this.tabs.findIndex((tab) => tab.path === currentPath);
      if (index === -1) return;

      this.tabs = this.tabs.filter((tab, i) => i >= index || tab.affix);

      // 更新缓存
      this.cachedTabs = [];
      this.tabs.forEach((tab) => {
        if (tab.name && !this.cachedTabs.includes(tab.name)) {
          this.cachedTabs.push(tab.name);
        }
      });

      // 如果当前活动标签被关闭，切换到指定标签
      if (!this.tabs.find((tab) => tab.path === this.activeTab)) {
        this.activeTab = currentPath;
        router.push(currentPath);
      }
    },

    /**
     * 固定/取消固定标签页
     */
    toggleAffixTab(path: string) {
      const tab = this.tabs.find((t) => t.path === path);
      if (tab) {
        tab.affix = !tab.affix;
      }
    },

    /**
     * 设置活动标签
     */
    setActiveTab(path: string) {
      this.activeTab = path;
    },

    /**
     * 重置标签页（退出登录时调用）
     */
    resetTabs() {
      this.tabs = [];
      this.activeTab = HOME_PATH;
      this.cachedTabs = [];
    },

    /**
     * 初始化固定标签页
     */
    initAffixTabs(routes: any[]) {
      const affixTabs: TabItem[] = [];

      const findAffixTabs = (routeList: any[]) => {
        routeList.forEach((route) => {
          if (route.meta?.affix) {
            affixTabs.push({
              path: route.path,
              name: route.name,
              title: route.meta?.title || route.name,
              icon: route.meta?.icon,
              affix: true,
            });
          }
          if (route.children) {
            findAffixTabs(route.children);
          }
        });
      };

      findAffixTabs(routes);

      // 添加固定标签页
      affixTabs.forEach((tab) => {
        if (!this.tabs.find((t) => t.path === tab.path)) {
          this.tabs.push(tab);
          if (tab.name && !this.cachedTabs.includes(tab.name)) {
            this.cachedTabs.push(tab.name);
          }
        }
      });
    },
  },

  persist: {
    key: 'hzhub-employee-tabs',
    storage: sessionStorage, // 使用 sessionStorage，浏览器关闭后自动清除
    paths: ['tabs', 'activeTab', 'cachedTabs'],
  },
});