<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="name">
				<el-input v-model="form.name" placeholder="角色名称"></el-input>
			</el-form-item>
			<el-form-item label="角色级别:" prop="level">
				<el-input-number v-model="form.level" :min="1" step-strictly controls-position="right" placeholder="1"></el-input-number>
			</el-form-item>
			<el-form-item label="描述信息:" prop="description">
				<el-input v-model="form.description" type="textarea" :rows="4" clearable placeholder="角色描述"></el-input>
			</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,
					name: null,
					level: 1,
					description: null
				},
				rules: {
					name: [{ required: true, message: "请输入角色名称" }],
					level: [{ required: true, message: "请选择角色级别" }],
					description: [{ message: "请输入角色描述信息" }]
				}
			}
		},

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

			// 表单注入数据
			setData(data) {
				this.form.id = data.id || null;
				this.form.name = data.name || null;
				this.form.level = data.level || 1;
				this.form.description = data.description || null;
			},
			
			// 表单提交方法
			submit() {
				this.$refs.dialogForm.validate(valid => {
					if (valid) {
						this.isSaveing = true;
						this.$API.system.role[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>