<template>
  <div class="tab-menu">
    <el-tabs
      v-model="activeTab"
      type="card"
      closable
      class="dynamic-tabs"
      @tab-remove="removeTab"
      @tab-click="handleTabClick"
    >
      <el-tab-pane
        v-for="tab in tabs"
        :key="tab.path"
        :label="tab.title"
        :name="tab.path"
        :closable="tab.path !== '/enter/dashboard'"
      >
        <template #label>
          <span>
            <i v-if="tab.icon" :class="tab.icon"></i>
            {{ tab.title }}
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from 'vuex'
  import { useI18n } from 'vue-i18n'

  // 组合式 API
  const route = useRoute()
  const router = useRouter()
  const store = useStore()
  const { t, locale } = useI18n()

  // 响应式数据
  const tabs = ref([
    {
      title: t('Home'),
      path: '/enter/dashboard',
      icon: 'el-icon-house',
      closable: false,
    },
  ])
  const activeTab = ref()

  // 计算属性
  const menus = computed(() => store.state.navMenu.menus)

  // 方法
  const extractNumberFromLink = (link) => {
    if (!link) return null
    const match = link.match(/(\d+)$/)
    return match ? parseInt(match[1], 10) : null
  }

  const addTab = (route) => {
    let routeName = route.name
    if (route.name === 'R-CustomerDetail') {
      const linkNumber = extractNumberFromLink(route.path)
      routeName = `${t('CustomerDetail')}(${linkNumber})`
    }

    const path = route.path
    const name = routeName || route.name
    const icon = route.icon

    // 检查tab是否已存在
    const existingTab = tabs.value.find((tab) => tab.path === path)
    if (existingTab) {
      activeTab.value = path
      return
    }

    // 从菜单中查找对应的菜单项
    let menuItem = findMenuItemByPath(path)

    if (!menuItem) {
      // 如果没有找到对应的菜单项，使用路由信息
      menuItem = {
        name: name || path,
        icon: icon || 'el-icon-document',
      }
    }

    const newTab = {
      title: t(menuItem.name) || menuItem.name || name || path,
      path: path,
      icon: menuItem.icon || 'el-icon-document',
      closable: path !== '/enter/dashboard',
    }

    tabs.value.push(newTab)
    activeTab.value = path
  }

  const updateTabTitles = () => {
    tabs.value.forEach((tab) => {
      // 特殊处理CID详情的情况
      if (tab.path.includes('/customer/detail/')) {
        const linkNumber = extractNumberFromLink(tab.path)
        tab.title = `${t('CustomerDetail')}(${linkNumber})`
        return
      }

      // 重新获取菜单项信息
      const menuItem = findMenuItemByPath(tab.path)
      if (menuItem) {
        const newTitle = t(menuItem.name) || menuItem.name
        tab.title = newTitle
      }
    })
  }

  const findMenuItemByPath = (path) => {
    for (const menu of menus.value) {
      if (menu.children) {
        for (const subMenu of menu.children) {
          if (subMenu.link === path) {
            return {
              name: subMenu.name,
              icon: menu.icon || 'el-icon-document',
            }
          }
        }
      }
    }
    return null
  }

  const removeTab = (targetPath) => {
    // 不允许关闭首页tab
    if (targetPath === '/enter/dashboard') {
      return
    }

    const currentTabs = tabs.value
    let activePath = activeTab.value

    if (activePath === targetPath) {
      currentTabs.forEach((tab, index) => {
        if (tab.path === targetPath) {
          const nextTab = currentTabs[index + 1] || currentTabs[index - 1]
          if (nextTab) {
            activePath = nextTab.path
          }
        }
      })
    }

    tabs.value = currentTabs.filter((tab) => tab.path !== targetPath)
    activeTab.value = activePath

    // 跳转到激活的tab
    if (route.path !== activePath) {
      router.push(activePath)
    }
  }

  const handleTabClick = (tab) => {
    const path = tab.props.name
    if (route.path !== path) {
      router.push(path)
    }
  }

  const handleMenuClick = (menuItem) => {
    addTab({
      path: menuItem.link,
      name: menuItem.name,
      icon: menuItem.icon,
    })
  }

  // 事件监听
  const setupEventListeners = () => {
    // 使用事件总线或自定义事件
    window.addEventListener('menu-click', (event) => {
      handleMenuClick(event.detail)
    })
  }

  const removeEventListeners = () => {
    window.removeEventListener('menu-click', handleMenuClick)
  }

  // 监听器
  watch(
    route,
    (newRoute) => {
      addTab(newRoute)
    },
    { immediate: true }
  )

  watch(
    locale,
    () => {
      updateTabTitles()
    },
    { immediate: true }
  )

  // 生命周期
  onMounted(() => {
    setupEventListeners()
  })

  onUnmounted(() => {
    removeEventListeners()
  })
</script>

<style scoped lang="scss">
  .tab-menu {
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
    padding: 0;
    margin-bottom: 15px;

    .dynamic-tabs {
      .el-tabs__header {
        margin: 0;

        .el-tabs__nav-wrap {
          .el-tabs__nav-scroll {
            .el-tabs__nav {
              .el-tabs__item {
                height: 40px;
                line-height: 40px;
                padding: 0 20px;
                font-size: 14px;
                color: #606266;
                border: 1px solid #e4e7ed;
                border-bottom: none;
                background: #fafafa;
                margin-right: 2px;
                border-radius: 4px 4px 0 0;

                &:hover {
                  color: #409eff;
                  background: #fff;
                }

                &.is-active {
                  color: #409eff;
                  background: #fff;
                  border-color: #409eff;
                }

                .el-icon-close {
                  margin-left: 5px;
                  font-size: 12px;

                  &:hover {
                    background-color: #c0c4cc;
                    color: #fff;
                    border-radius: 50%;
                  }
                }
              }
            }
          }
        }
      }

      .el-tabs__content {
        display: none; // 隐藏内容区域，因为我们使用router-view来显示内容
      }
    }
  }

  // 图标样式
  .el-tabs__item i {
    margin-right: 5px;
    font-size: 14px;
  }
</style>
