<template>
  <popup
    v-model="visible"
    class="mx-auto my-[50px] px-0 py-6"
    width="520px"
    header-class="hidden"
    :align-center="false"
    :show-footer="false"
    :show-close="false"
  >
    <div class="search-container">
      <div class="search-header">
        <el-input
          class="h-[40px] flex-1"
          v-model="searchText"
          placeholder="输入菜单名称搜索"
          prefix-icon="Search"
          clearable
          size="large"
          ref="searchRef"
        />
      </div>
      <div class="search-body">
        <el-scrollbar view-class="flex flex-col gap-3">
          <template v-if="filteredRoutes.length > 0">
            <div
              class="search-body__item"
              v-for="route in filteredRoutes"
              :key="route.path"
              @click="handleMenuClick(route)"
            >
              <icon :name="route.meta.icon" :size="16" :type="route.meta.iconType" v-if="route.meta?.icon" />
              <span class="flex-1 text-base truncate">{{ route.formattedTitle || route.meta?.title }}</span>
            </div>
          </template>
          <el-empty description="未找到匹配的菜单" :image-size="100" v-else />
        </el-scrollbar>
      </div>
    </div>
  </popup>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { filterTree } from '@/utils/util'

// 定义组件属性
const props = defineProps<{
  modelValue: boolean
}>()
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 组件状态管理
const searchRef = ref<HTMLInputElement>()
const userStore = useUserStore()
const router = useRouter()
const searchText = ref('')
const visible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

// 格式化菜单项
const formatMenuItems = (routes: any[], parentPath: string = '') => {
  let result: any[] = []
  routes.forEach((route) => {
    if (route.meta?.type === 2) {
      const formattedRoute = { ...route }
      if (parentPath) {
        formattedRoute.formattedTitle = `${parentPath}/${route.meta.title}`
      } else {
        formattedRoute.formattedTitle = route.meta.title
      }
      result.push(formattedRoute)
    } else if (route.children && route.children.length > 0) {
      const newParentPath = parentPath ? `${parentPath}/${route.meta.title}` : route.meta.title
      result = [...result, ...formatMenuItems(route.children, newParentPath)]
    }
  })
  return result
}
// 格式化后的菜单列表
const formattedMenus = computed(() => {
  return formatMenuItems(filterTree(userStore.routes, { type: 3 }))
})
// 根据搜索关键词过滤路由
const filteredRoutes = computed(() => {
  const menus = formattedMenus.value
  if (!searchText.value.trim()) {
    return menus
  }
  const keyword = searchText.value.toLowerCase()
  return menus.filter((menu) => {
    return menu.formattedTitle?.toLowerCase().includes(keyword) || menu.meta?.title?.toLowerCase().includes(keyword)
  })
})

// 处理菜单项点击事件
const handleMenuClick = (route: any) => {
  router.push(route.path)
  visible.value = false
}

// 监听弹窗显示/隐藏
watch(
  () => visible.value,
  (value) => {
    if (value) {
      searchText.value = ''
      setTimeout(() => {
        searchRef.value?.focus()
      }, 100)
    }
  }
)
</script>

<style lang="scss" scoped>
.search-container {
  @apply flex flex-col gap-3;

  .search-header {
    @apply px-6;
  }

  .search-body {
    @apply flex-1 px-6;

    &__item {
      @apply flex items-center gap-2 min-w-0 p-3.5 rounded-lg cursor-pointer;
      background: var(--el-fill-color-dark);
      transition: all 0.3s;

      &:hover {
        background: var(--el-color-primary);
        color: #fff;
      }
    }

    :deep(.el-scrollbar__wrap) {
      @apply max-h-[calc(100vh-200px)] min-h-[80px];
    }
  }

  .search-footer {
    @apply flex justify-center items-end gap-4 text-base font-medium;
    @apply border-t border-br pt-[15px] leading-5 px-6;
  }
}
</style>
