<template>
  <div class="rich-text-editor">
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      class="toolbar"
    />
    <Editor
      :defaultConfig="editorConfig"
      :mode="mode"
      v-model="valueHtml"
      class="editor"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, watch, onBeforeUnmount } from "vue"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import type { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor"
import { uploadFile } from "@/api/upload"
import "@wangeditor/editor/dist/css/style.css"

const props = defineProps<{
  modelValue: string
  placeholder?: string
  height?: number
}>()

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

// 编辑器实例
const editorRef = shallowRef<IDomEditor | null>(null)
const valueHtml = ref(props.modelValue || "")
const mode = "default"

// 监听外部值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== valueHtml.value) {
      valueHtml.value = newVal || ""
    }
  }
)

// 监听内部值变化，触发更新
watch(valueHtml, (newVal) => {
  emit("update:modelValue", newVal)
})

// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: [
    "group-video", // 排除视频
    "fullScreen", // 排除全屏
  ],
}

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.placeholder || "请输入内容...",
  MENU_CONF: {
    // 上传图片配置
    uploadImage: {
      async customUpload(file: File, insertFn: (url: string) => void) {
        try {
          const result: any = await uploadFile(file)
          const url = result.data?.url || result.url
          if (url) {
            insertFn(url)
          }
        } catch (error) {
          console.error("图片上传失败:", error)
        }
      },
    },
  },
}

// 编辑器创建完成
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
}

// 组件销毁时，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor) {
    editor.destroy()
  }
})
</script>

<style scoped>
.rich-text-editor {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.toolbar {
  border-bottom: 1px solid #d9d9d9;
}

.editor {
  height: v-bind('(props.height || 300) + "px"');
  overflow-y: auto;
}

.rich-text-editor :deep(.w-e-text-container) {
  background-color: #fff;
}

.rich-text-editor :deep(.w-e-toolbar) {
  background-color: #fafafa;
}
</style>
