<template>
  <div class="editor-container">
    <div ref="editorRef" class="quill-editor"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请输入内容'
  },
  height: {
    type: Number,
    default: 300
  }
});

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

const editorRef = ref<HTMLElement | null>(null);
let editor: any = null;

onMounted(() => {
  if (editorRef.value) {
    editor = new Quill(editorRef.value, {
      theme: 'snow',
      modules: {
        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']
        ]
      },
      placeholder: props.placeholder
    });
    
    // 设置初始内容
    if (props.modelValue) {
      editor.clipboard.dangerouslyPasteHTML(props.modelValue);
    }
    
    // 监听内容变化
    editor.on('text-change', () => {
      const html = editor.root.innerHTML;
      emit('update:modelValue', html);
    });
  }
});

// 监听 modelValue 变化
watch(() => props.modelValue, (newValue) => {
  if (editor && newValue !== editor.root.innerHTML) {
    editor.clipboard.dangerouslyPasteHTML(newValue);
  }
});

onBeforeUnmount(() => {
  editor = null;
});

// 暴露获取编辑器内容的方法
defineExpose({
  getContent: () => {
    return editor ? editor.root.innerHTML : '';
  }
});
</script>

<style scoped>
.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.quill-editor {
  height: v-bind('props.height + "px"');
}
</style> 