<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" :width="800" destroy-on-close @closed="$emit('closed')">
		<el-form :model="eForm" :rules="eRules" :disabled="mode==='show'" ref="eFormRef"
				 label-width="110" label-position="right" size="default">
			<el-form-item label="发件人名称" prop="name">
				<el-input v-model="eForm.name" type="text" style="width: 30%"/>
			</el-form-item>
			<el-form-item label="发件人邮箱" prop="username">
				<el-input v-model="eForm.username" type="text" style="width: 30%"/>
			</el-form-item>
			<el-form-item label="SMTP密码" prop="password">
				<el-input v-model="eForm.password" type="text" style="width: 30%"/>
			</el-form-item>
			<el-form-item label="SMTP服务器" prop="host">
				<el-input v-model="eForm.host" type="text" style="width: 30%"/>
			</el-form-item>
			<el-form-item label="端口" prop="port">
				<el-input v-model="eForm.port" type="text" style="width: 30%"/>
			</el-form-item>
			<el-form-item label="" prop="button_5">
				<el-button v-model="eForm.button_5" type="primary" plain>
					<template #default>
						保存
					</template>
				</el-button>
			</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 eFormRef = ref(null)
const {proxy} = getCurrentInstance()

let mode = ref('add')
let titleMap = ref({
	add: '新增',
	edit: '编辑',
	show: '查看'
})
let visible = ref(false)
let isSaveing = ref(false)
let eForm = ref({
	name: null,
	username: null,
	password: null,
	host: null,
	port: 465,
	button_5: null,

})
const eRules = ref({name: [
		{ required: true, message: '该项必填', trigger: 'blur' },
	],
	username: [
		{ required: true, message: '该项必填', trigger: 'blur' },
	],
	password: [
		{ required: true, message: '该项必填', trigger: 'blur' },
	],
	host: [
		{ required: true, message: '该项必填', trigger: 'blur' },
	],
	port: [
		{ required: true, message: '该项必填', trigger: 'blur' },
	],
})

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

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