<template>
	<div class="app-container">
		<a-form
			:model="form"
			ref="formRef"
			:label-col="{ span: 4 }"
			:wrapper-col="{ span: 16 }"
			:rules="rules"
			:loading="formLoading"
			layout="horizontal"
		>
			<a-form-item label="试卷类型：">
				<a-select v-model:value="form.examType" placeholder="请选择试卷类型" @change="examTypeChange" allow-clear>
					<a-select-option v-for="item in examTypeEnum" :key="item.value" :value="item.value">
						{{ item.label }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="考试标题" name="examName" :rules="rules.examName">
				<a-input v-model:value="form.examName" placeholder="请输入考试标题" />
			</a-form-item>
			<a-form-item label="选择试卷" name="paperId" :rules="rules.paperId">
				<a-input-group compact>
					<a-input
						v-model:value="selectedPaperName"
						placeholder="请选择试卷"
						readonly
						style="width: calc(100% - 100px)"
					/>
					<a-button type="primary" @click="addPaper" style="width: 100px">选择试卷</a-button>
				</a-input-group>
			</a-form-item>
			<a-form-item label="学期" name="semesterId" :rules="rules.semesterId">
				<a-select v-model:value="form.semesterId" placeholder="请选择学期" allowClear @change="handleSemesterChange">
					<a-select-option v-for="item in semesterList" :key="item.id" :value="item.id">
						{{ item.name }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<!-- <a-form-item label="专业" name="majorId">
				<a-select v-model:value="form.majorId" placeholder="请选择专业" allowClear @change="handleMajorChange">
					<a-select-option v-for="item in majorList" :key="item.id" :value="item.id">
						{{ item.majorName }}
					</a-select-option>
				</a-select>
			</a-form-item> -->
			<a-form-item label="课程" name="courseId" :rules="rules.courseId">
				<a-select v-model:value="form.courseId" placeholder="请选择课程" allowClear :disabled="!form.semesterId">
					<a-select-option v-for="item in courseList" :key="item.courseId" :value="item.courseId">
						{{ item.courseName }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="开始时间" name="startTime" :rules="rules.startTime">
				<a-date-picker
					v-model:value="form.startTime"
					show-time
					format="YYYY-MM-DD HH:mm:ss"
					placeholder="请选择开始时间"
					style="width: 100%"
					:disabledDate="disabledStartDate"
				/>
			</a-form-item>
			<a-form-item label="结束时间" name="endTime" :rules="rules.endTime">
				<a-date-picker
					v-model:value="form.endTime"
					show-time
					format="YYYY-MM-DD HH:mm:ss"
					placeholder="请选择结束时间"
					style="width: 100%"
					:disabledDate="disabledStartDate"
				/>
			</a-form-item>
			<a-form-item label="考试状态" name="examStatus">
				<a-radio-group v-model:value="form.examStatus">
					<a-radio :value="0">未开始</a-radio>
					<a-radio :value="1">已开始</a-radio>
					<a-radio :value="2">已结束</a-radio>
				</a-radio-group>
			</a-form-item>
			<a-form-item>
				<a-space>
					<a-button type="primary" @click="submitForm">提交</a-button>
					<a-button @click="resetForm">重置</a-button>
				</a-space>
			</a-form-item>
		</a-form>

		<a-modal
			v-model:visible="paperPage.showDialog"
			width="70%"
			title="选择试卷"
			@ok="confirmPaperSelect"
			@cancel="() => (paperPage.showDialog = false)"
		>
			<a-form layout="inline">
				<a-form-item label="试卷类型">
					<a-select v-model:value="paperPage.queryParam.paperType" placeholder="请选择试卷类型" disabled>
						<a-select-option v-for="item in paperTypeEnum" :key="item.key" :value="item.key">
							{{ item.value }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item>
					<a-button type="primary" @click="examPaperSubmitForm">查询</a-button>
				</a-form-item>
			</a-form>
			<a-table
				:dataSource="paperPage.tableData"
				:columns="modalColumns"
				rowKey="id"
				:loading="paperPage.listLoading"
				:rowSelection="rowSelection"
				bordered
				:pagination="false"
				style="margin-top: 16px"
			>
				<!-- <template #bodyCell="{ column, record }">
					<template v-if="column.key === 'subjectId'">
						{{ subjectEnumFormat(record.subjectId) }}
					</template>
				</template> -->
			</a-table>
			<a-pagination
				v-show="paperPage.total > 0"
				:total="paperPage.total"
				:current="paperPage.queryParam.pageIndex"
				:pageSize="paperPage.queryParam.pageSize"
				@change="onPageChange"
				@showSizeChange="onPageSizeChange"
				show-size-changer
				style="margin-top: 16px; text-align: right"
			/>
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted, computed } from 'vue'
	import { message } from 'ant-design-vue'
	import { useExamStore } from '@/store/exam.js'
	import examManagerApi from '@/api/exam/paper/examManager.js'
	import examPaperApi from '@/api/exam/paper/examPaperApi.js'
	import resourceAuditApi from '@/api/resourceAudit.js'
	import tool from '@/utils/tool'
	import dayjs from 'dayjs'
	const emit = defineEmits(['success'])
	const props = defineProps({
		id: {
			type: Number,
			default: null
		}
	})
	const formRef = ref()
	const examStore = useExamStore()
	const paperTypeEnum = computed(() => examStore.paperTypeEnum.filter((item) => item.key !== '5'))
	const examTypeEnum = tool.dictList('EXAM_TYPE').filter((item) => item.value !== '3')
	console.log('examTypeEnum', examTypeEnum)
	console.log('paperTypeEnum', paperTypeEnum.value)
	const formLoading = ref(false)
	const semesterList = ref([])
	const majorList = ref([])
	const courseList = ref([])
	const form = reactive({
		id: null,
		examName: '',
		paperId: null,
		courseId: null,
		startTime: null,
		endTime: null,
		examStatus: 0,
		semesterId: null
		// majorId: null
	})

	const rules = {
		examName: [{ required: true, message: '请输入考试标题', trigger: 'blur' }],
		paperId: [{ required: true, message: '请选择试卷', trigger: 'change' }],
		startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
		endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
		semesterId: [{ required: true, message: '请选择学期', trigger: 'change' }],
		courseId: [{ required: true, message: '请选择课程', trigger: 'change' }]
	}

	const selectedPaperName = ref('')

	const modalColumns = [
		{ title: 'Id', dataIndex: 'id', key: 'id', width: 90 },
		// { title: '学科', dataIndex: 'subjectId', key: 'subjectId', width: 120 },
		{ title: '名称', dataIndex: 'name', key: 'name' },
		{
			title: '创建时间',
			dataIndex: 'createTimeStr',
			key: 'createTimeStr',
			width: 200
		}
	]

	const paperPage = reactive({
		subjectFilter: [],
		selectedPaper: null,
		showDialog: false,
		queryParam: {
			paperId: null,
			paperType: '6',
			pageIndex: 1,
			pageSize: 5
		},
		listLoading: false,
		tableData: [],
		total: 0
	})

	// 试卷选择表格单选
	const selectedRowKeys = ref([])
	const rowSelection = reactive({
		type: 'radio',
		selectedRowKeys: selectedRowKeys,
		onChange: (selectedRowKeysVal, selectedRows) => {
			selectedRowKeys.value = selectedRowKeysVal
			paperPage.selectedPaper = selectedRows[0] || null
		}
	})
	// 学期变更处理函数
	const handleSemesterChange = (value) => {
		form.courseId = null
		courseList.value = []

		// 如果学期和专业都已选择，则查询课程列表
		if (value) {
			loadCourseList()
		}
	}

	// 专业变更处理函数
	// const handleMajorChange = (value) => {
	// 	form.courseId = null
	// 	courseList.value = []

	// 	// 如果学期和专业都已选择，则查询课程列表
	// 	if (value && form.semesterId) {
	// 		loadCourseList()
	// 	}
	// }

	// 加载课程列表
	const loadCourseList = () => {
		// 添加加载状态
		const courseLoading = message.loading('正在加载课程列表...', 0)
		// 根据选择的学期和专业加载课程列表
		resourceAuditApi
			.courseAllList({
				semesterId: form.semesterId
			})
			.then((res) => {
				if (res.code === 200) {
					courseList.value = res.data
				} else {
					message.error('加载课程列表失败：' + (res.msg || '未知错误'))
				}
			})
			.catch((err) => {
				message.error('加载课程列表失败：' + (err.message || '网络错误'))
			})
			.finally(() => {
				courseLoading()
			})
	}
	// 禁用开始时间大于今天的日期
	const disabledStartDate = (current) => {
		// 禁用大于今天的日期
		return current && current < dayjs().endOf('day')
	}

	// 试卷类型变更
	const paperTypeChange = () => {
		paperPage.queryParam.paperId = null
		form.paperId = null
		selectedPaperName.value = ''
	}
	// 考试类型变更
	const examTypeChange = (type) => {
		switch (type) {
			case '1': // 普通考试
				paperPage.queryParam.paperType = '6'
				break
			case '2': // 章节测验
				paperPage.queryParam.paperType = '3'
				break
			case '4': // 课时作业
				paperPage.queryParam.paperType = '2'
				break
		}
	}

	// 选择试卷
	const addPaper = () => {
		paperPage.showDialog = true
		search()
	}

	// 查询试卷
	const search = async () => {
		paperPage.listLoading = true
		paperPage.showDialog = true
		const params = {
			...paperPage.queryParam,
			current: paperPage.queryParam.pageIndex,
			size: paperPage.queryParam.pageSize,
			paperType: paperPage.queryParam.paperType
		}
		delete params.pageIndex
		delete params.pageSize
		const data = await examPaperApi.selectExamList(params)
		const re = data
		paperPage.tableData = re.records
		paperPage.total = re.total
		paperPage.queryParam.pageIndex = re.current
		paperPage.listLoading = false
	}

	// 确认选择试卷
	const confirmPaperSelect = () => {
		if (!paperPage.selectedPaper) {
			message.warning('请选择一个试卷')
			return
		}
		form.paperId = paperPage.selectedPaper.id
		selectedPaperName.value = paperPage.selectedPaper.name
		paperPage.showDialog = false
		selectedRowKeys.value = []
	}

	// 分页
	const onPageChange = (page) => {
		paperPage.queryParam.pageIndex = page
		search()
	}
	const onPageSizeChange = (current, size) => {
		paperPage.queryParam.pageSize = size
		paperPage.queryParam.pageIndex = 1
		search()
	}

	// 查询按钮
	const examPaperSubmitForm = () => {
		paperPage.queryParam.pageIndex = 1
		search()
	}

	// 提交表单
	const submitForm = () => {
		formRef.value.validate().then(async () => {
			formLoading.value = true
			try {
				const submitData = {
					...form,
					startTime: form.startTime ? form.startTime.format('YYYY-MM-DD HH:mm:ss') : null,
					endTime: form.endTime ? form.endTime.format('YYYY-MM-DD HH:mm:ss') : null
				}

				if (form.id) {
					await examManagerApi.edit(submitData)
				} else {
					await examManagerApi.createExam(submitData)
				}
				emit('success')
			} catch (e) {
				console.error(e)
			} finally {
				formLoading.value = false
			}
		})
	}

	// 重置表单
	const resetForm = () => {
		const lastId = form.id
		formRef.value.resetFields()
		form.id = lastId
		form.examName = ''
		form.paperId = null
		form.semesterId = null // 重置学期
		// form.majorId = null // 重置专业
		form.courseId = null
		form.startTime = null
		form.endTime = null
		form.examStatus = 0
		selectedPaperName.value = ''
		paperPage.queryParam.paperType = null
		majorList.value = [] // 清空专业列表
		courseList.value = [] // 清空课程列表
	}

	// 初始化
	onMounted(() => {
		const id = props.id
		if (id && parseInt(id) !== 0) {
			formLoading.value = true
			examManagerApi
				.select(id)
				.then((re) => {
					Object.assign(form, {
						...re,
						startTime: re.startTime ? dayjs(re.startTime) : null,
						endTime: re.endTime ? dayjs(re.endTime) : null
					})
					// 如果有试卷ID，需要获取试卷名称显示
					if (re.paperId) {
						paperPage.queryParam.paperId = re.paperId
						// 这里可以根据需要调用接口获取试卷名称
						examPaperApi.select(re.paperId).then((r) => {
							selectedPaperName.value = r.name
						})
					}

					// 如果是编辑模式，需要根据已有数据加载相应的课程列表
					if (re.semesterId) {
						// 直接加载课程列表
						loadCourseList()
					}

					formLoading.value = false
				})
				.catch((err) => {
					message.error('加载考试信息失败：' + (err.message || '网络错误'))
					formLoading.value = false
				})
		}
		// 加载学期列表
		const semesterLoading = message.loading('正在加载学期列表...', 0)
		resourceAuditApi
			.semesterDownList()
			.then((res) => {
				if (res.code === 200) {
					semesterList.value = res.data
				} else {
					message.error('加载学期列表失败：' + (res.msg || '未知错误'))
				}
			})
			.catch((err) => {
				message.error('加载学期列表失败：' + (err.message || '网络错误'))
			})
			.finally(() => {
				semesterLoading()
			})
		// 加载专业
		// const majorLoading = message.loading('正在加载专业列表...', 0)
		// resourceAuditApi
		// 	.majordownList()
		// 	.then((res) => {
		// 		if (res.code === 200) {
		// 			majorList.value = res.data
		// 		} else {
		// 			message.error('加载专业列表失败：' + (res.msg || '未知错误'))
		// 		}
		// 	})
		// 	.catch((err) => {
		// 		message.error('加载专业列表失败：' + (err.message || '网络错误'))
		// 	})
		// 	.finally(() => {
		// 		majorLoading()
		// 	})
	})
</script>

<style lang="less" scoped>
	.app-container {
		padding: 24px;
		background: #fff;
	}
</style>
