<template>
    <div class="rich-editor">
        <editor v-model="myValue" :init="setting"  :disabled="disabled">
        </editor>
    </div>
</template>

<script>
    window.tinymce.baseURL = '/tinymce';
    //富文本支持
    import tinymce from 'tinymce/tinymce'
    import Editor from '@tinymce/tinymce-vue'
    import 'tinymce/themes/silver/theme'
    import 'tinymce/icons/default/icons'
    //富文本插件
    import 'tinymce/plugins/code' //已经验证
    import 'tinymce/plugins/image' //图片
    import 'tinymce/plugins/media' //媒体
    import 'tinymce/plugins/link' //链接
    import 'tinymce/plugins/hr' //横线
    import 'tinymce/plugins/help' //帮助
    import 'tinymce/plugins/fullscreen' //全屏
    import 'tinymce/plugins/table' //表格
    import 'tinymce/plugins/lists'  //列表
    import 'tinymce/plugins/contextmenu' //右键菜单
    import 'tinymce/plugins/wordcount'   //字数计算器
    import 'tinymce/plugins/colorpicker' //已经验证
    import 'tinymce/plugins/textcolor' //已经验证

    import { getToken } from "../utils/auth";

    export default {
        name:"RichEditor",
        components: {
            Editor
        },
        props: {
            options:{
              type:Object,
              default(){
                  return {};
              }
            },
            //传入一个value，使组件支持v-model绑定
            value: {
                type: String,
                default: ''
            },
            disabled: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                //初始化配置
                setting: {},
                myValue: this.value,
                defaults:{
                    // inline: true,//内联模式
                    // language_url: 'tinymce/langs/zh_CN.js',//语言包的路径
                    language: 'zh_CN',//语言
                    // skin:"oxide",
                    // skin_url: 'tinymce/skins/ui/oxide',//skin路径
                    height: 500,//编辑器高度
                    // theme: "silver",//主题
                    branding: false,//是否禁用“Powered by TinyMCE”
                    menubar: false,//顶部菜单栏显示
                    statusbar: false, // 隐藏编辑器底部的状态栏
                    paste_data_images: true, // 允许粘贴图像
                    // indentation : '20pt',//缩进大小设置，目前采用的 padding-left 不是期望的结果
                    //自定义字体
                    font_formats:"微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
                    //自定义字体大小支持
                    fontsize_formats: "8px 9px 10px 11px 12px 13px 14px 16px 18px 20px 22px 24px 28px 32px 36px 40px 50px 60px 6pt 8pt 10pt 12pt 13pt 14pt 15pt 16pt 17pt 18pt 19pt 20pt 24pt 28pt 32pt 36pt 40pt 50pt 60pt",
                    //载入的插件
                    plugins: 'code image media link hr help fullscreen table lists wordcount preview ', // 即将过时的插件 colorpicker textcolor contextmenu
                    toolbar_mode:"wrap",//wrap显示  sliding嵌入
                    toolbar: 'code | bold italic underline strikethrough | fontselect fontsizeselect | forecolor backcolor | fullscreen ' +
                        '| lineheight | alignleft aligncenter alignright alignjustify alignnone ' +
                        '| bullist numlist | outdent indent blockquote | link unlink image media | hr table ' +
                        '| cut copy paste | undo redo | subscript superscript | removeformat | preview | help ',
                    //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片， 需要image插件
                    //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
                    images_upload_handler: (blobInfo, success, failure) => {
                        if(blobInfo.blob().name) {//判断是文件,且有文件名,才认为是上传操作
                            this.postFile( blobInfo.blob(), blobInfo.filename(),success,failure);
                        }
                    },
                    // selector: "remark",
                    file_picker_types: 'file image media',
                    //此处为文件上传支持，需要link插件,不论是哪种上传方式最终都会指向此函数
                    file_picker_callback: (callback, value, meta) => {
                        let filetype = "application/*";
                        //为不同插件指定文件类型及后端地址
                        switch (meta.filetype) {
                            case 'image':
                                filetype = 'image/*';
                                break;
                            case 'media':
                                filetype = 'video/*,audio/*';
                                break;
                            case 'file':
                            default:
                                break;
                        }
                        let input = document.createElement('input');
                        input.setAttribute('type', 'file');
                        input.setAttribute('accept', filetype);
                        input.click();
                        let that=this;
                        input.onchange = function () {
                            let file = this.files[0];
                            that.postFile(file, file.name,callback);
                        };
                    },
                    media_live_embeds:true,//没有效果
                    media_alt_source:false,//禁用备用地址
                    media_dimensions: false,//禁用大小控制
                    media_poster:false,// 禁止封面
                    media_filter_html:false,//禁用代码过滤
                    video_template_callback: function(data) {
                        //格式上面如果没有宽度，高度，控件又会自己补充
                        // console.log("=====>追加数据到正文",data);
                        return '<video  controls="controls" src="' + data.source + '"' + (data.sourcemime ? ' type="' + data.sourcemime + '"' : '') + '></video>';
                    },
                }
            }
        },
        created(){
            this.setting= this.$d.merge(this.defaults,this.options);
        },
        mounted() {
            console.log(this.setting);
            tinymce.init({});
        },
        methods: {
            postFile(file,name,success,failure){//目前还没对出错进行处理
                let xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                let url = this.$store.state.api.axios.baseURL + this.$store.state.api.upload; //后端接收上传文件的地址
                xhr.open('POST', url);
                let formData = new FormData();
                formData.append('app_id', this.$store.getters.appId);
                formData.append('access_token', this.$store.getters.accessToken);
                formData.append('token', getToken());
                let dataCallback = (xhr) => {
                    let json;
                    if (xhr.status != 200) {
                        this.$message.error('上传失败，错误代码: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.url != 'string') {
                        this.$message.error('上传失败，错误的应答格式:' + xhr.responseText);
                        return;
                    }
                    if (json.success) {
                        this.$message.success(json.msg);
                        let file_url=json.url;
                        if(!this.$d.isExternal(json.url)) {//如果是外部地址则不用拼接
                            file_url=this.$store.state.api.axios.baseURL+"/" +json.url;
                            if(json.url&&json.url.indexOf("/")==0)
                                file_url=this.$store.state.api.axios.baseURL+json.url;
                        }
                        success(file_url, {alt: json.name, text: json.name, target: "_blank", title: json.name});
                    } else {
                        this.$message.error(json.msg);
                    }
                }
                xhr.onload = function (e, x, t) {
                    dataCallback(xhr);
                };
                formData.append('file', file, name);
                xhr.send(formData);
            }
        },
        watch: {
            value(newValue) {
                this.myValue = newValue
            },
            myValue(newValue) {
                this.$emit('input', newValue)
            }
        }
    }

</script>
<style scoped>
</style>
