<template>
  <TEditor v-model="content" :init="init" tag-name="div" :disabled="disabled" />
</template>

<script setup lang="ts">
  //引入tinymce编辑器
  import TEditor from '@tinymce/tinymce-vue'
  import tinymce from 'tinymce/tinymce'
  import { computed, ref, onMounted, watch } from 'vue'
  import defaultInit from './init'
  import './sideEffects'
  import Config from '@/config'
  import { useI18n } from 'vue-i18n'
  import { uploadFile } from '@/utils/upload.js'

  const { t } = useI18n()
  const props = defineProps({
    modelValue: {
      type: String,
      default: '',
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    plugins: {
      type: [String, Array],
      default: 'link lists image code table wordcount autoresize',
    },
    toolbar: {
      type: [String, Array],
      default:
        'undo redo | bold italic underline strikethrough | fontsizeselect lineheight | forecolor backcolor | bullist numlist | removeformat | alignleft aligncenter alignright alignjustify | indent2em blockquote | link unlink image code | tagsSplit ',
    },
    height: Number,
  })

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

  const init = ref({
    ...defaultInit,
    plugins: props.plugins || defaultInit.plugins,
    toolbar: props.toolbar || defaultInit.toolbar,
    height: props.height || defaultInit.height,
    images_upload_handler: (blobInfo, success, failure) => {
      handleImgUpload(blobInfo, success, failure)
    },
    file_picker_callback: (callback, value, meta) => {
      console.log('file_picker_callback', callback, value, meta)
    },
    // 添加错误处理，静默处理图片尺寸获取失败的情况
    setup: (editor) => {
      // 监听图片尺寸获取错误，静默处理
      editor.on('Error', (e) => {
        if (e.message && e.message.includes('Failed to get image dimensions')) {
          // 静默处理，不显示错误提示
          e.preventDefault()
          console.warn('图片尺寸获取失败，但不影响使用:', e.message)
        }
      })
    },
  })
  const content = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emit('update:modelValue', val)
    },
  })

  const handleImgUpload = async (blobInfo, success, failure) => {
    try {
      const file = blobInfo.blob()
      const result = await uploadFile(file, '/common/upload')
      if (result.code === 200) {
        // 新接口返回的文件路径，需要拼接 Host05
        let host05 = Config.Host05
        // 确保Host05有协议前缀
        if (!host05.startsWith('http://') && !host05.startsWith('https://')) {
          host05 = 'http://' + host05
        }
        const filePath = result.data.startsWith('/') ? result.data : '/' + result.data
        const fileUrl = host05 + filePath
        success(fileUrl)
      } else {
        failure(result.msg || t('Msg.Fail'))
      }
    } catch (error) {
      failure(error.message || t('Msg.Fail'))
    }
  }
  onMounted(() => {
    tinymce.init(init.value) // 初始化富文本
  })
</script>

<style scoped lang="scss">
  .tinymce {
    .el-form-item:nth-child(3) {
      .el-form-item__content {
        width: 85%;
      }
    }
    .tox-tinymce {
      min-height: 450px;
    }
  }
</style>
