<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="pid">
				<tree-select v-model="form.pid" :apiObj="$API.system.dept" disabled isDept check-strictly placeholder="顶级组织"></tree-select>
			</el-form-item>
			<el-form-item label="组织名称:" prop="name">
				<el-input v-model="form.name" placeholder="请输入组织名称"></el-input>
			</el-form-item>
			<el-form-item label="组织编码:" prop="code">
				<el-input v-model="form.code" placeholder="请输入组织编码"></el-input>
			</el-form-item>
			<el-form-item label="排序:" prop="deptSort">
				<el-input-number v-model="form.deptSort" :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: {
					pid: null,
					deptId: null,
					name: null,
					code: null,
					enabled: true,
					deptSort: 999
				},
				rules: {
					pid: [{ required: true, validator: (rule, value, callback) => callback() }],
					name: [{ required: true, message: "请输入组织名称" }],
					code: [{ required: true, message: "请输入组织编码" }],
					deptSort: [{ required: true, message: "请输入组织排序" }]
				}
			}
		},

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

			// 表单注入数据
			setData(data) {
				this.form.pid = data.pid || null;
				this.form.deptId = data.deptId || null;
				this.form.name = data.name || null;
				this.form.code = data.code || null;
				this.form.deptSort = data.deptSort || 999;
			},
			
			// 表单提交方法
			submit() {
				this.$refs.dialogForm.validate(valid => {
					if (valid) {
						this.isSaveing = true;
						this.$API.system.dept[this.mode](this.form).then(res => {
							this.isSaveing = false;
							this.$message.success("操作成功");
							this.visible = false;
							this.$emit("success", res);
						}).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>