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

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

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  disable: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'content-change'])

const editorRef = shallowRef<IDomEditor>()
const valueHtml = ref(props.modelValue)
const mode = 'default'

const toolbarConfig = {
  excludeKeys: [
    'insertVideo',
    'uploadVideo',
    'codeBlock',
    '|',
    'group-more-style'
  ]
}

const editorConfig = {
  placeholder: '请输入内容...',
  readOnly: props.disable,
  MENU_CONF: {
    uploadImage: {
      allowedFileTypes: ['image/*'],
      async customUpload(file: File, insertFn: (url: string) => void) {
        try {
          const formData = new FormData()
          formData.append('biz', 'richText')
          formData.append('file', file)
          formData.append('new', '1')
          formData.append('Ctrl', 'upload')

          const res: any = await myAxios.post('/file/upload', formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
          })

          if (res.code === 1) {
            // 拼接完整 URL 地址再插入到富文本中
            const imageUrl = 'http://27.30.77.229:9092/file/download/' + res.data
            insertFn(imageUrl)
          } else {
            console.error('上传失败:', res.message)
          }
        } catch (error) {
          console.error('图片上传失败', error)
        }
      }
    }
  }


}

const handleFocus = () => {
  editorRef.value?.restoreSelection()
}

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

  editor.on('menuClick', (menu: { key: string }) => { // ✅ 显式类型声明
    if (menu.key === 'headerSelect') {
      nextTick(() => {
        editor.restoreSelection()
        editor.focus()
      })
    }
  })
}

watch(() => props.modelValue, (newVal) => {
  if (newVal !== valueHtml.value && editorRef.value?.isEmpty()) {
    valueHtml.value = newVal
  }
}, { immediate: true })

watch(valueHtml, (newVal) => {
  emit('update:modelValue', newVal)
  emit('content-change', newVal)
})

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
  }
})
</script>

<style scoped>
.editor-container {
  border-radius: 0.75rem;
  overflow: hidden;
  height: 100vh;
}
.toolbar {
  border-bottom: 1px solid #e2e8f0 !important;
}
</style>