<script setup lang="ts">
import { onBeforeUnmount, computed, PropType, unref, nextTick, ref, watch, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor, IEditorConfig, i18nChangeLanguage } from '@wangeditor/editor'
import { propTypes } from '@/utils/propTypes'
import { isNumber } from '@/utils/is'
import { ElMessage } from 'element-plus'
import { useLocaleStore } from '@/store/modules/locale'
import { REQUEST_BASE } from '@/constants'
import { useUserStoreWithOut } from '@/store/modules/user'
const userStore = useUserStoreWithOut()
const localeStore = useLocaleStore()

const currentLocale = computed(() => localeStore.getCurrentLocale)

i18nChangeLanguage(unref(currentLocale).lang)

const props = defineProps({
  editorId: propTypes.string.def('wangeEditor-1'),
  height: propTypes.oneOfType([Number, String]).def('500px'),
  editorConfig: {
    type: Object as PropType<IEditorConfig>,
    default: () => undefined
  },
  modelValue: propTypes.string.def('')
})

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

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

const valueHtml = ref('')

watch(
  () => props.modelValue,
  (val: string) => {
    if (val === unref(valueHtml)) return
    valueHtml.value = val
  }
)

// 监听
watch(
  () => valueHtml.value,
  (val: string) => {
    emit('update:modelValue', val)
  }
)

const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor
  valueHtml.value = props.modelValue
}
const toolbarConfig = {
  excludeKeys: ['group-video']
}
const loading = ref(false)
const loadingText = ref('上传中')
// 编辑器配置
const editorConfig = computed((): IEditorConfig => {
  return Object.assign(
    {
      MENU_CONF: {
        uploadImage: {
          fieldName: 'file',
          meta: {
            pid: 0
          },
          headers: {
            'Authori-Zation': userStore.getTokenKey + userStore.getToken
          },
          allowedFileTypes: ['image/*'],
          server: `${REQUEST_BASE}/file/upload/0`,
          customInsert(res: any, insertFn) {
            insertFn(res.data.src, res.data.src, res.data.src)
          },
          // 上传之前触发
          onBeforeUpload(file: File) {
            loading.value = true
            return file
          },
          // 上传进度的回调函数
          onProgress(progress: number) {
            loadingText.value = `进度${progress}%`
            console.log('progress', progress)
          },
          // 单个文件上传成功之后
          onSuccess(file: File, res: any) {
            loading.value = false
            console.log(`${file.name} 上传成功`, res)
          },
          // 单个文件上传失败
          onFailed(file: File, res: any) {
            loading.value = false
            console.log(`${file.name} 上传失败`, res)
          },
          onError(_: File, err: any, __: any) {
            loading.value = false
            //判断是否图片上传过大
            if (err.message.indexOf('exceeds maximum allowed size of') > -1) {
              ElMessage.error(
                `文件上传不可大于${err.message.split('exceeds maximum allowed size of')[1]}`
              )
            }
          }
        }
      },
      readOnly: false,
      customAlert: (s: string, t: string) => {
        switch (t) {
          case 'success':
            ElMessage.success(s)
            break
          case 'info':
            ElMessage.info(s)
            break
          case 'warning':
            ElMessage.warning(s)
            break
          case 'error':
            ElMessage.error(s)
            break
          default:
            ElMessage.info(s)
            break
        }
      },
      autoFocus: false,
      scroll: true,
      uploadImgShowBase64: true
    },
    props.editorConfig || {}
  )
})

const editorStyle = computed(() => {
  return {
    height: isNumber(props.height) ? `${props.height}px` : props.height
  }
})

// 回调函数
const handleChange = (editor: IDomEditor) => {
  emit('change', editor)
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = unref(editorRef.value)

  // 销毁，并移除 editor
  editor?.destroy()
})

const getEditorRef = async (): Promise<IDomEditor> => {
  await nextTick()
  return unref(editorRef.value) as IDomEditor
}

defineExpose({
  getEditorRef
})
</script>

<template>
  <div class="border-1 border-solid border-[var(--el-border-color)] z-10">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :editorId="editorId"
      class="border-0 b-b-1 border-solid border-[var(--el-border-color)]"
    />
    <!-- 编辑器 -->
    <Editor
      v-loading="loading"
      :element-loading-text="loadingText"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      v-model="valueHtml"
      :editorId="editorId"
      :defaultConfig="editorConfig"
      :style="editorStyle"
      @on-change="handleChange"
      @on-created="handleCreated"
    />
  </div>
</template>

<style src="@wangeditor/editor/dist/css/style.css"></style>
