<template>
	<el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable width="800px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" label-width="100px" :validate-on-rule-change="false" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="班级" prop="classCode">
						<el-select v-model="form.classCode" placeholder="请选择班级" clearable filterable style="width: 100%" @change="handleClassChange">
							<el-option v-for="item in classList" :key="item.classCode" :label="item.classNo" :value="item.classCode"> </el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="考核项目" prop="assessmentCategory">
						<el-select v-model="form.assessmentCategory" placeholder="请选择考核项目" clearable filterable style="width: 100%">
							<el-option v-for="item in assessmentCategoryList" :key="item.id" :label="item.category" :value="item.id"> </el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="考核指标" prop="assessmentPoint">
						<el-select v-model="form.assessmentPoint" placeholder="请选择考核指标" clearable filterable style="width: 100%">
							<el-option v-for="item in assessmentPointList" :key="item.id" :label="item.pointName" :value="item.id"> </el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="类型" prop="type">
						<el-select v-model="form.type" placeholder="请选择类型" clearable style="width: 100%">
							<el-option label="加分" value="1" />
							<el-option label="减分" value="2" />
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="分数" prop="score">
						<el-input-number v-model="form.score" :precision="0" :step="1" :min="0" placeholder="请输入分数" style="width: 100%" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="考核日期" prop="recordDate">
						<el-date-picker
							v-model="form.recordDate"
							type="date"
							placeholder="选择考核日期"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>

				<el-col :span="24" class="mb20">
					<el-form-item label="情况说明" prop="remarks">
						<el-input v-model="form.remarks" type="textarea" :rows="4" placeholder="请输入情况说明" maxlength="500" show-word-limit />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取 消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ClassMasterEvaluationDialog">
import { ref, reactive, nextTick, onMounted } from 'vue';
import { useMessage } from '/@/hooks/message';
import { getObj, addObj, putObj } from '/@/api/stuwork/classmasterevaluation';
import { getClassListByRole } from '/@/api/basic/basicclass';
import { getList as getAssessmentCategoryList } from '/@/api/stuwork/assessmentcategory';
import { getList as getAssessmentPointList } from '/@/api/stuwork/assessmentpoint';

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const classList = ref<any[]>([]);
const assessmentCategoryList = ref<any[]>([]);
const assessmentPointList = ref<any[]>([]);

// 提交表单数据
const form = reactive({
	id: '',
	classCode: '',
	assessmentCategory: '',
	assessmentPoint: '',
	type: '',
	score: 0,
	recordDate: '',
	remarks: '',
});

// 定义校验规则
const dataRules = ref({
	classCode: [{ required: true, message: '班级不能为空', trigger: 'change' }],
	assessmentCategory: [{ required: true, message: '考核项目不能为空', trigger: 'blur' }],
	assessmentPoint: [{ required: true, message: '考核指标不能为空', trigger: 'blur' }],
	type: [{ required: true, message: '类型不能为空', trigger: 'change' }],
	score: [{ required: true, message: '分数不能为空', trigger: 'blur' }],
	recordDate: [{ required: true, message: '考核日期不能为空', trigger: 'blur' }],
});

// 班级选择变化
const handleClassChange = () => {
	// 可以在这里添加其他逻辑
};

// 打开弹窗
const openDialog = async (id?: string) => {
	visible.value = true;

	// 重置表单数据
	Object.assign(form, {
		id: '',
		classCode: '',
		assessmentCategory: '',
		assessmentPoint: '',
		type: '',
		score: 0,
		recordDate: '',
		remarks: '',
	});

	// 清除表单验证状态，不触发验证
	nextTick(() => {
		dataFormRef.value?.clearValidate();
		dataFormRef.value?.resetFields();
	});

	// 获取详情
	if (id) {
		form.id = id;
		getClassMasterEvaluationData(id);
	}
	// 新增时，确保验证状态已清除
	nextTick(() => {
		dataFormRef.value?.clearValidate();
	});
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		form.id ? await putObj(form) : await addObj(form);
		useMessage().success(form.id ? '修改成功' : '添加成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg || '操作失败');
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getClassMasterEvaluationData = (id: string) => {
	loading.value = true;
	getObj({ id: id })
		.then((res: any) => {
			if (res.data) {
				// 处理返回数据，可能是对象或数组
				const data = Array.isArray(res.data) ? res.data[0] : res.data;
				if (data) {
					Object.assign(form, {
						id: data.id || '',
						classCode: data.classCode || '',
						assessmentCategory: data.assessmentCategory || '',
						assessmentPoint: data.assessmentPoint || '',
						type: data.type || '',
						score: data.score || 0,
						recordDate: data.recordDate || '',
						remarks: data.remarks || '',
					});
				}
			}
		})
		.catch((err: any) => {
			useMessage().error('获取详情失败');
		})
		.finally(() => {
			loading.value = false;
			// 数据加载完成后，清除验证状态，避免触发验证
			nextTick(() => {
				dataFormRef.value?.clearValidate();
			});
		});
};

// 获取班号列表
const getClassListData = async () => {
	try {
		const res = await getClassListByRole();
		if (res.data) {
			classList.value = Array.isArray(res.data) ? res.data : [];
		}
	} catch (err) {
		classList.value = [];
	}
};

// 获取考核项目列表
const getAssessmentCategoryListData = async () => {
	try {
		const res = await getAssessmentCategoryList();
		if (res.data) {
			assessmentCategoryList.value = Array.isArray(res.data) ? res.data : [];
		}
	} catch (err) {
		assessmentCategoryList.value = [];
	}
};

// 获取考核指标列表
const getAssessmentPointListData = async () => {
	try {
		const res = await getAssessmentPointList();
		if (res.data) {
			assessmentPointList.value = Array.isArray(res.data) ? res.data : [];
		}
	} catch (err) {
		assessmentPointList.value = [];
	}
};

// 初始化
onMounted(() => {
	getClassListData();
	getAssessmentCategoryListData();
	getAssessmentPointListData();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
