<template>
  <div class="rich-text-editor">
    <QuillEditor
      v-model:content="content"
      :toolbar="toolbar"
      contentType="html"
      theme="snow"
      @update:content="handleContentChange"
      @blur="handleBlur"
      @ready="handleReady"
      :options="{
        placeholder: '请输入内容...',
        modules: {
          clipboard: {
            matchVisual: false
          }
        }
      }"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { uploads } from '../utils/api'
import { useToast } from '../composables/useToast'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'blur'])
const { showToast } = useToast()

const content = ref(props.modelValue)

// 监听外部值的变化
watch(() => props.modelValue, (newVal) => {
  if (newVal !== content.value) {
    content.value = newVal
  }
})

const toolbar = [
  ['bold', 'italic', 'underline', 'strike'],
  ['blockquote', 'code-block'],
  [{ 'header': 1 }, { 'header': 2 }],
  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
  [{ 'script': 'sub'}, { 'script': 'super' }],
  [{ 'indent': '-1'}, { 'indent': '+1' }],
  [{ 'direction': 'rtl' }],
  [{ 'size': ['small', false, 'large', 'huge'] }],
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
  [{ 'color': [] }, { 'background': [] }],
  [{ 'font': [] }],
  [{ 'align': [] }],
  ['clean'],
  ['link', 'image', 'video']
]

const handleContentChange = (newContent) => {
  emit('update:modelValue', newContent)
}

const handleBlur = (editor, e) => {
  emit('blur', editor, e)
}

const handleReady = (editor) => {
  // 添加图片上传处理
  const toolbar = editor.getModule('toolbar')
  toolbar.addHandler('image', () => {
    const input = document.createElement('input')
    input.setAttribute('type', 'file')
    input.setAttribute('accept', 'image/*')
    input.click()

    input.onchange = async () => {
      const file = input.files[0]
      if (file) {
        try {
          // 上传图片到服务器
          const { data } = await uploads.uploadImage(file)
          const imageUrl = data.url
          
          // 获取编辑器选中的位置
          const range = editor.getSelection()
          
          // 在光标位置插入图片
          editor.insertEmbed(range.index, 'image', imageUrl)
        } catch (error) {
          console.error('Error uploading image:', error)
          showToast('图片上传失败', 'error')
        }
      }
    }
  })
}
</script>

<style scoped>
.rich-text-editor {
  @apply mb-4;
}

:deep(.ql-editor) {
  min-height: 200px;
}

:deep(.ql-toolbar) {
  @apply bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600;
}

:deep(.ql-container) {
  @apply bg-white dark:bg-gray-700 border-gray-300 dark:border-gray-600;
}

:deep(.ql-editor) {
  @apply text-gray-900 dark:text-white;
}

:deep(.ql-toolbar button) {
  @apply text-gray-700 dark:text-gray-300;
}

:deep(.ql-toolbar button:hover) {
  @apply text-gray-900 dark:text-white;
}

:deep(.ql-formats) {
  @apply mr-2;
}
</style>
