<template>
	<div style="border: 1px solid #ccc">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
		<Editor style="height: 500px; overflow-y: hidden" v-model="modelValue" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
	</div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount, withDefaults, shallowRef, computed } from 'vue'

import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'

import { configCustomUploadImage } from './upload-image'
import { configCustomUploadVideo } from './upload-video'

interface PropsState {
	// 默认的内容信息
	value?: string
}

const props = withDefaults(defineProps<PropsState>(), {
	value: ''
})

// 编辑器实体
const editorRef = shallowRef<IDomEditor>()
// toolbar配置
const toolbarConfig: Partial<IToolbarConfig> = {}
// editor配置
const editorConfig: Partial<IEditorConfig> = {
	MENU_CONF: {
		uploadImage: configCustomUploadImage,
		uploadVideo: configCustomUploadVideo
	}
}
// 模式
const mode = ref<'default' | 'simple'>('default')

onBeforeUnmount(() => {
	const editor = editorRef.value
	if (editor == undefined) {
		return
	}
	editor.destroy()
})

const handleCreated = (editor: IDomEditor) => {
	editorRef.value = editor
}

const emit = defineEmits<{
	(e: 'update:value', content: string): void
}>()

const modelValue = computed<string>({
	get: () => props.value,
	set: value => {
		// 判断如果为p标签包含换行，默认为空
		if (value === '<p><br></p>') {
			emit('update:value', '')
			return
		}
		emit('update:value', value)
	}
})

defineExpose({
	// 获取内容
	getContent: () => modelValue.value,
	// 设置内容
	setContent: (content: string) => {
		modelValue.value = content
	},
	// 清除内容
	clear: () => editorRef.value?.clear()
})
</script>

<style src="./style.css"></style>
<style scoped></style>
