<template>
  <div class="global-breadcrumb">
    <a-breadcrumb>
      <a-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
        <span
          v-if="index === breadcrumbItems.length - 1"
          class="breadcrumb-text"
        >
          {{ item.title }}
        </span>
        <a-link
          v-else
          @click="goToRoute(item.defRouter)"
          :hoverable="false"
          class="breadcrumb-link"
        >
          {{ item.title }}
        </a-link>
      </a-breadcrumb-item>
    </a-breadcrumb>
  </div>
</template>

<script name="GlobalBreadcrumb" lang="ts" setup>
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

const route = useRoute();
const router = useRouter();
const { t } = useI18n();

const breadcrumbItems = ref<
  { title: string; path: string; defRouter: string }[]
>([]);

// 获取面包屑项
const getBreadcrumbItems = () => {
  const matched = route.matched.filter(item => {
    return item.meta && item.meta.locale;
  });
  const items = matched.map(item => {
    return {
      title: t(item.meta.locale as string),
      path: item.path,
      defRouter: item.children[0]?.path || item?.path,
    };
  });
  return items;
};

// 监听路由变化更新面包屑
watch(
  () => route.matched,
  () => {
    breadcrumbItems.value = getBreadcrumbItems();
  },
  { immediate: true }
);

// 跳转到指定路由
const goToRoute = (path: string) => {
  console.log('path', path);
  if (path) {
    router.push(path);
  }
};
</script>

<style scoped lang="less">
.global-breadcrumb {
  margin-left: 16px;

  :deep(.arco-breadcrumb) {
    display: flex;
    align-items: center;
    height: 50px;
  }

  :deep(.arco-breadcrumb-item) {
    display: flex;
    align-items: center;

    &:last-child .arco-breadcrumb-item-inner {
      color: var(--color-text-1);
      font-weight: 500;
    }
  }
}

.breadcrumb-link {
  color: rgb(var(--color-text-1));
  text-decoration: none;
  cursor: pointer;

  &:hover {
    color: rgb(var(--color-text-4));
    // text-decoration: underline;
  }
}

.breadcrumb-text {
  color: var(--color-text-1);
}
</style>
