addLevel.vue 11.4 KB
<template>
    <!-- ... existing code ... -->
    <div class="grade-editor">
        <el-button :disabled="status == 2 || status == 1"
                   icon="el-icon-plus"
                   plain
                   @click="addLevel">
            添加等级
        </el-button>
        <el-form ref="levelForm"
                 class="grade-form"
                 :model="formModel">
            <el-table border
                      :data="levels"
                      size="mini"
                      style="width: 100%; margin-top: 8px">
                <el-table-column align="center"
                                 label="序号"
                                 width="60">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>

                <el-table-column align="center"
                                 label="等级分数段"
                                 min-width="373">
                    <template #default="scope">
                        <el-input disabled
                                  style="width: 140px"
                                  :value="scope.row.minScore" />
                        <span class="between">≤ 分数 ≤</span>
                        <!-- 包裹最大值为表单项,动态校验:正整数、> 最小值、≤ 999 -->
                        <el-form-item :prop="`levels.${scope.$index}.maxScore`"
                                      :rules="[
                                          {
                                              validator: maxValidatorFactory(scope.$index),
                                              trigger: ['blur'],
                                          },
                                      ]">
                            <el-input v-model="levels[scope.$index].maxScore"
                                      :disabled="status == 2 || status == 1"
                                      placeholder="请输入"
                                      style="width: 140px"
                                      @input="onMaxInput(scope.$index, $event)" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <el-table-column align="center"
                                 label="等级名称"
                                 min-width="373">
                    <template #default="scope">
                        <el-form-item :prop="`levels.${scope.$index}.levelName`"
                                      :rules="nameRules">
                            <el-input v-model="levels[scope.$index].levelName"
                                      :disabled="status == 2 || status == 1"
                                      maxlength="10"
                                      placeholder="请输入"
                                      @input="onNameInput(scope.$index, $event)" />
                        </el-form-item>
                    </template>
                </el-table-column>

                <el-table-column v-if="status == 0"
                                 align="center"
                                 label="操作"
                                 width="68">
                    <template #default="scope">
                        <el-link v-if="scope.$index !== 0"
                                 type="primary"
                                 :underline="false"
                                 @click="deleteLevel(scope.$index)">
                            删除
                        </el-link>
                        <span v-else style="color: #999"></span>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
    </div>
</template>

