<template>
  <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container">
    <textarea :id="tinymceId" class="tinymce-textarea"/>
    <div class="editor-custom-btn-container">
      <editorImage color="#1890ff"
                   class="editor-upload-btn"
                   @onChange="imageSuccessCBK"
                   ref="upload"
                   :limit="1"
                   :oss-key="ossKey"
                   :appendix-ids="appendixIds"
                   accept=".jpg,.png"
                   :table-name="tableName"
                   :comp-id="compId"
                   :vesselId="vesselId"
      />
    </div>
  </div>
</template>

<script>
    import editorImage from './components/editorImage';
    import plugins from './plugins';
    import toolbar from './toolbar';
    import {getFileList} from '../../api/new'

    export default {
        name: 'Tinymce',
        components: {editorImage},
        props: {
            id: {
                type: String,
                default: function () {
                    return (
                        'vue-tinymce-' +
                        +new Date() +
                        ((Math.random() * 1000).toFixed(0) + '')
                    );
                }
            },
            value: {
                type: String,
                default: ''
            },
            toolbar: {
                type: Array,
                required: false,
                default() {
                    return [];
                }
            },
            menubar: {
                type: String,
                // default: "file edit insert view format table"
                default: ''
            },
            height: {
                type: Number,
                required: false,
                default: 360
            },
            compId: {
                // 公司ID
                type: String,
                required: false
            },
            vesselId: {
                // 船舶ID
                type: String,
                required: false
            },
            tableName: {
                // 要保存的表的名字
                type: String,
                required: false
            },
            ossKey: {
                type: String,
                required: true
            },
        },
        data() {
            return {
                hasChange: false,
                appendixIds: '',
                hasInit: false,
                tinymceId: this.id,
                tinymceUrl: '',
                appendixIds: '',
                fullscreen: false,
                languageTypeList: {
                    en: 'en',
                    zh: 'zh_CN'
                }
            };
        },
        computed: {
            language() {
                return this.languageTypeList['zh'];
            }
        },
        watch: {
            value(val, old) {
                if (!this.hasChange && this.hasInit) {
                    this.$nextTick(() => {
                        window.tinymce.get(this.tinymceId).setContent(val || '');
                    });
                }
            },
            language() {
                this.destroyTinymce();
                this.$nextTick(() => this.initTinymce());
            }
        },
        mounted() {
            this.initTinymce();
        },
        activated() {
            this.initTinymce();
        },
        deactivated() {
            this.destroyTinymce();
        },
        destroyed() {
            this.destroyTinymce();
        },
        methods: {
            resetContent(content) {
                this.value = content || '';
                this.$nextTick(() => {
                    window.tinymce.get(this.tinymceId).setContent(content || '');
                });
            },
            initTinymce() {
                const _this = this;
                window.tinymce.init({
                    selector: `#${this.tinymceId}`,
                    language: this.language,
                    height: this.height,
                    body_class: 'panel-body ',
                    object_resizing: false,

                    toolbar: this.toolbar.length > 0 ? this.toolbar : toolbar,
                    menubar: this.menubar,
                    plugins: plugins,
                    end_container_on_empty_block: true,
                    powerpaste_word_import: 'clean',
                    code_dialog_height: 450,
                    code_dialog_width: 1000,
                    advlist_bullet_styles: 'square',
                    advlist_number_styles: 'default',
                    // imagetools_cors_hosts: ["www.tinymce.com", "codepen.io"],
                    default_link_target: '_blank',
                    link_title: false,
                    nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
                    init_instance_callback: editor => {
                        if (_this.value) {
                            editor.setContent(_this.value);
                        }
                        _this.hasInit = true;
                        editor.on('NodeChange Change KeyUp SetContent', () => {
                            this.hasChange = true
                            this.$emit('input', editor.getContent())
                        });
                    },
                    setup(editor) {
                        editor.on('FullscreenStateChanged', e => {
                            _this.fullscreen = e.state;
                        });
                        editor.addButton('imageUpload', {
                            tooltip: '插入图片',
                            icon: 'mce-ico mce-i-image',
                            onclick: function () {
                                let upload = _this.$refs.upload
                                upload.handleUploadClick()
                            }
                        })
                    }
                });
            },
            destroyTinymce() {
                const tinymce = window.tinymce.get(this.tinymceId);
                if (this.fullscreen) {
                    tinymce.execCommand('mceFullScreen');
                }

                if (tinymce) {
                    tinymce.destroy();
                }
            },
            setContent(value) {
                window.tinymce.get(this.tinymceId).setContent(value);
            },
            getContent() {
                window.tinymce.get(this.tinymceId).getContent();
            },
            checkUrl(path){
                if(path.indexOf("http://")>-1||path.indexOf("https://")>-1){
                    let pathSplit = path.split(".com/")
                    if (pathSplit){
                        path = pathSplit[1]
                    }
                }
                return path;
            },
            getFilePath(path) {
                let sysUrl =  process.env.NODE_ENV === "production"?"http://" + window.location.host+"/":"http://product-dev.winsea.com/";
                path = this.checkUrl(path)
                if (this.clientFag === "B") {
                    sysUrl+="pb/"
                }
                return sysUrl + this.slash(path);
            },
            imageSuccessCBK(arr) {
                const _this = this;
                _this.$refs.upload.handleSaveBill().then(res => {
                    if (res) {
                        let appendixIds = res
                        // getFileList({appendixIds})
                        //     .then(resp => {
                        //         if (resp.data.length > 0) {
                        //             _this.tinymceUrl = this.getFilePath(resp.data[0].appendixPath)
                        //             debugger
                          if (arr.length>0){
                                    window.tinymce
                                        .get(_this.tinymceId)
                                        .insertContent(`<div style="width: 100%;text-align: center;">
                                        <img style="max-width: 50%;max-height: 280px" src="${arr[0].url}"/>
                                        </div><br>`);
                          }
                                    
                        //         }
                        //     })
                    }
                })

            }
        }
    };
</script>

<style scoped>
  .tinymce-container {
    position: relative;
    line-height: normal;
  }

  .tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
  }

  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }

  .editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    /*z-index: 2005;*/
  }

  .fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
  }

  .editor-upload-btn {
    display: inline-block;
  }

  .wscnph {


  }
</style>
