<script setup>
import {computed, nextTick, ref, watch} from "vue";
import Editor from "@tinymce/tinymce-vue";
import {VITE_TINYMCE_KEY} from "../../utils/index.js";
import Api from "../../api/index.js";

const content = defineModel('content');
const EditorIF = ref(true);
const loading = ref(true);
const {skin} = defineProps({
    skin: {
        type: String,
        default: 'borderless', // 'fluent'
    }
});

const onEditorReady = () => {
    loading.value = false;
}

const INIT = computed(() => ({
    language: 'zh_CN',
    skin: skin,
    content_css: skin === 'fluent' ? 'fluent' : null,
    toolbar_mode: skin === 'fluent' ? 'floating' : null,
    plugins: 'advlist anchor autolink charmap code codesample directionality help image editimage insertdatetime link lists media nonbreaking pagebreak preview searchreplace table tableofcontents visualblocks visualchars wordcount',
    toolbar: 'undo redo | blocks | bold italic strikethrough forecolor backcolor blockquote | link image media | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat',
    init_instance_callback: onEditorReady,
    images_upload_url: 'http://your-api/upload',
    images_upload_credentials: true,
    images_upload_handler: (blobInfo, success, failure) => {
        return new Promise((resolve, reject) => {
            Api.system.uploadFile(blobInfo.blob()).then(({data}) => {
                resolve(data);
            }).catch(err => {
                reject(err);
            });
        })
    },
    file_picker_types: 'image',
    images_reuse_filename: true,
    images_upload_types: 'jpeg,jpg,png,gif',
}));

watch(
    () => skin,
    () => {
        EditorIF.value = false;
        nextTick(() => {
            EditorIF.value = true;
        })
    },
    {deep: true}
)
</script>

<template>
    <div id="TinyMCE" class="w-full h-full min-h-[500px]">
        <a-spin
            dot
            :size="20"
            class="w-full h-full min-h-[500px]"
            :loading="loading"
            tip="编辑器加载中">
            <Editor
                v-model="content"
                v-if="EditorIF"
                :init="INIT"
                :api-key="VITE_TINYMCE_KEY()"
                @on-ready="onEditorReady">
            </Editor>
        </a-spin>
    </div>
</template>

<style scoped lang="scss">
#TinyMCE {
    :deep(.tox) {
        width: 100%;
        height: 100% !important;
        min-height: 500px !important;
    }
}
</style>
