<template>
  <div style="border: 1px solid #ccc; z-index: 9999">
    <Toolbar
      class="editor_toolbar"
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="html"
      style="height: 300px; overflow-y: hidden"
      :default-config="editorConfig"
      :mode="mode"
      @on-created="onCreated"
    />
  </div>
</template>
<script setup lang="ts">
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { computed, onBeforeUnmount, ref, shallowRef } from 'vue'
import { uploadImg } from '@/utils/file'
const props = defineProps({
  modelValue: String,
  placeholder: {
    type: String,
    default: '',
  },
  isInsert: {
    type: Boolean,
    default: false,
  },
  insertData: {
    type: Array,
    default: () => [
      {
        label: '客户名称',
        value: '{payerName} {payerSurname}',
      },
      { label: '订单编号', value: '{id}' },
      { label: '店铺单号', value: '{shopNumber}' },
      { label: '商品名称', value: '{productName}' },
      { label: '商品规格', value: '{productSpec}' },
      { label: '商品数量', value: '{productQuantity}' },
      { label: '商品单价', value: '{productPrice}' },
    ],
  },
})

const emit = defineEmits(['update:modelValue'])
const html = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  },
})
const editorRef = shallowRef()
const toolbarConfig = computed(() => {
  return {
    excludeKeys: ['group-video'],
  }
})
const editorConfig = computed(() => {
  return {
    placeholder: props.placeholder,
    MENU_CONF: {
      uploadImage: {
        allowedFileTypes: ['jpg', 'jpeg', 'png', 'gif', 'bmp'],
        async customUpload(files: File, insertFn: (url: string) => void) {
          // JS 语法
          // res 即服务端的返回结果

          const res = await uploadImg(files, {
            url: 'upload/ossUpload',
            businessType: 'product',
          })

          const url = res.imagePath || res.filePath
          // 从 res 中找到 url alt href ，然后插入图片
          if (url) insertFn(url)
        },
      },
      insertSelect: { options: props.insertData },
    },
  }
})
const mode = ref('default')
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const onCreated = (editor: any) => {
  console.log(editor)
  editorRef.value = editor
}
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return

  editor.destroy()
})
</script>
<style scoped>
.editor_toolbar::v-deep .panel_menu li:hover {
  background: #efefef;
}
</style>
