<template>
	<div class="app-container">
		<a-form
			:model="form"
			ref="formRef"
			:label-col="{ span: 4 }"
			:wrapper-col="{ span: 16 }"
			:rules="rules"
			:loading="formLoading"
		>
			<!-- <a-form-item label="年级" name="level" :rules="rules.level">
				<a-select v-model:value="form.level" 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="subjectId" :rules="rules.subjectId">
				<a-select v-model:value="form.subjectId" placeholder="请选择学科">
					<a-select-option v-for="item in subjectFilter" :key="item.id" :value="item.id">
						{{ item.name + ' ( ' + item.levelName + ' )' }}
					</a-select-option>
				</a-select>
			</a-form-item> -->
			<a-form-item label="类型" name="paperType" :rules="rules.paperType">
				<a-select v-model:value="form.paperType" placeholder="请选择试卷类型" @change="handPaperTypeChange">
					<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 label="时间限制" v-if="form.paperType === 4">
				<a-range-picker
					v-model:value="form.limitDateTime"
					show-time
					format="YYYY-MM-DD HH:mm:ss"
					:placeholder="['开始日期', '结束日期']"
				/>
			</a-form-item>
			<a-form-item label="名称" name="name" :rules="rules.name">
				<a-input v-model:value="form.name" placeholder="请输入试卷名称" :maxLength="50" />
			</a-form-item>
			<template v-for="(titleItem, index) in form.titleItems" :key="index">
				<a-form-item :label="'标题' + (index + 1)" required>
					<a-input v-model:value="titleItem.name" style="width: 80%" :maxLength="50" />
					<a-button type="link" @click="addQuestion(titleItem)" style="margin-left: 20px">添加题目</a-button>
					<a-button type="link" danger @click="removeTitleItem(index)">删除</a-button>
					<a-card v-if="titleItem.questionItems.length !== 0" class="exampaper-item-box">
						<template v-for="(questionItem, questionIndex) in titleItem.questionItems" :key="questionIndex">
							<a-form-item :label="'题目' + (questionIndex + 1)" style="margin-bottom: 15px">
								<a-row>
									<a-col :span="23">
										<QuestionShow :qType="questionItem.questionType" :question="questionItem" />
									</a-col>
									<a-col :span="1">
										<a-button type="link" danger @click="removeQuestion(titleItem, questionIndex)">删除</a-button>
									</a-col>
								</a-row>
							</a-form-item>
						</template>
					</a-card>
				</a-form-item>
			</template>
			<a-form-item label="建议时长" name="suggestTime" :rules="rules.suggestTime">
				<a-input v-model:value="form.suggestTime" placeholder="分钟" :maxLength="10" />
			</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="addTitle">添加标题</a-button>
				</a-space>
			</a-form-item>
		</a-form>
		<a-modal
			v-model:visible="questionPage.showDialog"
			title="选择题目"
			width="70%"
			@ok="confirmQuestionSelect"
			@cancel="askCancel"
		>
			<a-form layout="inline">
				<a-form-item label="ID">
					<a-input v-model:value="questionPage.queryParam.id" allow-clear />
				</a-form-item>
				<a-form-item label="题型">
					<a-select v-model:value="questionPage.queryParam.questionType" allow-clear style="width: 120px">
						<a-select-option v-for="item in questionTypeEnum" :key="item.key" :value="item.key">
							{{ item.value }}
						</a-select-option>
					</a-select>
				</a-form-item>
				<!-- <a-form-item label="题库类型">
					<a-select v-model:value="questionPage.queryParam.bankType" allow-clear style="width: 120px">
						<a-select-option v-for="item in bankTypeEnum" :key="item.key" :value="item.key">
							{{ item.value }}
						</a-select-option>
					</a-select>
				</a-form-item> -->
				<a-form-item>
					<a-button type="primary" @click="queryForm">查询</a-button>
				</a-form-item>
			</a-form>
			<a-table
				:dataSource="questionPage.tableData"
				:loading="questionPage.listLoading"
				rowKey="id"
				:rowSelection="rowSelection"
				:pagination="false"
				style="margin-top: 16px"
			>
				<a-table-column type="selection" width="35" />
				<a-table-column title="Id" dataIndex="id" width="60" />
				<a-table-column title="题型" dataIndex="questionType" :customRender="questionTypeFormatter" width="70" />
				<a-table-column title="题干" dataIndex="shortTitle" ellipsis />
			</a-table>
			<a-pagination
				v-if="questionPage.total > 0"
				:total="questionPage.total"
				:current="questionPage.queryParam.pageIndex"
				:pageSize="questionPage.queryParam.pageSize"
				@change="onPageChange"
				style="margin-top: 16px; text-align: right"
			/>
		</a-modal>
	</div>
</template>

