<template>
  <div class="tinymce-box">
    <editor v-model="myValue" :init="tinymceInit" :disabled="disabled" @onBlur="onBlur"></editor>
    <el-dialog
      title="上传"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="600px"
      append-to-body
    >
      <div class="FileUpload">
        <div v-for="(item, index) in fileList" :key="item" class="fileDiv">
          <img :src="item" alt />
          <div class="fileDivBg">
            <i class="el-icon-delete" @click="deleteFile(index)"></i>
          </div>
        </div>
        <el-upload
          class="avatar-uploader"
          :action="action+'/Upload/UploadImage'"
          :headers="myHeaders"
          multiple
          accept=".jpg, .jpeg, .png"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelInsert">取 消</el-button>
        <el-button type="primary" @click="insertImage">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Editor from "@tinymce/tinymce-vue";
  import tinymce from "../../static/tinymce/tinymce"; //tinymce默认hidden，不引入不显示
  import "../../static/tinymce/themes/silver";
  import "../../static/tinymce/plugins/media"; // 插入视频插件
  import "../../static/tinymce/plugins/lists"; // 列表插件
  import "../../static/tinymce/plugins/link";
  import "../../static/tinymce/plugins/lineheight/plugin";
  import '../../static/tinymce/icons/default'

  export default {
    components: {
      Editor,
    },
    name: "tinymce",
    props: {
      disabled: {
        type: Boolean,
        default: false,
      },
      val: {
        type: String,
        default: "",
      },
      valIndex: {
        type: Number,
        default: -1,
      },
      boxHeight: {
        type: Number,
        default: 600,
      },
      mediaDisabled: {
        type: Boolean,
        default: false,
      },
    },
    //监听数据实现传参双向绑定
    watch: {
      val (val) {
        this.myValue = val;
      },
      myValue (val) {
        if (this.valIndex >= 0) {
          this.$emit("getval", val, this.valIndex);
        } else {
          this.$emit("getval", val);
        }
      },
    },
    data () {
      return {
        action: '',
        myValue: "",
        tinymceInit: {},
        dialogVisible: false,
        myHeaders: {
          'Authorization': "Bearer "
        },
        fileList: [],
      };
    },
    created () {
      let that = this;
      this.tinymceInit = {
        automatic_uploads: false,
        language_url: "./static/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        skin_url: "./static/tinymce/skins/ui/oxide",
        content_css: "./static/tinymce/skins/content/default/index.css",
        height: this.boxHeight,
        plugins: "lists media link lineheight",
        toolbar: this.mediaDisabled
          ? "undo redo | formatselect fontselect | lineheight fontsizeselect bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists  table | removeformat"
          : "imageUpload link  | undo redo | formatselect fontselect | lineheight fontsizeselect bold italic forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists  table | removeformat",
        font_formats: "Microsoft Yahei",//| media
        fontsize_formats: "12px 14px 16px 18px 20px 28px 32px 40px",
        lineheight_formats: "20px 24px 28px 32px 36px 40px",
        menu: {
          file: { title: "文件", items: "newdocument" },
          edit: {
            title: "编辑",
            items: "undo redo | cut copy paste pastetext | selectall",
          },
          insert: {
            title: "插入",
            items: "link | template hr",
          },
          format: {
            title: "格式",
            items: "bold italic underline strikethrough superscript subscript | formats | removeformat",
          },
        },
        setup: (editor) => {
          editor.ui.registry.addButton("imageUpload", {
            tooltip: "插入图片",
            icon: "image",
            onAction: () => {
              that.dialogVisible = true;
            },
          });
        },
        media_alt_source: false, //媒体弹框显示隐藏资源备用地址输入框
        media_poster: false, //媒体弹框显示隐藏资源备用地址输入框
        media_url_resolver: function(data, resolve /*, reject*/) {
          if (data.width === undefined) {
            data.width = 500;
          }
          if (data.height === undefined) {
            data.height = 400;
          }
          if (data.url.indexOf("video.xjtlu.edu.cn") !== -1) {
            var embedHtml = `<iframe frameborder="0" scrolling="auto" marginheight="0" marginwidth="0" allowfullscreen msallowfullscreen allow="fullscreen"
                                      width="${data.width}"
                                      height="${data.height}"
                                      src="${data.url}">`;
            resolve({ html: embedHtml });
          } else {
            resolve({ html: "" });
          }
        },
      };
      this.myValue = this.val;
    },
    methods: {
      cancelInsert () {
        this.dialogVisible = false;
        this.fileList = [];
      },
      insertImage () {
        this.fileList.forEach((item) => {
          let myHTML = '<img style="max-width:100%!important" src="' + item + '" />';
          // tinyMCE.execCommand("mceInsertContent", false, myHTML);
          this.myValue += myHTML;
        });
        this.dialogVisible = false;
        this.fileList = [];
      },
      handleAvatarSuccess (res, file) {
        if (res.code === 200) {

          if (res.internalCode && res.internalCode == 'Information') {
            this.$message.closeAll();
            this.$message.error(res.message);
          }
          else {

            this.fileList = this.fileList.concat(res.data);
          }
        } else if (res.code === 401) {
          this.$message.closeAll();
          this.$message.error('登录已过期，请重新登录');
          router.push('/login');
        } else {
          this.$message.closeAll();
          this.$message.error(res.message);
        }

      },
      deleteFile (index) {
        this.fileList.splice(index, 1);
        this.$emit("validateBanner");
      },
      onBlur () {
        this.$emit("geTinymcetVal", this.myValue);
      },
    },
  };
</script>
<style lang="less">
.FileUpload {
  display: flex;
  flex-wrap: wrap;
  & > * {
    margin-right: 10px;
  }
  .fileDiv {
    width: 100px;
    height: 100px;
    line-height: 100px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    position: relative;
    &:hover {
      .fileDivBg {
        opacity: 1;
      }
    }
    img {
      width: 100%;
      display: inline-block;
      vertical-align: middle;
    }
    .fileDivBg {
      position: absolute;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
      text-align: center;
      color: #fff;
      opacity: 0;
      font-size: 20px;
      background-color: rgba(0, 0, 0, 0.5);
      transition: opacity 0.3s;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-icon-delete {
        cursor: pointer;
        height: 21px;
        line-height: 21px;
        margin: 0 5px;
      }
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
}
</style>
