<template>
    <div>
        <QuillEditor
            ref="myQuillEditor"
            theme="snow"
            v-model:content="content"
            :options="data.editorOption"
            contentType="html"
            @update:content="onContentUpdate"
        />
        <!-- 使用自定义图片上传 -->
        <!-- <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" /> -->
    </div>
</template>

<script setup>
import { ref, watch, onMounted, toRefs } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

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

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

const { modelValue } = toRefs(props)
const content = ref(props.modelValue)
const myQuillEditor = ref()
const fileBtn = ref()

const data = {
    editorOption: {
        modules: {
            toolbar: [
                ['bold', 'italic', 'underline', 'strike'],
                [{ size: ['small', false, 'large', 'huge'] }],
                [{ font: [] }],
                [{ align: [] }],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ indent: '-1' }, { indent: '+1' }],
                [{ header: 1 }, { header: 2 }],
                // ['image'],
                [{ direction: 'rtl' }],
                [{ color: [] }, { background: [] }]
            ]
        },
        placeholder: '请输入内容...'
    }
}

const onContentUpdate = (newContent) => {
    content.value = newContent
    emit('update:modelValue', newContent)
}

const imgHandler = state => {
    if (state) {
        fileBtn.value.click()
    }
}

const handleUpload = e => {
    const files = Array.prototype.slice.call(e.target.files)
    if (!files) {
        return
    }
    const formdata = new FormData()
    formdata.append('file', files[0])
    // backsite.uploadFile(formdata)
    //   .then(res => {
    //     if (res.data.url) {
    //       const quill = toRaw(myQuillEditor.value).getQuill()
    //       const length = quill.getSelection().index
    //       // 插入图片，res为服务器返回的图片链接地址
    //       quill.insertEmbed(length, 'image', res.data.url)
    //       // 调整光标到最后
    //       quill.setSelection(length + 1)
    //     }
    //   })
}

onMounted(() => {
    const quill = myQuillEditor.value.getQuill()
    if (quill) {
        quill.getModule('toolbar').addHandler('image', imgHandler)
    }
    myQuillEditor.value.setHTML(modelValue.value)
})

watch(modelValue, (newVal) => {
    if (newVal !== content.value) {
        content.value = newVal
        myQuillEditor.value.setHTML(newVal)
    }
}, { deep: true })
</script>

<style scoped lang="scss">
:deep(.ql-editor) {
    min-height: 180px;
}
:deep(.ql-formats) {
    height: 21px;
    line-height: 21px;
}
</style>