<script setup>
	import { ref, reactive, computed, onMounted } from 'vue'
	import { useExamStore } from '@/store/exam'
	import examPaperApi from '@/api/exam/paper/examPaperApi'
	import questionApi from '@/api/exam/question/tQuestionApi'
	import QuestionShow from '@/views/exm/question/components/Show.vue'
	import { message } from 'ant-design-vue'
	const bankTypeEnum = computed(() => examStore.getBankTypeEnum)
	const props = defineProps({
		id: {
			type: Number,
			default: 0
		}
	})
	const emit = defineEmits(['success'])
	const formRef = ref()
	const examStore = useExamStore()

	const form = reactive({
		id: null,
		// level: null,
		// subjectId: null,
		paperType: null,
		limitDateTime: [],
		name: '',
		suggestTime: null,
		titleItems: []
	})
	const subjectFilter = ref([])
	const formLoading = ref(false)
	const rules = {
		level: [{ required: true, message: '请选择年级', trigger: 'change' }],
		subjectId: [{ required: true, message: '请选择学科', trigger: 'change' }],
		paperType: [{ required: true, message: '请选择试卷类型', trigger: 'change' }],
		name: [{ required: true, message: '请输入试卷名称', trigger: 'blur' }],
		suggestTime: [{ required: true, message: '请输入建议时长', trigger: 'blur' }]
	}
	const questionPage = reactive({
		multipleSelection: [],
		showDialog: false,
		queryParam: {
			id: null,
			questionType: null,
			subjectId: 1,
			pageIndex: 1,
			pageSize: 5
		},
		listLoading: false,
		tableData: [],
		total: 0
	})
	const currentTitleItem = ref(null)

	const levelEnum = computed(() => examStore.levelEnum)
	const paperTypeEnum = computed(() => examStore.paperTypeEnum)
	const questionTypeEnum = computed(() => examStore.questionTypeEnum)
	const subjects = computed(() => examStore.subjects)

	onMounted(async () => {
		// await examStore.initSubject()
		// subjectFilter.value = subjects.value
		const id = props.id
		if (id && parseInt(id) !== 0) {
			formLoading.value = true
			const re = await examPaperApi.select(id)
			re.paperType = re.paperType.toString()
			Object.assign(form, re)
			formLoading.value = false
		}
	})

	function submitForm() {
		formRef.value
			.validate()
			.then(async () => {
				formLoading.value = true
				const re = await examPaperApi.edit(form)
				if (re) {
					emit('success')
				} else {
					message.error(re.message)
					formLoading.value = false
				}
			})
			.catch(() => {})
	}
	function addTitle() {
		form.titleItems.push({ name: '', questionItems: [] })
	}
	function addQuestion(titleItem) {
		currentTitleItem.value = titleItem
		questionPage.multipleSelection = []
		questionPage.showDialog = true
		search()
	}
	function removeTitleItem(index) {
		form.titleItems.splice(index, 1)
	}
	function removeQuestion(titleItem, questionIndex) {
		titleItem.questionItems.splice(questionIndex, 1)
	}
	function queryForm() {
		questionPage.queryParam.pageIndex = 1
		search()
	}
	function confirmQuestionSelect() {
		Promise.all(questionPage.multipleSelection.map((q) => questionApi.select(q.id))).then((resArr) => {
			resArr.forEach((re) => {
				currentTitleItem.value.questionItems.push(re)
			})
			questionPage.showDialog = false
		})
	}
	function levelChange() {
		form.subjectId = null
		subjectFilter.value = subjects.value.filter((data) => data.level === form.level)
	}
	function search() {
		questionPage.queryParam.subjectId = form.subjectId
		questionPage.listLoading = true
		const params = {
			...questionPage.queryParam,
			size: questionPage.queryParam.pageSize,
			current: questionPage.queryParam.pageIndex
		}
		questionApi.pageList(params).then((data) => {
			const re = data
			questionPage.tableData = re.records
			questionPage.total = re.total
			questionPage.queryParam.pageIndex = re.current
			questionPage.listLoading = false
		})
	}
	function onPageChange(page) {
		questionPage.queryParam.pageIndex = page
		search()
	}
	// 获取所有已选题目的ID
	const allSelectedQuestionIds = computed(() => {
		const ids = []
		form.titleItems.forEach((titleItem) => {
			titleItem.questionItems.forEach((question) => {
				ids.push(question.id)
			})
		})
		return ids
	})

	const rowSelection = {
		selectedRowKeys: computed(() => questionPage.multipleSelection.map((q) => q.id)),
		onChange: (selectedRowKeys, selectedRows) => {
			questionPage.multipleSelection = selectedRows
		},
		getCheckboxProps: (record) => ({
			disabled: allSelectedQuestionIds.value.includes(record.id),
			title: allSelectedQuestionIds.value.includes(record.id) ? '该题目已被选择' : ''
		})
	}
	const handPaperTypeChange = (paperType) => {
		if (['2', '3'].includes(paperType)) {
			questionPage.queryParam.bankType = '1'
		}
		if ('5' === paperType) {
			questionPage.queryParam.bankType = '2'
		}
		if ('6' === paperType) {
			questionPage.queryParam.bankType = '3'
		}
	}
	function questionTypeFormatter({ text }) {
		return examStore.enumFormat(questionTypeEnum.value, text)
	}
	function resetForm() {
		const lastId = form.id
		Object.assign(form, {
			id: null,
			// level: null,
			// subjectId: null,
			paperType: null,
			limitDateTime: [],
			name: '',
			suggestTime: null,
			titleItems: []
		})
		form.id = lastId
	}
	const askCancel=()=>{
		questionPage.queryParam.id = ""
		questionPage.queryParam.questionType =""
		questionPage.showDialog = false
	}
</script>

<style lang="less" scoped>
	.app-container {
		padding: 24px;
	}
	.exampaper-item-box {
		margin-top: 12px;
		padding-right: 20px;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		.q-title {
			margin: 0 5px;
		}
	}
</style>
