<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="gradeLevel" :rules="rules.gradeLevel">
				<a-select v-model:value="form.gradeLevel" placeholder="请选择年级" @change="levelChange">
					<a-select-option v-for="item in levelEnum" :key="item.key" :value="item.key">
						{{ item.value }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="标题" name="title" :rules="rules.title">
				<a-input v-model:value="form.title" placeholder="请输入任务标题" />
			</a-form-item>
			<a-form-item label="试卷">
				<a-table :dataSource="form.paperItems" :columns="paperColumns" rowKey="id" bordered :pagination="false">
					<template #bodyCell="{ column, record }">
						<template v-if="column.key === 'subjectId'">
							{{ subjectEnumFormat(record.subjectId) }}
						</template>
						<template v-else-if="column.key === 'action'">
							<a-button type="link" danger @click="removePaper(record)">删除</a-button>
						</template>
					</template>
				</a-table>
			</a-form-item>
			<a-form-item>
				<a-space>
					<a-button type="primary" @click="submitForm">提交</a-button>
					<a-button @click="resetForm">重置</a-button>
					<a-button type="dashed" @click="addPaper">添加试卷</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.subjectId" allowClear style="width: 200px">
						<a-select-option v-for="item in paperPage.subjectFilter" :key="item.id" :value="item.id">
							{{ item.name }} ( {{ item.levelName }} )
						</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 } from 'vue'
	import { useExamStore } from '@/store/exam.js'
	import taskApi from '@/api/exam/paper/task.js'
	import examPaperApi from '@/api/exam/paper/examPaperApi.js'
	const emit = defineEmits(['success'])
	const props = defineProps({
		id: {
			type: Number,
			default: null
		}
	})
	const formRef = ref()
	const examStore = useExamStore()
	const { subjectEnumFormat } = examStore
	const levelEnum = computed(() => examStore.getLevelEnum)
	const formLoading = ref(false)
	const form = reactive({
		id: null,
		gradeLevel: null,
		title: '',
		paperItems: []
	})

	const rules = {
		gradeLevel: [{ required: true, message: '请选择年级', trigger: 'change' }],
		title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }]
	}

	const paperColumns = [
		{ title: '学科', dataIndex: 'subjectId', key: 'subjectId', width: 120 },
		{ title: '名称', dataIndex: 'name', key: 'name' },
		{ title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 160 },
		{ title: '操作', key: 'action', width: 100 }
	]

	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: [],
		multipleSelection: [],
		showDialog: false,
		queryParam: {
			subjectId: null,
			level: null,
			paperType: 6,
			pageIndex: 1,
			pageSize: 5
		},
		listLoading: false,
		tableData: [],
		total: 0
	})

	// 试卷选择表格多选
	const selectedRowKeys = ref([])
	const rowSelection = reactive({
		selectedRowKeys: selectedRowKeys,
		onChange: (selectedRowKeysVal, selectedRows) => {
			selectedRowKeys.value = selectedRowKeysVal
			paperPage.multipleSelection = selectedRows
		}
	})

	// 初始化学科
	const initSubject = async (cb) => {
		await examStore.initSubject()
		paperPage.subjectFilter = examStore.subjects
		if (cb) cb()
	}

	// 年级变更
	const levelChange = () => {
		paperPage.queryParam.subjectId = null
		paperPage.subjectFilter = examStore.subjects.filter((data) => data.level === form.gradeLevel)
	}

	// 添加试卷
	const addPaper = () => {
		paperPage.queryParam.level = form.gradeLevel
		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
		}
		delete params.pageIndex
		delete params.pageSize
		const data = await examPaperApi.taskExamPage(params)
		const re = data
		paperPage.tableData = re.records
		paperPage.total = re.total
		paperPage.queryParam.pageIndex = re.current
		paperPage.listLoading = false
	}

	// 确认选择试卷
	const confirmPaperSelect = () => {
		paperPage.multipleSelection.forEach((ep) => {
			if (!form.paperItems.some((item) => item.id === ep.id)) {
				form.paperItems.push(ep)
			}
		})
		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 removePaper = (row) => {
		const idx = form.paperItems.findIndex((item) => item.id === row.id)
		if (idx !== -1) form.paperItems.splice(idx, 1)
	}

	// 提交表单
	const submitForm = () => {
		formRef.value.validate().then(async () => {
			formLoading.value = true
			try {
				await taskApi.edit(form)
				emit('success')
			} catch (e) {
				//
			} finally {
				formLoading.value = false
			}
		})
	}

	// 重置表单
	const resetForm = () => {
		const lastId = form.id
		formRef.value.resetFields()
		form.id = lastId
		form.gradeLevel = null
		form.title = ''
		form.paperItems = []
	}

	// 初始化
	onMounted(() => {
		initSubject(() => {
			paperPage.subjectFilter = examStore.subjects
		})
		const id = props.id
		if (id && parseInt(id) !== 0) {
			formLoading.value = true
			taskApi.select(id).then((re) => {
				Object.assign(form, re)
				formLoading.value = false
			})
		}
	})
</script>

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