// hooks/useCourse.ts /** * 课程相关的可复用逻辑 */ import { ref } from 'vue' import { courseApi } from '@/api/modules/course' import type { ICourseDetail, ICatalogue, IChapter, IVipInfo } from '@/types/course' export function useCourse() { const loading = ref(false) const courseDetail = ref(null) const catalogueList = ref([]) const chapterList = ref([]) const userVip = ref(null) /** * 获取课程详情 */ const fetchCourseDetail = async (courseId: number) => { try { loading.value = true const res = await courseApi.getCourseDetail(courseId) if (res.code === 0 && res.data) { courseDetail.value = res.data.course catalogueList.value = res.data.catalogues || [] return res.data } } catch (error) { console.error('获取课程详情失败:', error) throw error } finally { loading.value = false } } /** * 获取章节列表 */ const fetchChapterList = async (catalogueId: number) => { try { const res = await courseApi.getCatalogueChapterList(catalogueId) if (res.code === 0) { chapterList.value = res.chapterList || [] return res.chapterList } } catch (error) { console.error('获取章节列表失败:', error) chapterList.value = [] throw error } } /** * 检查VIP状态 */ const checkVipStatus = async (courseId: number) => { try { const res = await courseApi.checkCourseVip(courseId) if (res.code === 0) { userVip.value = res.userVip || null return res.userVip } } catch (error) { console.error('检查VIP状态失败:', error) userVip.value = null throw error } } /** * 领取免费课程 */ const getFreeCourse = async (catalogueId: number) => { try { const res = await courseApi.startStudyForMF(catalogueId) if (res.code === 0) { uni.showToast({ title: '领取成功', icon: 'success' }) return true } return false } catch (error) { console.error('领取免费课程失败:', error) throw error } } return { loading, courseDetail, catalogueList, chapterList, userVip, fetchCourseDetail, fetchChapterList, checkVipStatus, getFreeCourse } }