<script>
export default {
	props: {
		examLevel: {
			type: Array,
			default: () => [],
		},
		status: {
			type: Number | String,
			default: "",
		},
	},
	data() {
		return {
			id: this.$route.query.id,
			levels: [{ maxScore: "", minScore: 0, levelName: "" }],
			// 行内错误集合
			errors: [],
			formModel: { levels: [] },
			nameRules: [
				{ required: true, message: "等级名称必填", trigger: "blur" },
				{
					validator: (rule, value, cb) => {
						const name = String(value || "").trim();
						if (!name)
							return cb(new Error("等级名称必填"));
						if (name.length > 10)
							return cb(new Error("最多 10 个字符"));
						const names = (this.levels || [])
							.map(l =>
								String(l && l.levelName != null ? l.levelName : "").trim(),
							)
							.filter(n => !!n);
						const count = names.filter(n => n === name).length;
						if (count > 1) {
							return cb(new Error("等级名称不可重复"));
						}
						cb();
					},
					trigger: ["blur", "change"],
				},
			],
		};
	},
	watch: {
		// levels 任何变动时,重算错误并修正连续性
		levels: {
			deep: true,
			handler() {
				this.computeErrors();
			},
		},
		examLevel: {
			deep: true,
			immediate: true,
			handler(val) {
				if (this.id || this.id === 0) {
					this.levels = val;
					this.formModel.levels = this.levels;
					this.computeErrors();
				}
			},
		},
	},
	created() {
		this.formModel.levels = this.levels;
		this.computeErrors();
	},
	methods: {
		// 添加等级:最小值 = 上一行最大值 + 1,且不可编辑
		addLevel() {
			if (this.levels.length == 6) {
				this.$message.error("最多添加6个等级");
				return;
			}
			if (this.status == 2)
				return;
			const last = this.levels[this.levels.length - 1];
			const lastMax = this.toInt(last.maxScore);
			if (!this.isValidMax(lastMax, last.minScore)) {
				this.$message.warning(
					"请先填写上一行的最大值(正整数且 > 最小值,≤ 999)",
				);
				return;
			}
			const nextMin = lastMax + 1;
			if (nextMin > 999) {
				this.$message.warning("已达到最大分数 999,不能继续添加");
				return;
			}
			this.levels.push({ minScore: nextMin, maxScore: "", levelName: "" });
		},

		// 删除等级(第一行不可删)
		deleteLevel(index) {
			if (index === 0)
				return;
			this.levels.splice(index, 1);
			this.recomputeMins();
		},

		// 最大值输入:仅正整数、自动纠偏(≥ 最小值 且 ≤ 999)
		onMaxInput(index, val) {
			const row = this.levels[index];
			const minScore = Number(row.minScore) || 0;

			// 规范化:只保留数字字符
			let s = String(val == null ? "" : val).replace(/\D/g, "");

			// 长度限制:最多 3 位(上限 999)
			if (s.length > 3)
				s = s.slice(0, 3);

			// 更新可见值
			row.maxScore = s;

			// 空输入:不联动
			if (!s)
				return;

			const n = Number(s);
			if (!Number.isFinite(n))
				return;

			// 上限处理:> 999 时直接卡到 999 并联动
			if (n > 999) {
				row.maxScore = "999";
				this.recomputeMins();
				return;
			}

			// 仅当有效且 n > minScore 时,联动后续最小值
			if (n > minScore) {
				this.recomputeMins();
			}
			// n <= minScore 的中间态(如 1、12 相对 minScore=71):允许存在,不清空、不联动
		},

		// 等级名称:最多 10 个字符
		onNameInput(index, val) {
			const row = this.levels[index];
			const levelName = String(val || "").slice(0, 10);
			this.$set(this.levels, index, { ...row, levelName });
		},

		// 删除或编辑后,后续行最小值按“上一行最大值 + 1”重算
		recomputeMins() {
			for (let i = 1; i < this.levels.length; i++) {
				const prev = this.levels[i - 1];
				const prevMax = this.toInt(prev.maxScore);
				if (Number.isFinite(prevMax)) {
					this.levels[i].minScore = prevMax + 1;
					if (
						this.levels[i].maxScore !== ""
						&& Number(this.levels[i].maxScore) <= this.levels[i].minScore
					) {
						// 当前行最大值不合法:清空,让用户重新输入(避免强制等于最小值)
						this.levels[i].maxScore = "";
					}
				}
			}
		},

		// 工具:提取正整数
		toInt(val) {
			if (val === null || val === undefined)
				return Number.NaN;
			const s = String(val).trim();
			if (!s)
				return Number.NaN;
			const n = Number(s);
			if (!Number.isFinite(n))
				return Number.NaN;
			return Math.floor(Math.abs(n));
		},

		// 重算每行错误,并确保后续行最小值连续
		computeErrors() {
			const errs = [];
			for (let i = 0; i < this.levels.length; i++) {
				const row = this.levels[i];
				const err = {};

				// 校验最大值
				const maxScore = this.toInt(row.maxScore);
				if (!Number.isFinite(maxScore)) {
					err.maxScore = "请输入最大值(正整数)";
				} else if (maxScore < row.minScore) {
					err.maxScore = `最大值须 ≥ ${row.minScore}`;
				} else if (maxScore > 999) {
					err.maxScore = "最大值须 ≤ 999";
				}

				// 校验名称
				const levelName = String(row.levelName || "").trim();
				if (!levelName) {
					err.levelName = "等级名称必填";
				} else if (levelName.length > 10) {
					err.levelName = "最多 10 个字符";
				}

				// 连续性:后一行的最小值 = 当前行最大值 + 1(若能计算)
				if (Number.isFinite(maxScore) && i + 1 < this.levels.length) {
					const expectedMin = maxScore + 1;
					if (this.levels[i + 1].minScore !== expectedMin) {
						this.$set(this.levels[i + 1], "minScore", expectedMin);
					}
				}

				errs.push(err);
			}
			this.errors = errs;
		},

		// 对外校验入口:全部通过返回 true,否则提示并返回 false
		validateAll() {
			this.computeErrors();
			for (let i = 0; i < this.errors.length; i++) {
				const e = this.errors[i];
				if (e.maxScore || e.levelName) {
					this.$message.error(`第 ${i + 1} 行:${e.maxScore || e.levelName}`);
					return false;
				}
				// 强制要求每行最大值已填写
				const maxScore = this.toInt(this.levels[i].maxScore);
				if (!Number.isFinite(maxScore)) {
					this.$message.error(`第 ${i + 1} 行:请输入最大值(正整数)`);
					return false;
				}
			}
			return true;
		},

		// 校验最大值合法性
		isValidMax(maxScore, minScore) {
			return (
				Number.isFinite(maxScore) && maxScore >= minScore && maxScore <= 999
			);
		},

		// 动态生成最大值校验器(严格 > 最小值)
		maxValidatorFactory(index) {
			return (rule, value, callback) => {
				const minScore = this.levels[index].minScore;
				const n = this.toInt(value);
				if (!Number.isFinite(n))
					return callback(new Error("请输入最大值(正整数)"));
				if (n <= minScore) {
					this.levels[index].maxScore = "";
					return callback(new Error(`最大值须 > ${minScore}`));
				}
				if (n > 999)
					return callback(new Error("最大值须 ≤ 999"));
				callback();
			};
		},

		// 新增:保存入口,先跑表单校验,再跑连续性校验,成功后提交
		onSave() {
			return new Promise((resolve, reject) => {
				this.$refs.levelForm.validate((valid) => {
					resolve(valid);
				});
			});
		},
		// 输入触发尝试提交:先跑表单校验,再跑整体验证(连续性)
		onTrySubmit() {
			this.$refs.levelForm.validate((valid) => {
				if (!valid)
					return;
				if (this.validateAll()) {
					this.$emit("submit", this.levels);
				}
			});
		},
	},
};
</script>

<style scoped lang="scss">
.grade-editor {
	margin-top: 8px;
}
.between {
	display: inline-block;
	margin: 0 8px;
	color: #666;
}
::v-deep .grade-form {
	.el-form-item__error {
		position: static !important;
	}
}
::v-deep .el-button.is-disabled,
.el-button.is-disabled:focus,
.el-button.is-disabled:hover {
	color: #c0c4cc !important;
	background-color: #fff !important;
	border-color: #ebeef5 !important;
}
</style>