<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="formRef" label-width="100px">
			<el-form-item label="字典名称" prop="dict_name">
				<el-input type="text" v-model="form.dict_name" placeholder="请输入字典名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="字典类型" prop="dict_type">
				<el-input type="text" v-model="form.dict_type" placeholder="请输入字典类型" clearable></el-input>
			</el-form-item>
			<el-form-item label="备注" prop="remark">
				<el-input type="textarea" :rows="3" v-model="form.remark" placeholder="请输入备注" clearable></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">取 消</el-button>
			<el-button v-if="mode!=='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import {getCurrentInstance, ref} from 'vue'
import api from "@/api/index"

defineExpose({
	open
})
const emit = defineEmits(['success', 'closed'])
const formRef = ref(null)
const {proxy} = getCurrentInstance()

let mode = ref('add')
let titleMap = ref({
	add: '新增',
	edit: '编辑',
	show: '查看'
})
let visible = ref(false)
let isSaveing = ref(false)
let form = ref({
	dict_id: null,
	dict_name: null,
	dict_type: null,
	remark: null
})
const rules = ref({
	dict_name: [
		{required: true, message: '请填写字典名称'}
	],
	dict_type: [
		{required: true, message: '请填写字典类型'}
	]
})

function open(m = 'add', data = null) {
	mode.value = m
	visible.value = true
	Object.assign(form.value, data)
}

async function submit() {
	// 校验登录
	const validate = await formRef.value.validate().catch(() => {
	});
	if (!validate) {
		return false
	}
	isSaveing.value = true;
	const res = form.value.dict_id ? await api.system.dict.edit(form.value) : await api.system.dict.add(form.value);
	isSaveing.value = false;
	emit('success')
	visible.value = false;
	proxy.$message.success(res.msg)
}
</script>
