<template>
	<div class="subject-form-container">
		<a-form ref="formRef" :model="form" :rules="rules" layout="vertical" v-loading="formLoading">
			<a-form-item label="学科" name="name" :rules="rules.name" required>
				<a-input v-model:value="form.name" placeholder="请输入学科名称" allow-clear />
			</a-form-item>
			<a-form-item label="年级" name="level" :rules="rules.level" required>
				<a-select v-model:value="form.level" placeholder="请选择年级">
					<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>
				<a-button type="primary" @click="submitForm" :loading="formLoading">提交</a-button>
				<a-button style="margin-left: 8px" @click="resetForm">重置</a-button>
			</a-form-item>
		</a-form>
	</div>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { message } from 'ant-design-vue'
	import subjectApi from '@/api/exam/paper/subject.js'
	import { useExamStore } from '@/store/exam.js'

	const examStore = useExamStore()
	const levelEnum = examStore.levelEnum
	const enumFormat = examStore.enumFormat
	const emit = defineEmits(['success'])
	const props = defineProps({
		id: {
			type: Number,
			default: null
		}
	})
	const formRef = ref()
	const form = reactive({
		id: null,
		name: '',
		level: 1,
		levelName: ''
	})
	const formLoading = ref(false)
	const rules = {
		name: [{ required: true, message: '请输入学科名称', trigger: 'blur' }],
		level: [{ required: true, message: '请选择年级', trigger: 'change' }]
	}

	// 初始化：编辑时获取详情
	onMounted(async () => {
		const id = props.id
		if (id && parseInt(id) !== 0) {
			formLoading.value = true
			try {
				const res = await subjectApi.select(id)
				if (res) {
					Object.assign(form, res)
				}
			} finally {
				formLoading.value = false
			}
		}
	})

	const submitForm = () => {
		formRef.value.validate().then(async () => {
			formLoading.value = true
			form.levelName = enumFormat(levelEnum, form.level)
			try {
				const data = await subjectApi.edit(form)
				emit('success')
			} catch (e) {
				// 网络异常等
				message.error('提交失败')
			} finally {
				formLoading.value = false
			}
		})
	}

	const resetForm = () => {
		const lastId = form.id
		formRef.value.resetFields()
		form.id = lastId
		form.name = ''
		form.level = 1
		form.levelName = ''
	}
</script>

<style lang="less" scoped>
	.subject-form-container {
		max-width: 480px;
		margin: 40px auto;
	}
</style>
