<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="330" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" ref="dialogForm" label-width="80px" label-position="left">
			<el-form-item label="编码" prop="name">
				<el-input v-model="form.name" clearable placeholder="字典编码"></el-input>
			</el-form-item>
			<el-form-item label="字典名称" prop="title">
				<el-input v-model="form.title" clearable placeholder="字典显示名称"></el-input>
			</el-form-item>
			<el-form-item label="父路径" prop="parent_id">
				<el-cascader v-model="form.parent_id" :options="dic" :props="dicProps" :show-all-levels="false" clearable></el-cascader>
			</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>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增字典分类',
					edit: '编辑字典分类'
				},
				visible: false,
				isSaveing: false,
				form: {
					id:"",
					title: "",
					name: "",
					parent_id: ""
				},
				rules: {
					name: [
						{required: true, message: '请输入编码'}
					],
					title: [
						{required: true, message: '请输入字典名称'}
					]
				},
				dic: [],
				dicProps: {
					value: "id",
					label: "name",
					emitPath: false,
					checkStrictly: true
				}
			}
		},
		mounted() {
			this.getDic()
		},
		methods: {
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this;
			},
			//获取字典列表
			async getDic(){
				var res = await this.$API.system.dictionary.category.get({is_tree: 1});
				this.dic = res.data;
			},
			//表单提交方法
			submit(){
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;
						var res = {};
						this.form.parent_id = this.form.parent_id ? this.form.parent_id : 0;
						if(this.mode == 'add'){
							res = await this.$API.system.dictionary.addcate.post(this.form);
						}else{
							res = await this.$API.system.dictionary.editcate.post(this.form);
						}

						this.isSaveing = false;
						if(res.code == 1){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						}else{
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}
				})
			},
			//表单注入数据
			setData(data){
				this.form.id = data.id
				this.form.title = data.title
				this.form.name = data.name
				this.form.parent_id = data.parent_id
			}
		}
	}
</script>

<style>
</style>
