<script setup lang="ts">
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

import '@wangeditor/editor/dist/css/style.css'
// 引入 css
defineOptions({ name: 'MjEditor' })
// 属性
const props = defineProps<{
  disabled?: any
  modelValue: any
}>()

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

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

const value = computed({
  get: () => props.modelValue || '',
  set: (val) => emit('update:modelValue', val || ''),
})

const mode = 'simple'

const toolbarConfig = {
  insertKeys: {
    index: 0,
    keys: [
      'insertFormula', // “插入公式”菜单
      'editFormula', // “编辑公式”菜单
    ],
  },
}
const editorConfig = {
  placeholder: '请输入内容...', // 选中公式时的悬浮菜单
  autoFocus: false,
  hoverbarKeys: {
    formula: {
      menuKeys: ['editFormula'], // “编辑公式”菜单
    },
  },
  readOnly: props.disabled,
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  editorRef.value?.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value?.destroy()
  editorRef.value = editor // 记录 editor 实例，重要！
}

defineExpose({
  isBlank() {
    let s = (value.value as string) || ''
    s = s.replaceAll('<br>', '')
    s = s.replaceAll('&nbsp;', '')
    s = s.replaceAll(' ', '')
    s = s.replaceAll('<p></p>', '')
    return s.length === 0
  },
})
</script>

<template>
  <div class="mj-editor">
    <Toolbar
      :editor="editorRef"
      style="border-bottom: 1px solid #ddd"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="value"
      :default-config="editorConfig"
      :mode="mode"
      @on-created="handleCreated"
    />
  </div>
</template>

<style lang="scss">
.w-e-text-container {
  u {
    display: inline-flex;
    justify-content: center;
    min-width: 20px;
    padding: 0 16px;
    margin: 0 10px;
    text-indent: 0;
    text-decoration: none;
    border-bottom: 1px solid #00f;
  }
}
</style>

<style lang="scss" scoped>
.mj-editor {
  border: 1px solid #ccc;

  &.w-e-full-screen-container {
    z-index: 500;
  }
}
</style>
