import { defineComponent, onMounted, shallowRef, markRaw, computed, watch, h } from 'vue'
import { useRoute } from 'vue-router'
import { usePageTypeSlug } from '@/shared/utils/slug'
import { resolvePagetypeListOverride } from '@/core/registry/pagetypeOverride'
import DefaultList from '@/core/pagetype/default_list.vue'

/**
 * 列表页路由分发器：决定使用覆盖组件还是默认组件
 * 位置：app/router/listPage.ts - 与路由配置在同一目录，职责清晰
 */
export default defineComponent({
  name: 'ListPage',
  setup() {
    const route = useRoute()
    const { pagetypeSlug } = usePageTypeSlug(route)
    const overrideComponent = shallowRef<any | null>(null)

    // 为覆盖组件准备 context（可选，覆盖组件可独立工作）
    const context = computed(() => ({
      route,
      pagetypeSlug: pagetypeSlug.value,
      entity: route.params.entity as string
    }))

    onMounted(async () => {
      // 查找列表页覆盖组件
      const listComp = await resolvePagetypeListOverride(pagetypeSlug.value)
      overrideComponent.value = listComp ? markRaw(listComp) : null
    })

    // 监听路由参数变化，当 entity 变化时重新加载覆盖组件
    watch(() => route.params.entity, async (newEntity, oldEntity) => {
      if (newEntity !== oldEntity) {
        const listComp = await resolvePagetypeListOverride(String(newEntity))
        overrideComponent.value = listComp ? markRaw(listComp) : null
      }
    })

    return () => {
      if (overrideComponent.value) {
        return h(overrideComponent.value, { context: context.value })
      }
      return h(DefaultList)
    }
  }
})

