<template>
	<pi-dialog :title="titleMap[mode]" v-model="visible" :width="1000" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" showFullscreen>
		<el-form :model="form" :rules="rules" :disabled="mode==='show'" ref="formRef" label-width="100px">
			<el-form-item label="标题" prop="title">
				<el-input type="text" v-model="form.title" placeholder="请输入标题" clearable></el-input>
			</el-form-item>
			<el-form-item label="内容" prop="content">
				<pi-editor v-model="form.content" placeholder="请输入内容"></pi-editor>
			</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>
	</pi-dialog>
</template>

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

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({
	message_id: null,
	title: null,
	content: null
})
const rules = ref({
})

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.message_id? await api.system.message.edit(form.value) : await api.system.message.add(form.value);
	isSaveing.value = false;
	emit('success')
	visible.value = false;
	proxy.$message.success(res.msg)
}
</script>
