<script setup lang="ts">
import type {Ref} from  "vue";
import {onMounted, reactive, ref, watch} from "vue";

// 编辑器本体
import '@toast-ui/editor/dist/toastui-editor.css';
import "@toast-ui/editor/dist/i18n/zh-cn";
import Editor from "@toast-ui/editor";

// 代码高亮样式
import Prism from 'prismjs'
import 'prismjs/themes/prism.css';
import '@toast-ui/editor-plugin-code-syntax-highlight/dist/toastui-editor-plugin-code-syntax-highlight.css';
import codeSyntaxHighlight from '@toast-ui/editor-plugin-code-syntax-highlight'
// 字体颜色
import 'tui-color-picker/dist/tui-color-picker.css'
import "@toast-ui/editor-plugin-color-syntax/dist/toastui-editor-plugin-color-syntax.css"
import colorSyntax from "@toast-ui/editor-plugin-color-syntax"
// 表格插件
import chart from "@toast-ui/editor-plugin-chart"
// 单元格合并
import tableMergedCell from "@toast-ui/editor-plugin-table-merged-cell"
// uml 插件
import uml from "@toast-ui/editor-plugin-uml"

import {useI18n} from "vue-i18n";

const emit = defineEmits([
    "update:modelValue"
])
const props = defineProps({
    modelValue: {
        type: String,
        default: ""
    }
})
const chartOptions = {
    minWidth: 100,
    maxWidth: 600,
    minHeight: 100,
    maxHeight: 300
};

const {locale} = useI18n()

const editorRef = ref()

function initEditor(editorRef:Ref<any>){
    let editor = new Editor({
        theme: "dark",
        el: editorRef.value,
        // language: 'en-US',
        language: locale.value,
        previewStyle: 'vertical',
        height: '85vh',
        initialValue: props.modelValue,
        plugins: [
            [chart, chartOptions],
            [codeSyntaxHighlight, {highlighter: Prism}],
            tableMergedCell,
            uml,
            colorSyntax,
        ],
        useCommandShortcut: true,
        usageStatistics: true,
        hideModeSwitch: false,
        events: {
            change: () => emit('update:modelValue', editor.getMarkdown()),
        },
        // toolbarItems: [
        //     ['heading', 'bold', 'italic', 'strike'],
        //     ['hr', 'quote'],
        //     ['ul', 'ol', 'task', 'indent', 'outdent'],
        //     ['table', 'image', 'link'],
        //     ['code', 'codeblock'],
        //     ['scrollSync'],
        // ]
    })


    // const viewer = Editor.factory({
    //     el: editorRef.value,
    //     viewer: true,
    //     height: '500px',
    //     initialValue: "",
    //     plugins: [[chart, chartOptions], [codeSyntaxHighlight, { highlighter: Prism }], tableMergedCell, uml]
    // });

    return editor;
}

onMounted(() => {
    let editor = initEditor(editorRef);
    watch(locale, value => {
        let markdown = editor.getMarkdown()
        editor.destroy()

        editor = initEditor(editorRef);
        editor.setMarkdown(markdown)
    })
})

const ctx = reactive({
    data: ""
})
</script>

<template>
    <div ref="editorRef" class="overscroll-none"/>
</template>

<style scoped lang="scss">

</style>
