<script lang="ts" setup>
import type { IResponse } from '~/api'
import { getCourseDetail } from '~/api/course'
import type { ICourse } from '~/types'

const {
  fullPath,
  params: { id },
} = useRoute()
const router = useRouter()
const { setBreadcrumbs } = useBreadcrumbs()

const {
  data: course,
  status: courseStatus,
  error: courseError,
} = useAsyncData<
  IResponse<{
    data: ICourse
  }>,
  IResponse
>(() => getCourseDetail(id as string))

definePageMeta({
  requiresAuth: true,
  hideSidebar: true,
})

watch(
  () => course.value,
  (data) => {
    useHead({
      title: `${course.value?.data.courseName || '课程不存在'} - 课程管理`,
    })

    if (data?.data.courseName) {
      setBreadcrumbs([
        {
          label: '课程管理',
          path: '/course',
        },
        {
          label: data.data.courseName || '课程不存在',
        },
      ])
    }
  },
)

onMounted(() => {
  if (fullPath === `/course/${id}`) {
    router.replace(`/course/${id}/chapters`)
  }
})

watch(
  () => useRoute().fullPath,
  (newPath) => {
    if (newPath === `/course/${id}`) {
      router.replace(`/course/${id}/chapters`)
    }
  },
)
</script>

<template>
  <AppContainer
    :nav-secondary="[
      {
        label: '课程章节',
        to: `/course/${id}/chapters`,
      },
      {
        label: '教师团队',
        to: `/course/${id}/team`,
      },
      {
        label: '学生班级',
        to: `/course/${id}/classes`,
      },
      {
        label: '学生评价',
        to: `/course/${id}/evaluation`,
      },
    ]"
  >
    <div v-if="courseStatus === 'error'">
      <EmptyScreen
        title="课程加载失败"
        :description="courseError?.data?.msg || '请求失败'"
        icon="tabler:exclamation-circle"
      />
    </div>
    <EmptyScreen
      v-else-if="courseStatus === 'pending'"
      title="加载中..."
      icon="svg-spinners:90-ring-with-bg"
    />
    <NuxtPage
      v-else
      :page-key="fullPath"
    />
  </AppContainer>
</template>

<style scoped></style>