<template>
  <div class="tinymce">
    <Editor v-model="myValue" :init="init" :disabled="disabled"></Editor>
  </div>
</template>

<script>
  import {
    uploads
  } from '@/api/uploads.js'
  import tinymce from "tinymce/tinymce";
  import Editor from "@tinymce/tinymce-vue";
  import "tinymce/skins/ui/oxide/skin.css";
  import "@/assets/tinymce/langs/zh_CN";
  import "tinymce/themes/silver/theme";
  import "tinymce/plugins/media";
  import "tinymce/plugins/lists";
  import "tinymce/plugins/table";
  import "tinymce/plugins/hr";
  import "tinymce/plugins/autolink";
  import "tinymce/plugins/help";
  import "tinymce/plugins/visualblocks";
  import "tinymce/plugins/fullscreen";
  import "tinymce/plugins/textpattern";
  import "tinymce/plugins/contextmenu";
  import "tinymce/plugins/wordcount";
  import "tinymce/plugins/colorpicker";
  import "tinymce/plugins/textcolor";
  import "tinymce/icons/default"
  import 'tinymce/plugins/code'
  import "tinymce/plugins/image"
  import "tinymce/plugins/imagetools"
  import "/public/tinymce/plugins/axupimgs/plugin.js"
  import 'tinymce/plugins/media'
  export default {
    components: {
      Editor
    },
    props: {
      height: {
        type: Number,
        default: 300,
      },
      value: {
        type: String,
        default: "",
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      plugins: {
        type: [String, Array],
        default: "code image axupimgs media paste preview searchreplace autolink directionality visualblocks visualchars fullscreen template codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave ",
      },
      toolbar: {
        type: [String, Array],
        default: ` undo redo restoredraft | code | image | axupimgs | media | imagetools | assignment | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough  anchor | alignleft aligncenter alignright alignjustify outdent indent |
                styleselect formatselect fontselect fontsizeselect | table charmap emoticons hr pagebreak | bullist numlist | blockquote subscript superscript removeformat |
                 insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter`,
      },
      menubar: {
        type: String,
        default: "edit insert view format table CardBtn",
      },
    },
    data() {
      return {
        myValue: this.value,
        showImg: false,
        imgUploadUrl: `${process.env.VUE_APP_BASE_API}/api/admin/upload-file`,
        init: {
          language_url: "@/asset/tinymce/langs/zh_CN.js", // 这里需要单独处理
          language: "zh_CN",
          height: this.height,
          plugins: this.plugins,
          fontsize_formats: "8px 10px 12px 14px 16px 18px 24px 28px 36px",
          toolbar: this.toolbar,
          branding: false,
          menubar: this.menubar,
          // 图片上传三个参数，图片数据，成功时的回调函数，失败时的回调函数
          images_upload_url: this.imgUploadUrl,
          images_upload_handler: (blobInfo, success, failure) => {
            this.handleImgUpload(blobInfo, success, failure);
          },
          file_picker_types: 'media',
          file_picker_callback: function(cb, value, meta) {
             if(meta.filetype == 'media'){
               let input = document.createElement('input');//创建一个隐藏的input
               input.setAttribute('type', 'file');
               let that = this;
               input.onchange = function(){
                  let file = this.files[0]
                  let formdate = new FormData();
                  formdate.append("file", file); //imageFile文件名和后端统一
                  uploads(formdate).then(res => {
                    if (res) {
                      let url = res.url;
                      cb(url)
                      // success(url); //回显url
                    } else {
                      // failure(res.errmsg);
                      this.$message.error(res.errmsg);
                    }
                  })
                  // this.handleVideoUpload(file, cb)
                 // let file = this.files[0];//选取第一个文件
                 // that.uploadVideo(that.qiniuToken, file, 'video'); // 上传视频拿到url
                 // if(that.uploaded){
                 //   callback(that.resVideo, { title: file.name }) //将url显示在弹框输入框中
                 // }else{
                 //   setTimeout(()=>{
                 //     callback(that.resVideo, { title: file.name })
                 //   },2000)
                 // }
               }
               //触发点击
               input.click();
             }
          }

          // setup: (editor) => {
          //   let _this = this
          //   //定义一个名为 assignment 的toolbar
          //   editor.ui.registry.addButton('assignment', {
          //     text: `<i class="el-icon-position" style="font-size: 16px">上传</i>`,
          //     // tooltip: '图片上传',
          //     onAction: () => {
          //       this.showImg = true
          //       // _this.showEdit = true
          //     },
          //   })
          // },

          //此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
          //如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
          // images_upload_handler: (blobInfo, success, failure) => {
          //   const img = 'data:image/jpeg;base64,' + blobInfo.base64()
          //   success(img)
          // },
        },
      };
    },
    methods: {
      updateshow(val) {
        this.showImg = val
      },
      imageSuccessCBK(arr) {
        console.log("arr", arr)
        arr.forEach(
          (v) => (this.myValue += `<img class="wscnph" src="${v.url}" >`)
        );
      },
      handleImgUpload(blobInfo, success, failure) {
        console.log("我要上传", blobInfo);
        let self = this;
        let file = blobInfo.blob();
        const isLt2M = file.size / 1024 < 2048;
        if (!isLt2M) {
          failure("上传失败，图片不可超过2M!");
          return false;
        }
        let formdate = new FormData();
        formdate.append("file", blobInfo.blob()); //imageFile文件名和后端统一
        uploads(formdate).then(res => {
          if (res) {
            let url = res.url;
            success(url); //回显url
          } else {
            failure(res.errmsg);
            this.$message.error(res.errmsg);
          }
        })
      },
      handleVideoUpload(file, success, failure) {
        console.log("我要上传", blobInfo);
        let formdate = new FormData();
        formdate.append("file", file); //imageFile文件名和后端统一
        uploads(formdate).then(res => {
          if (res) {
            let url = res.url;
            success(url); //回显url
          } else {
            failure(res.errmsg);
            this.$message.error(res.errmsg);
          }
        })
      }
    },
    computed: {},
    mounted() {
      tinymce.init({});
    },
    watch: {
      value(newValue) {
        this.myValue = newValue;
      },
      myValue(newValue) {
        this.$emit("input", newValue);
      },
    },
  };
</script>

<style scoped lang="scss">
  .tinymce {
    position: relative;

    &__upload {
      z-index: 2;
      position: absolute;
      right: 4px;
      top: 0px;
    }

    ::v-deep .tox.tox-tinymce.tox-fullscreen {
      z-index: 0
    }
  }
</style>
