<template>
  <div style="border: 1px solid #ccc; width: 600px">
    <Toolbar
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="valueHtml"
      :default-config="editorConfig"
      :mode="mode"
      style="height: 400px; overflow-y: hidden"
      @on-created="handleCreated"
      @mouseout="mouseout"
    />
  </div>
</template>

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

const emits = defineEmits(['change'])

const valueHtml = ref('')
const mode = 'default'
const editorRef = shallowRef()
const flag = ref(true)
const imgList = ref([] as string[])
const videoList = ref([] as string[])

const toolbarConfig = {
  // 去除不需要的工具
  excludeKeys: ['fullScreen']
}

const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      fieldName: 'File',
      server:
        '/K3Cloud/LQKJ.K3.NSJYBSystem.WebApi.WebApiEditService.UpdateFile,LQKJ.K3.NSJYBSystem.WebApi.common.kdsvc',
      meta: {
        Type: 0
      },
      // 上传之前触发
      onBeforeUpload(file: File) {
        console.log(file)
        return file
      },
      // 上传进度的回调函数
      onProgress(progress: number) {
        console.log('progress', progress)
      },
      // 单个文件上传成功之后
      onSuccess(file: File, res: any) {
        if (res.errno === 0) {
          const parts = res.data.url.split('/')
          if (parts.length) {
            const filename = parts[parts.length - 1].split('.')[0]
            if (filename) imgList.value.push(filename)
            console.log(`${file.name} 上传成功`, res, imgList.value)
          }
        }
      },
      // 单个文件上传失败
      onFailed(file: File, res: any) {
        console.log(`${file.name} 上传失败`, res)
      },
      // 上传错误，或者触发 timeout 超时
      onError(file: File, err: any, res: any) {
        console.log(`${file.name} 上传出错`, err, res)
      }
    },
    uploadVideo: {
      fieldName: 'File',
      server:
        '/K3Cloud/LQKJ.K3.NSJYBSystem.WebApi.WebApiEditService.UpdateFile,LQKJ.K3.NSJYBSystem.WebApi.common.kdsvc',
      meta: {
        Type: 1
      },
      // 上传之前触发
      onBeforeUpload(file: File) {
        return file
      },
      // 上传进度的回调函数
      // onProgress(progress: number) {
      //   console.log('progress', progress)
      // },
      // 单个文件上传成功之后
      onSuccess(file: File, res: any) {
        if (res.errno === 0) {
          const parts = res.data.url.split('/')
          if (parts.length) {
            const filename = parts[parts.length - 1].split('.')[0]
            if (filename) videoList.value.push(filename)
            console.log(`${file.name} 上传成功`, res, videoList.value)
          }
        }
      },
      // 单个文件上传失败
      onFailed(file: File, res: any) {
        console.log(`${file.name} 上传失败`, res)
      },
      // 上传错误，或者触发 timeout 超时
      onError(file: File, err: any, res: any) {
        console.log(`${file.name} 上传出错`, err, res)
      }
    }
  }
}

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

// 编辑器回调函数
const handleCreated = (editor: any) => {
  editorRef.value = editor
}

const mouseout = () => {
  if (!flag.value || valueHtml.value === '<p><br></p>') return
  // console.log('change', valueHtml.value)
  // 存储当前的文件名数组
  let newList = [] as string[]
  // 要删除的文件名数组
  let delList = [] as string[]
  editorRef.value.getElemsByType('image').map((item: any) => {
    const parts = item.src.split('/')
    if (parts.length) {
      const filename = parts[parts.length - 1].split('.')[0]
      if (filename) newList.push(filename)
    }
  })
  editorRef.value.getElemsByType('video').map((item: any) => {
    const parts = item.src.split('/')
    if (parts.length) {
      const filename = parts[parts.length - 1].split('.')[0]
      if (filename) newList.push(filename)
    }
  })
  // 记录的文件名数组
  let list = [...imgList.value, ...videoList.value]
  list.map((item: any) => {
    if (!newList.includes(item)) delList.push(item)
  })
  flag.value = false
  emits('change', valueHtml.value, delList)
}

const init = (html: string) => {
  valueHtml.value = html
  editorRef.value.getElemsByType('image').map((item: any) => {
    const parts = item.src.split('/')
    if (parts.length) {
      const filename = parts[parts.length - 1].split('.')[0]
      imgList.value.push(filename)
    }
  })
  editorRef.value.getElemsByType('video').map((item: any) => {
    const parts = item.src.split('/')
    if (parts.length) {
      const filename = parts[parts.length - 1].split('.')[0]
      videoList.value.push(filename)
    }
  })
}

defineExpose({
  flag,
  init
})
</script>

<style lang="scss" scoped>
:deep(video) {
  width: 100%;
}
</style>
