<template>
  <div class="tab-bar-container">
    <a-affix ref="affixRef" :offset-top="offsetTop">
      <div class="tab-bar-box">
        <div class="tab-bar-scroll">
          <div class="tags-wrap">
            <a-tabs
              :active-key="activeTabKey"
              type="card-gutter"
              :justify="true"
              :auto-switch="true"
              :hide-content="true"
              size="medium"
              :editable="true"
              @tab-click="goto($event as string)"
              @delete="tagClose($event as string)"
            >
              <a-tab-pane
                v-for="(tag, index) in tagList"
                :key="tag.fullPath"
                :closable="
                  tag.fullPath === $route.fullPath &&
                  tag.name !== DEFAULT_ROUTE_NAME
                "
              >
                <template #title>
                  <tab-item
                    :key="tag.fullPath"
                    :index="index"
                    :item-data="tag"
                  />
                </template>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
      </div>
    </a-affix>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'
import { useAppStore, useTabBarStore } from '@/store'
import { DEFAULT_ROUTE_NAME } from '@/router/routes/index'
import { listenerRouteChange } from '@/logics/mitt/routeChange'
import type { TagProps } from '@/store/modules/tab-bar/types'
import { onBeforeRouteUpdate, useRouter, useRoute } from 'vue-router'
import tabItem from './tab-item.vue'

const appStore = useAppStore()
const router = useRouter()
const route = useRoute()
const tabBarStore = useTabBarStore()
const activeTabKey = ref('')

const affixRef = ref()
const tagList = computed(() => {
  return tabBarStore.getTabList
})
const offsetTop = computed(() => {
  return appStore.navbar ? 60 : 0
})

/**
 * 根据tabs点击事件跳转到相对于的路由
 */
const goto = (key: string) => {
  const tag: TagProps = tagList.value.find(item => item.fullPath === key)!
  router.push({ ...tag })
}

/**
 * 点击tabs删除按钮时
 */
const tagClose = (key: string) => {
  const idx: number = tagList.value.findIndex(item => item.fullPath === key)
  const tag: TagProps = tagList.value[idx]
  tabBarStore.deleteTag(idx, tag)
  if (tag.fullPath === route.fullPath) {
    const parent = tagList.value.find(
      item => item.fullPath === tag.parent.fullPath
    )
    if (parent) {
      router.push({
        name: tag.parent!.name,
        params: tag.parent!.params,
        query: tag.parent!.query
      })
    } else {
      const latest = tagList.value[idx - 1] // 获取队列的前一个tab
      router.push({
        name: latest.name,
        params: latest.params,
        query: latest.query
      })
    }
  }
}

watch(
  () => appStore.navbar,
  () => {
    affixRef.value.updatePosition()
  }
)
listenerRouteChange(async (r: RouteLocationNormalized) => {
  if (
    !route.meta.noAffix &&
    !tagList.value.some(tag => tag.fullPath === r.fullPath)
  ) {
    tabBarStore.updateTabList(r)
  }
  setTimeout(() => {
    activeTabKey.value = r.fullPath
  }, 200) // 修复tabs内容宽度超出容器宽度时，未滚至最右或最左的bug
}, true)
onBeforeRouteUpdate((to, from) => {
  if (to.meta.reset && from.fullPath !== '/') {
    const tab = tabBarStore.getTabList.find(item => {
      return item.fullPath === to.fullPath
    })
    if (tab && tab.parent.fullPath === undefined) {
      if (to.name === from.name) {
        tab.parent = from.meta.parent
        return
      }
      tab.parent = from
      to.meta.parent = from
    }
  }
})
</script>

<style scoped lang="less">
.tab-bar-container {
  position: relative;
  background-color: var(--color-bg-2);
  .tab-bar-box {
    display: flex;
    padding: 5px 20px 0 20px;
    color: var(--color-text-1);
    background-color: var(--color-bg-2);
    border-bottom: 1px solid var(--color-border);
    .tab-bar-scroll {
      height: 48px;
      // width: 100%;
      flex: 1;
      overflow: hidden;
      .tags-wrap {
        padding: 4px 0;
        height: 48px;
        white-space: nowrap;
        overflow-x: auto;

        :deep(.arco-tag) {
          display: inline-flex;
          align-items: center;
          padding: 0;
          cursor: pointer;
        }
        :deep(.arco-icon-hover) {
          margin-top: 1px;
          margin-left: 4px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
