<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="考试标题" 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="chapterId">
				<a-select v-model:value="form.chapterId" placeholder="请选择课程（可选）" allowClear @change="chapterChange">
					<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%"
				/>
			</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="请选择试卷类型"
						@change="paperTypeChange"
					>
						<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 dayjs from 'dayjs'
	const emit = defineEmits(['success'])
	const props = defineProps({
		id: {
			type: Number,
			default: null
		}
	})
	const formRef = ref()
	const examStore = useExamStore()
	const { subjectEnumFormat } = examStore
	const paperTypeEnum = computed(() => examStore.paperTypeEnum)
	const formLoading = ref(false)
	const courseList = ref([])
	const form = reactive({
		id: null,
		examName: '',
		paperId: null,
		chapterId: null,
		startTime: null,
		endTime: null,
		examStatus: 0
	})

	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' }]
	}

	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: {
			subjectId: null,
			paperType: null,
			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 chapterChange = async () => {
		form.chapterId = ''
	}

	// 禁用开始时间大于今天的日期
	const disabledStartDate = (current) => {
		// 禁用大于今天的日期
		return current && current < dayjs().endOf('day')
	}

	// 试卷类型变更
	const paperTypeChange = () => {
		paperPage.queryParam.subjectId = null
		form.paperId = null
		selectedPaperName.value = ''
	}

	// 选择试卷
	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.pageList(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.chapterId = null
		form.startTime = null
		form.endTime = null
		form.examStatus = 0
		selectedPaperName.value = ''
		paperPage.queryParam.paperType = null
	}

	// 初始化
	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) {
					// 这里可以根据需要调用接口获取试卷名称
					selectedPaperName.value = '已选择试卷'
				}
				formLoading.value = false
			})
		}
		resourceAuditApi.courseAllList().then((re) => {
			if (re.code === 200) {
				courseList.value = re.data
			}
		})
	})
</script>

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