<template>
    <div ref="editorRef"></div>
</template>

<script>
import '@toast-ui/editor/dist/i18n/zh-cn';
import Editor from '@toast-ui/editor';

//uml插件
import uml from '@toast-ui/editor-plugin-uml';
//代码高亮插件
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight';
//图表插件
import chart from '@toast-ui/editor-plugin-chart';
//文本颜色选择插件
import colorSyntax from '@toast-ui/editor-plugin-color-syntax';
//表格合并插件
import tableMergedCell from '@toast-ui/editor-plugin-table-merged-cell';

export default {
    name: 'PaasMdEditor',
    computed: {
        see() {
            return this.$store?.forms?.see || false;
        }
    },
    props: {
        height: {
            type: String,
            default: '55vh'
        },
        modelValue: {
            type: String,
            default: ''
        }
    },
    emits: ['update:modelValue'],
    data() {
        return {
            editorInstance: null,
            hostname: window.location.protocol + '//' + window.location.host,
        };
    },
    mounted() {
        const editorContainer = this.$refs.editorRef;
        let markdown = '';
        if (this.modelValue) {
            markdown = this.modelValue.replace("$hostname", this.hostname);
        }
        this.editorInstance = new Editor({
            el: editorContainer,
            height: this.height,
            previewStyle: 'vertical',
            initialEditType: 'wysiwyg',
            initialValue: markdown,
            language: 'zh-CN',
            usageStatistics: false,
            readOnly: this.see,
            plugins: this.see ? [] : [codeSyntaxHighlight, chart, uml, colorSyntax, tableMergedCell],
            hooks: this.see ? {} : {
                addImageBlobHook: async (blob, callback) => {
                    let url;
                    const uploadUrl = "/system/open/minio/image/uploadFile";
                    const formData = new FormData();
                    formData.append('file', blob, blob.name || 'image.png');
                    let res = await this.$upload(uploadUrl, formData);
                    if (res.data.code == this.$success) {
                        this.$message.success(res.data.msg);
                        url = res.data.data.newName;
                    }
                    callback(this.hostname + '/system/open/minio/preview?filename=' + url, blob.name || '图片');
                }
            }
        });

        this.editorInstance.on('change', () => {
            let markdown = this.editorInstance.getMarkdown();

            markdown = markdown.replace(this.hostname, "$hostname");
            if (markdown !== this.modelValue) {
                this.$emit('update:modelValue', markdown);
            }
        });
    },
    beforeDestroy() {
        this.editorInstance && this.editorInstance.destroy();
    }
};
</script>
