<template>
    <div id="app">
        <h1>TinyMCE in Vue</h1>
        <textarea id="editor" v-model="form.content"></textarea>
    </div>
</template>

<script>
import { defineComponent, nextTick, onMounted, reactive } from 'vue';

export default defineComponent({
    setup() {
        const form = reactive({
            content: '我是初始化内容',
        });

        // 动态引入 TinyMCE
        const loadTinyMCE = () => {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = '/tinymce/tinymce.min.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        };

        // 页面加载时
        onMounted(() => {
            loadTinyMCE()
                .then(() => {
                    // 富文本编辑器
                    nextTick(() => {
                        window.tinymce.init({
                            selector: '#editor', // 选择器，指定哪个元素使用 TinyMCE
                            license_key: 'gpl', // 许可密钥，如果是 GPL 版本则不需要设置
                            language: 'zh_CN', // 语言设置
                            width: '100%', // 编辑器宽度
                            height: 500, // 编辑器高度
                            menubar: true, // 是否显示菜单栏
                            statusbar: true, // 是否显示状态栏
                            branding: false, // 去除底部的 TinyMCE 广告
                            plugins: [
                                'advlist',
                                'autolink',
                                'lists',
                                'link',
                                'image',
                                'charmap',
                                'preview',
                                'anchor',
                                'searchreplace',
                                'visualblocks',
                                'code',
                                'fullscreen',
                                'insertdatetime',
                                'media',
                                'table',
                                'help',
                                'wordcount',
                                'emoticons',
                                'autosave',
                                'quickbars',
                                'codesample',
                            ], // 启用的插件列表
                            toolbar: [
                                'code formatselect fontselect fontsizeselect forecolor backcolor bold italic underline strikethrough link alignment outdent indent bullist numlist blockquote subscript superscript removeformat table image media importword charmap pagebreak formatpainter cut copy undo redo restoredraft searchreplace fullscreen',
                            ], // 工具栏按钮列表
                            toolbar_sticky: true, // 工具栏固定在顶部
                            content_css: '/path/to/content.css', // 自定义内容样式文件路径
                            content_style: `
              h2 { position: relative; z-index: 99; }
              h2::before {
                content: "";
                display: block;
                width: 200px;
                height: 8px;
                position: absolute;
                bottom: 6px;
                left: -4px;
                z-index: -1;
                border-radius: 4px 0 0 4px;
                background: linear-gradient(90deg, #F6AFB0 0%, #FFFFFF 100%);
              }
            `, // 自定义编辑器内容的样式
                            images_upload_handler: (blobInfo, success, failure) => {
                                const xhr = new XMLHttpRequest();
                                xhr.withCredentials = false;
                                xhr.open('POST', '/your-backend-endpoint'); // 图片上传的后端接口
                                xhr.onload = () => {
                                    if (xhr.status === 200) {
                                        success(xhr.responseText); // 上传成功，返回图片 URL
                                    } else {
                                        failure('HTTP Error: ' + xhr.status); // 上传失败，返回错误信息
                                    }
                                };
                                xhr.onerror = () => {
                                    failure('Image upload failed due to a network error.'); // 网络错误
                                };
                                xhr.send(blobInfo.blob()); // 发送图片数据
                            },
                            setup: editor => {
                                editor.on('change', () => {
                                    form.content = editor.getContent(); // 监听编辑器内容变化并更新表单内容
                                });
                            },
                        });
                    });
                })
                .catch(error => {
                    console.error('Failed to load TinyMCE:', error); // 处理 TinyMCE 加载失败的情况
                });
        });

        return {
            form,
        };
    },
});
</script>

<style>
#app {
    font-family: Avenir, Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
}
</style>
