<template>
	<div >
		<Toolbar
			style="border-bottom: 1px solid #ccc"
			:editor="editorRef"
			:defaultConfig="toolbarConfig"
			:mode="mode"
		/>
		<!--		内容-->
		<Editor
			style="height: 500px; overflow-y: hidden"
			v-model="valueHtml"
			:defaultConfig="editorConfig"
			:mode="mode"
			@onCreated="handleCreated"
		/>
	</div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<InstanceType<typeof Editor> | null>(null)
const emit = defineEmits();
const state = reactive({
	path: import.meta.env.VITE_API_FRONT_BASE_URL + '/api/upload',
})
const props = defineProps({
	content: { type: String, default: '' },
});
// 内容 HTML
const valueHtml = ref<string>('')
// watch监听 更新编辑器内容
watch(
	() => props.content,
	(newContent) => {
		valueHtml.value = newContent;
		emit( "update:content",valueHtml.value)
	},
	{ immediate: true } // immediate 确保第一次渲染时就执行一次回调
);
watch(() => valueHtml.value,
	(newContent) => {
		emit( "update:content",valueHtml.value)
	},
	{ immediate: true } // immediate 确保第一次渲染时就执行一次回调
);

// 工具栏配置
const toolbarConfig = {
	toolbarKeys: [
		// 一些常用的菜单 key
		"bold", // 加粗
		"italic", // 斜体
		"through", // 删除线
		"underline", // 下划线
		"bulletedList", // 无序列表
		"numberedList", // 有序列表
		"color", // 文字颜色
		"fontSize", // 字体大小
		"lineHeight", // 行高
		"uploadImage", // 上传图片
		"delIndent", // 缩进
		"indent", // 增进
		"deleteImage", //删除图片
		"divider", // 分割线
		"justifyCenter", // 居中对齐
		"justifyJustify", // 两端对齐
		"justifyLeft", // 左对齐
		"justifyRight", // 右对齐
		"undo", // 撤销
		"redo", // 重做
		"clearStyle", // 清除格式
	],
};
// 编辑器配置
const editorConfig = {
	placeholder: '请输入内容...',
	MENU_CONF: {
		uploadImage: {
			server: state.path,
			fieldName: 'file',
			maxFileSize: 20 * 1024 * 1024, // 20MB
			allowedFileTypes: ['image/jpeg', 'image/png', 'image/gif'], // 允许的图片类型
			customInsert(res, insertFn) {
				if (res.code == 0) {
					insertFn(res.data, null, res.data);
					ElMessage.success("上传成功")
				}
			}
		},
	},
}
// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == null) return
	editor.destroy()
})

// 编辑器创建时的回调
const handleCreated = (editor: InstanceType<typeof Editor>) => {
	editorRef.value = editor
}

// 模式：default 或 simple
const mode = 'default'
</script>
