<template>
    <div id="su-tinymce-edit" v-if="isRender">
        <editor v-model="text"
                :placeholder="placeholder"
                :init="init"
                :disabled="disabled"></editor>
    </div>
</template>

<script>
import "tinymce/tinymce";
import "tinymce/themes/silver/theme";
import "tinymce/plugins/fullscreen/plugin.js"; // 全屏插件
import "tinymce/plugins/code/plugin.js"; // code插件
import "tinymce/plugins/table"; //表格插件
import "tinymce/plugins/link"; //超链接插件
import "tinymce/plugins/anchor"; //锚点插件
import "tinymce/plugins/image"; //锚点插件
import "tinymce/plugins/wordcount"

import "./plugins/placeholder/plugin"; // placeholder插件
import "./plugins/lineheight/plugin"; // placeholder插件
import "./plugins/paste/plugin"; // placeholder插件
import "./zh_CN"
import "./icons/default";

import "./skins/ui/oxide/skin.css";
import content_style from "./skins/content_style"
import Editor from "@tinymce/tinymce-vue";
import UploadUtil from "../../../service/uploader";
import Uploader from "../../../service/uploader/Uploader";
import Mask from "../../../service/Mask"

export default {
    name: "tinymce",
    components: {Editor},
    data() {
        let vm = this;
        return {
            isRender:true,
            init: {
                skin: false,
                // language_url: "../../../modules/frame/static/tinymce/langs/zh_CN.js",
                language: "zh_CN",
                // skin_url: "../../../modules/frame/static/tinymce/skins/oxide", //skin路径
                content_css: false,//resolved to http://domain.mine/myLayout.css
                width: "100%",
                height: 250, //编辑器高度
                branding: false, //是否禁用“Powered by TinyMCE”
                menubar: !this.disabled, //顶部菜单栏显示
                menu: this.disabled ? {} : {
                    file: {title: 'File', items: 'newdocument restoredraft | preview | print '},
                    edit: {title: 'Edit', items: 'undo redo | cut copy paste | selectall | searchreplace'},
                    view: {
                        title: 'View',
                        items: 'code | visualaid visualchars visualblocks | spellchecker | preview fullscreen'
                    },
                    insert: {
                        title: 'Insert',
                        items: 'image link media template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor toc | insertdatetime'
                    },
                    format: {
                        title: 'Format',
                        items: 'bold italic underline strikethrough superscript subscript codeformat | formats blockformats fontformats fontsizes align lineheight | forecolor backcolor | removeformat'
                    },
                    // tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | code wordcount' },
                    table: {title: 'Table', items: 'inserttable | cell row column | tableprops deletetable'},
                    help: {title: 'Help', items: 'help'}
                },
                content_style,
                fontsize_formats: '8px 10px 12px 14px 16px 18px 24px 36px 48px',
                plugins:
                    "image fullscreen code table link anchor lineheight placeholder paste wordcount",
                toolbar: this.disabled ? [] : [
                    "code fullscreen",
                    "undo redo image",
                    // "alignleft aligncenter alignright alignjustify lineheight",
                    "alignleft aligncenter alignright lineheight",
                    // "bold italic underline strikethrough",
                    "bold fontsizeselect",
                    "forecolor backcolor",
                    // "table",
                    "anchor link unlink",
                    // "removeformat",
                ].join(" | "),
                end_container_on_empty_block: true, // enter键 分块
                powerpaste_word_import: 'merge', // 是否保留word粘贴样式  clean | merge
                code_dialog_height: 450, // 代码框高度 、宽度
                code_dialog_width: 1000,
                advlist_bullet_styles: 'square', // 无序列表 有序列表
                entity_encoding: 'raw',
                //选中时出现的快捷工具，与插件有依赖关系
                quickbars_selection_toolbar: 'bold italic forecolor | link blockquote quickimage',
                paste_enable_default_filters: false,
                paste_data_images: true, // 设置为“true”将允许粘贴图像，而将其设置为“false”将不允许粘贴图像。
                link_title: false,
                nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                // init_instance_callback: editor => {
                // },
                //上传图片回调
                images_upload_handler: function (blobInfo, success, failure) {
                    if (vm.autoUpload) {
                        Mask.showLoading();
                        vm.uploader.uploadFile(blobInfo.blob()).then(function (data) {
                            success(data.serverUrl);
                        }).catch(e => failure(e)).finally(function () {
                            Mask.hideLoading();
                        });
                    } else {
                        success("data:image/png;base64," + blobInfo.base64())
                    }
                    // success(blobInfo.blobUri())
                },
                images_dataimg_filter: function (img) {
                    return true;//||img.hasAttribute('internal-blob');
                },
                urlconverter_callback: (url, node, on_save, name) => { //设置白名单
                    return url
                },
                setup(editor) {
                    editor.on('FullscreenStateChanged', (e) => {
                        vm.fullscreen = e.state
                    })
                },
            },
            text: "",
        };
    },
    props: {
        value: {
            type: String
        },
        placeholder: {
            type: String,
            default: "输入内容...",
        },
        autoUpload: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            default: false
        },
        uploader: {
            type: Uploader,
            default: () => UploadUtil,
        },
        options: {
            type: Object,
            default() {
                return {}
            }
        }
    },
    watch: {
        value: {
            immediate: true,
            handler(val, prevVal) {
                let vm = this;
                if (typeof val === 'string' && val !== prevVal && val !== this.text && val !== this.escapeValue) {
                    vm.text = val;
                }
            }
        },
        text() {
            if(this.isRender){
                this.onChange();
            }
        }
    },
    created() {
    },
    activated(){
        if(this.isDeactivated){
            this.refresh();
        }
    },
    deactivated(){
        this.isDeactivated = true;
    },
    methods: {
        escape2Html(str) {
            let arrEntities = {'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"'};
            return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
                return arrEntities[t];
            });
        },
        refresh(){
            //如果text里存在html head之类的  重新渲染后 这些会消失 从而走了onchange事件 原因未知 可能是进行了格式化
            this.isRender = false;
            let text_ = this.text;
            this.$nextTick(()=>{
                this.isRender = true;
                this.$nextTick(()=>{
                    this.text = text_;
                })
            })
        },
        onChange() {
            // console.log("onChange",this.text);
            let escapeValue = this.escape2Html(this.text);
            this.escapeValue = escapeValue;
            this.$emit('input', escapeValue);
        },
        getContentText () {
            const activeEditor = tinymce.activeEditor;
            const editBody = activeEditor.getBody();
            activeEditor.selection.select(editBody);
            return activeEditor.selection.getContent({ 'format' : 'text' }).replace(/\r?\n/g, ' ');
        }
    }
}
</script>

<style scoped>

</style>
