<template>
	<div class="course-detail-page">
		<!-- 顶部课程信息卡片 -->
		<a-card class="course-info-card" bordered>
			<div class="course-info-main">
				<div class="cover-box">
					<a-image shape="square" :size="120" :src="sysConfig.FILE_URL + course.coverImagePath" />
				</div>
				<div class="info-box">
					<div class="title">{{ course.courseName }}</div>
					<div class="meta">
						<p><EyeOutlined class="mr-0" /> {{ course.viewCount }}</p>
						<p><ClockCircleOutlined class="mr-0" /> {{ course.publishTime }}</p>
					</div>
				</div>
				<div class="action-box">
					<div class="btn-group">
						<a-button @click="handleEdit(course)"> <EditOutlined /> 编辑课程</a-button>
						<a-button v-if="course.putawayStatus == '1'" @click="handleTakeOffCourse(0)">
							<DownOutlined /> 下架课程
						</a-button>
						<a-button v-else @click="handleTakeOffCourse(1)"> <UpOutlined /> 上架课程 </a-button>
						<a-button @click="handleDeleteCourse"> <DeleteOutlined /> 删除课程</a-button>
					</div>
					<div class="extra-box">
						<div class="row">
							<span>当前状态</span><span class="status-normal">● {{ course.putawayStatusName }}</span>
						</div>
						<div class="row">
							<span>授课教师</span><span>{{ course.teacherIdName }}</span>
						</div>
						<div class="row">
							<span>课程分类</span><span>{{ course.courseTypeName }}</span>
						</div>
						<div class="row">
							<span>课时数量</span
							><span>{{
								course.timeLimitType === '0' ? '无限课时' : getTimeLimit(course.startTime, course.endTime)
							}}</span>
						</div>
					</div>
				</div>
			</div>
		</a-card>

		<!-- tab 导航 -->
		<a-tabs v-model:activeKey="activeTab" class="course-tabs">
			<a-tab-pane key="detail" tab="课程详情" />
