<template>
	<sc-dialog v-model="visible" :title="titleMap[mode]" :width="500" @closed="$emit('closed')">
		<el-form ref="dialogForm" :model="form" :rules="rules" label-width="90px">
			<el-form-item label="字典标签:" prop="label">
				<el-input v-model="form.label" placeholder="字典标签"></el-input>
			</el-form-item>
			<el-form-item label="字典值:" prop="value">
				<el-input v-model="form.value" placeholder="字典值"></el-input>
			</el-form-item>
			<el-form-item label="排序:" prop="dictSort">
				<el-input-number v-model="form.dictSort" :min="0" :max="999" step-strictly controls-position="right"></el-input-number>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">确 定</el-button>
		</template>
	</sc-dialog>
</template>

<script>
	export default {
		emits: ["success", "closed"],

		data() {
			return {
				mode: "add",
				titleMap: {
					add: "新增项",
					edit: "编辑项"
				},
				visible: false,
				isSaveing: false,

				form: {
					id: null,
					dict: {},
					label: null,
					value: null,
					dictSort: 999
				},
				rules: {
					label: [{ required: true, message: "请输入字典标签" }],
					value: [{ required: true, message: "请输入字典值" }],
					dictSort: [{ required: true, message: "请输入字典排序" }]
				}
			}
		},

		methods: {
			// 显示
			open(mode = "add") {
				this.mode = mode;
				this.visible = true;
				return this;
			},

			// 表单注入数据
			setData(data) {
				this.form.id = data.id || null;
				this.form.dict = Object.assign({}, data.dict);
				this.form.label = data.label || null;
				this.form.value = data.value || null;
				this.form.dictSort = data.dictSort || 999;
			},
			
			// 表单提交方法
			submit() {
				this.$refs.dialogForm.validate(valid => {
					if (valid) {
						this.isSaveing = true;
						this.$API.system.dictDetail[this.mode](this.form).then(() => {
							this.isSaveing = false;
							this.$message.success("操作成功");
							this.visible = false;
							this.$emit("success", this.mode);
						}).catch(() => this.isSaveing = false);
					} else {
						return false;
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
.el-form {
  padding: 10px 30px;
}

@media (max-width: 992px) {
  .el-form {
    padding: 10px;
  }
}
</style>