<template>
  <div class="vab-editor-container" :class="{ 'is-disabled': disabled }">
    <Toolbar
      class="editor-toolbar"
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="editor-content"
      :style="{ height: height, overflowY: 'hidden' }"
      v-model="valueHtml"
      :default-config="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>

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

defineOptions({
  name: 'VabEditor',
})

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  mode: {
    type: String,
    default: 'default', // or 'simple'
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
  height: {
    type: String,
    default: '400px',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
})

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

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<IDomEditor>()

// 内容 HTML
const valueHtml = ref('')

// Watch props to update content if changed externally
watch(
  () => props.modelValue,
  (val) => {
    if (val !== valueHtml.value) {
      valueHtml.value = val
    }
  },
  { immediate: true }
)

watch(
  () => props.disabled,
  (val) => {
    const editor = editorRef.value
    if (editor == null) return
    val ? editor.disable() : editor.enable()
  }
)

const toolbarConfig: Partial<IToolbarConfig> = {}
const editorConfig: Partial<IEditorConfig> = {
  placeholder: props.placeholder,
  readOnly: props.disabled,
  MENU_CONF: {
    uploadImage: {
        // mock upload
        customUpload(file: File, insertFn: any) {  
            // create object URL for local preview
            const url = URL.createObjectURL(file)
            insertFn(url, file.name, url)
        }
    }
  }
}

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

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例
}

const handleChange = (editor: any) => {
  const html = editor.getHtml()
  emit('update:modelValue', html)
  emit('change', html)
}

defineExpose({
    editorRef
})
</script>

<style lang="scss" scoped>
.vab-editor-container {
  border: 1px solid #ccc;
  
  &.is-disabled {
    opacity: 0.6;
    cursor: not-allowed;
    :deep(.w-e-text-container) {
        background-color: #f5f7fa;
    }
  }

  .editor-toolbar {
    border-bottom: 1px solid #ccc;
  }
  
  .editor-content {
    overflow-y: hidden;
  }
}
</style>