<!--			<a-tab-pane key="homework" tab="批改作业" />-->
<!--			<a-tab-pane key="test" tab="批改测试" />-->
<!--			<a-tab-pane key="student" tab="学员详情" />-->
<!--			<a-tab-pane key="stat" tab="学习统计" />-->
		</a-tabs>

		<LessonDetails
			v-if="activeTab === 'detail'"
			:pagedSections="pagedSections"
			:currentPage="currentPage"
			:pageSize="pageSize"
			:sectionsLength="course.sections?.length || 0"
			@edit-lesson="onEditLesson"
			@delete-lesson="onDeleteLesson"
			@page-change="onPageChange"
			@page-size-change="onPageSizeChange"
		/>
		<StudentDetails :courseInfoId="courseInfoId" v-if="activeTab === 'student'" />
		<LearningStatistics v-if="activeTab === 'stat'" />

		<!-- 编辑课程弹窗 -->
		<a-modal v-model:visible="editVisible" title="新建工单" :footer="null" width="700px" @cancel="editVisible = false">
			<CourseAdd />
		</a-modal>
		<!-- 编辑课时弹窗 -->
		<AddClassHours v-model:visible="addClassHoursVisible" @ok="onAddClassHoursOk" />
	</div>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { EyeOutlined, ClockCircleOutlined, EditOutlined, DeleteOutlined, DownOutlined } from '@ant-design/icons-vue'
	import { message, Modal } from 'ant-design-vue'
	import AddClassHours from './components/AddClassHours.vue'
	import LessonDetails from './components/tab/LessonDetails.vue'
	// import StudentDetails from './components/tab/StudentDetails.vue'
	import StudentDetails from '@/views/courseAdd/components/StudentDetails.vue'
	import LearningStatistics from './components/tab/LearningStatistics.vue'
	import CourseAdd from '../courseAdd/index.vue'
	import { getCourseDetail, getChapterAllList, updateCourseStatus, deleteCourse } from '@/api/course/courseDetail.js'
	import sysConfig from '@/config/index'
	import { useRouter, useRoute } from 'vue-router'

	const router = useRouter()
	const route = useRoute()

	const course = ref({
		courseId: '',
		courseName: '',
		courseType: '',
		courseTypeName: '',
		courseDesc: '',
		teacherId: '',
		teacherIdName: '',
		collegeId: '',
		collegeIdName: '',
		majorId: '',
		majorIdName: '',
		publishTime: '',
		timeLimitType: 0,
		startTime: '',
		endTime: '',
		coverImageId: '',
		coverImagePath: '',
		collegeTwoId: '',
		collegeTwoIdName: '',
		collegeThreeId: '',
		collegeThreeIdName: '',
		collegeAllId: '',
		collegeAllIdName: '',
		putawayStatus: '',
		putawayStatusName: '',
		sections: []
	})
	const activeTab = ref('detail')
	const currentPage = ref(1)
	const courseInfoId = ref(route.query.id)
	const pageSize = ref(10)
	const editVisible = ref(false)
	const addClassHoursVisible = ref(false)
	const editingLesson = ref(null)

	const pagedSections = computed(() => {
		if (!course.value.sections) return []
		const start = (currentPage.value - 1) * pageSize.value
		return course.value.sections.slice(start, start + pageSize.value)
	})

	onMounted(() => {
		const params = {
			courseId: route.query.id
		}
		// 获取课程基本信息
		getCourseDetail(params).then((res) => {
			course.value = {
				...course.value,
				...res.data
			}

			// 获取章节和课时信息
			getChapterAllList(params).then((chapterRes) => {
				if (chapterRes.data && Array.isArray(chapterRes.data)) {
					course.value.sections = chapterRes.data
				}
			})
		})
	})
	const handleEdit = (item) => {
		router.push({
			path: '/portal/courseAdd',
			query: {
				id: item.courseId
			}
		})
	}
	function onPageChange(page) {
		currentPage.value = page
	}
	function onPageSizeChange(size) {
		pageSize.value = size
		currentPage.value = 1
	}
	function onEditLesson(lesson) {
		editingLesson.value = lesson
		addClassHoursVisible.value = true
	}
	function onDeleteLesson(lesson) {
		// 这里只做mock删除
		course.value.sections.forEach((section) => {
			section.lessons = section.lessons.filter((l) => l.id !== lesson.id)
		})
	}
	function onAddClassHoursOk(data) {
		// 这里只做mock保存
		if (editingLesson.value) {
			Object.assign(editingLesson.value, data)
		}
		addClassHoursVisible.value = false
	}
	function getTimeLimit(startTime, endTime) {
		const start = new Date(startTime)
		const end = new Date(endTime)
		const diff = end - start
		const days = Math.floor(diff / (1000 * 60 * 60 * 24))
		const hours = Math.floor((diff / (1000 * 60 * 60)) % 24)
		const minutes = Math.floor((diff / (1000 * 60)) % 60)
		return `${days * 24 + hours}小时${minutes}分钟`
	}

	// 处理下架课程
	function handleTakeOffCourse(type) {
		Modal.confirm({
			title: type === 0 ? '确认下架课程' : '确认上架课程',
			content: `确定要${type === 0 ? '下架' : '上架'}课程"${course.value.courseName}"吗？`,
			okText: '确认',
			cancelText: '取消',
			onOk: async () => {
				try {
					const params = {
						courseId: course.value.courseId,
						putawayStatus: type
					}
					const res = await updateCourseStatus(params)
					if (res.code === 200) {
						message.success(`${type === 0 ? '下架' : '上架'}成功`)
						// 更新课程状态
						course.value.putawayStatus = type
						course.value.putawayStatusName = `${type === 0 ? '已下架' : '已上架'}`
					} else {
						message.error(res.msg || '操作失败')
					}
				} catch (error) {
					console.error(`${type === 0 ? '下架' : '上架'}课程失败:`, error)
					message.error(`${type === 0 ? '下架' : '上架'}课程失败，请稍后重试`)
				}
			}
		})
	}

	// 处理删除课程
	function handleDeleteCourse() {
		Modal.confirm({
			title: '确认删除课程',
			content: `确定要删除课程"${course.value.courseName}"吗？删除后将无法恢复。`,
			okText: '确认删除',
			okType: 'danger',
			cancelText: '取消',
			onOk: async () => {
				try {
					const params = [
						{
							courseId: course.value.courseId
						}
					]
					const res = await deleteCourse(params)
					if (res.code === 200) {
						message.success('课程删除成功')
						// 删除成功后返回课程列表页
						window.history.back()
					} else {
						message.error(res.msg || '删除失败')
					}
				} catch (error) {
					console.error('删除课程失败:', error)
					message.error('删除课程失败，请稍后重试')
				}
			}
		})
	}
