<template>
  <div class="tinymce-container">
    <editor id="tinymce" v-model="value" :init="init"></editor>
  </div>
</template>

<script>
import tinymce from "tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";

import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autosave";
import "tinymce/plugins/code";
import "tinymce/plugins/codesample";
import "tinymce/plugins/colorpicker";

import "tinymce/plugins/contextmenu";
import "tinymce/plugins/directionality";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/hr";
import "tinymce/plugins/image";
import "tinymce/plugins/imagetools";

import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/link";
import "tinymce/plugins/lists";
import "tinymce/plugins/media";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/noneditable";
import "tinymce/plugins/pagebreak";

import "tinymce/plugins/paste";
import "tinymce/plugins/preview";
import "tinymce/plugins/print";
import "tinymce/plugins/save";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/spellchecker";
import "tinymce/plugins/tabfocus";

import "tinymce/plugins/table";
import "tinymce/plugins/template";
import "tinymce/plugins/textcolor";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount";

import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
// import { uploadImg } from "@/api/common";
//下面的插件是自带的,不需要引入
// import "tinymce/plugins/contextmenu";
// import "tinymce/plugins/colorpicker";
// import "tinymce/plugins/textcolor";
export default {
  name: "Tinymce",
  props: {
    tinymceHtml: "",
    tinymceHeight: {
      type: Number,
      default: 430,
    },
  },
  components: {
    Editor,
  },
  data() {
    return {
      tinymceId: "mytinymceId", //this.id,
      value: this.tinymceHtml, //父组件通过ref拿到该组件的值
      init: {
        selector: "#tinymce",
        content_style:
          "html,body { width: 100%;height: 100%;position: relative; background: transparent;padding:0;margin: 0;box-sizing: border-box;} body{padding:16px} p{margin:0;line-height:40px} img{ display: inline-block;height:100px} *{margin:0;font-size:12px}",
        language_url: "/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        height: this.tinymceHeight,
        body_class: "panel-body ",
        object_resizing: false,
        skin_url: "/tinymce/skins/ui/oxide", //编辑器需要一个skin才能正常工作，所以要设置一个skin_url指向之前复制出来的skin文件
        toolbar:
          "removeformat  bold italic underline strikethrough  forecolor backcolor numlist bullist alignleft aligncenter alignright  link  table fullscreen",

        menubar: "", //this.menubar,
        plugins:
          "advlist anchor autolink autosave code codesample colorpicker  contextmenu directionality  fullscreen hr image imagetools insertdatetime link lists media    nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount", //引入插件

        end_container_on_empty_block: true,
        paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
        powerpaste_word_import: "clean",
        // imagetools_toolbar: "editimage", // 图片控制的工具栏
        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: false, // 插入非中断空间；需要不间断的空间插件
        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;
        //   });
        // },
        convert_urls: false,
        images_upload_handler(blobInfo, success, failure, progress) {
          progress(0);
          let form = new FormData();
          form.append("image", blobInfo.blob());
          form.append("token", getToken());
          axios
            .post(`${urlConfig.baseURL}admin/uploadimg`, form)
            .then((res) => {
              console.log(res);
              if (res && res.data && res.status === 200) {
                const { code, data } = res.data;
                if (code === 0) {
                  const { url, name } = data[0];
                  success(`${urlConfig.baseURL}storage/${url}`);
                  progress(100);
                } else if (code >= 100 && code <= 104) {
                  failure("登录信息已失效，请重新登录！");
                } else {
                  failure("出现未知问题，刷新页面，或者联系程序员！");
                }
              } else {
                failure("出现未知问题，刷新页面，或者联系程序员");
              }
            })
            .catch((error) => {
              reject();
            });
        },
      },
    };
  },
  watch: {
    tinymceHtml: {
      handler(newV, oldV) {
        this.value = newV;
      },
      immediate:true,
      deep:true,
    },
  },
  mounted() {
    tinymce.init({});
  },
  methods: {
    setContent(value) {
      window.tinymce.get(this.tinymceId).setContent(value);
    },
    getContent() {
      window.tinymce.get(this.tinymceId).getContent();
    },
  },
};
</script>
<style lang="scss" scoped></style>
