<script setup lang="ts">
import BussApi from '@/api/BussApi';
import pageWrapper from '@/components/page-wrapper.vue';
import type { Lesson } from '@/types/api/lesson';
import { calcLessonProgress } from '@/utils/lesson';
import { useRouter } from 'uni-mini-router';
import { onMounted, ref } from 'vue';
import { useToast } from 'wot-design-uni';

const toast = useToast()
const router = useRouter()

const expandedCourse = ref(['lesson'])
const groupedLessons = ref<{ [key: string]: Lesson[] }>({})

const openLessonDetail = (courseId: number) => {
  router.push({
    name: 'lesson',
    params: {
      courseId: `${courseId}`
    }
  })
}

onMounted(() => {
  toast.loading({
    msg: '加载中...'
  })
  BussApi.lessons().then(res => {
    toast.close()
    const groupData = res.data.reduce((acc: any, cur: any) => {
      if (!acc[cur.m_lesson_name]) {
        acc[cur.m_lesson_name] = []
      }
      acc[cur.m_lesson_name].push(cur)
      return acc
    }, {})
    groupedLessons.value = groupData
  }).catch(err => {
    toast.error({ msg: err.message })
  })
})
</script>

<template>
  <page-wrapper>
    <div>
      <wd-collapse v-model="expandedCourse">
        <wd-status-tip v-if="Object.keys(groupedLessons).length === 0" image="content" tip="没有微课" />
        <wd-collapse-item v-else v-for="(courses, courseName) in groupedLessons" :title="`${courseName || '无标题课程'}`"
          :name="`${courseName}`" :key="courseName">
          <div class="w-full">
            <wd-status-tip v-if="courses.length === 0" image="content" tip="没有课程小节" />
            <div v-else v-for="(lesson, i) in courses" :key="i" @click="openLessonDetail(lesson.id)"
              class="w-full py-2 flex justify-between items-center gap-20 border-b border-b-solid border-neutral-200 last:border-b-0 first:pt-0 last:pb-0">
              <div class="flex items-center gap-1">
                <wd-icon
                  :name="calcLessonProgress(lesson) === 100 ? 'check-circle' : (calcLessonProgress(lesson) === 0 ? 'circle1' : 'hourglass')"
                  size="16px"></wd-icon>
                <span>{{ lesson.course_name || '无标题视频' }}</span>
              </div>
              <div class="w-32 flex items-center gap-3">
                <wd-progress :percentage="calcLessonProgress(lesson)" hide-text />
                <wd-icon name="arrow-right" size="16px" class="op-85"></wd-icon>
              </div>
            </div>
          </div>
        </wd-collapse-item>
      </wd-collapse>
    </div>
  </page-wrapper>
</template>

<style></style>