</script>

<style lang="less" scoped>
	.course-detail-page {
		background: #f7f8fa;
		min-height: 100vh;
		padding: 32px 0 0 0;

		.course-info-card {
			width: 1200px;
			margin: 0 auto 24px auto;
			border-radius: 12px;
			box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
			border: none;
			.course-info-main {
				display: flex;
				align-items: flex-start;
				padding: 32px 32px 24px 32px;
				.cover-box {
					width: 160px;
					height: 120px;
					background: #f2f3f5;
					border-radius: 8px;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 32px;
					.ant-avatar {
						background: #e6e9ef;
						font-size: 48px;
					}
					:deep(.ant-image),
					:deep(.ant-image-img) {
						width: 100%;
						height: 100%;
					}
				}
				.info-box {
					flex: 1;
					.title {
						font-size: 22px;
						font-weight: 600;
						color: #222;
						margin-bottom: 12px;
					}
					.meta {
						color: #999;
						font-size: 14px;
						span {
							margin-right: 24px;
							display: inline-flex;
							align-items: center;
							.anticon {
								margin-right: 4px;
							}
						}
					}
				}
				.action-box {
					flex: 1;
					color: #999;
					.extra-box {
						min-width: 180px;
						margin-left: 32px;
						display: flex;
						justify-content: space-evenly;
						.row {
							display: flex;
							flex-direction: column;
							justify-content: space-between;
							font-size: 14px;
							margin-bottom: 8px;
							span:last-child {
								font-weight: 500;
							}
							.status-normal {
								margin-top: 10px;
								color: #52c41a;
								font-weight: 600;
								margin-left: 8px;
							}
						}
					}
					.btn-group {
						display: flex;
						flex-direction: row;
						margin-left: 40px;
						gap: 10px;
						justify-content: flex-end;
						.ant-btn {
							margin-bottom: 12px;
							width: 120px;
							font-size: 14px;
							border-radius: 6px;
						}
						.ant-btn-primary {
							background: #347aff;
							border-color: #347aff;
						}
					}
				}
			}
		}

		.course-tabs {
			width: 1200px;
			margin: 0 auto 0 auto;
			background: #fff;
			border-radius: 12px 12px 0 0;
			padding-left: 20px;
			.ant-tabs-bar {
				border-bottom: 1px solid #f0f0f0;
				margin-bottom: 0;
			}
			.ant-tabs-nav {
				font-size: 16px;
				.ant-tabs-tab {
					padding: 18px 32px 14px 32px;
					font-weight: 500;
					color: #666;
					&.ant-tabs-tab-active {
						color: #347aff;
						font-weight: 600;
					}
				}
				.ant-tabs-ink-bar {
					background: #347aff;
					height: 3px;
					border-radius: 2px 2px 0 0;
				}
			}
		}
		.mr-0 {
			margin-right: 5px !important;
		}
	}
</style>
