<template>
  <editor v-model="content" tag-name="div" :init="init" />
</template>
<script setup>
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import { ref, watch } from "vue";
import "tinymce/themes/silver/theme"; // 引用主题文件
import "tinymce/icons/default"; // 引用图标文件
import "tinymce/models/dom";
// tinymce插件可按自己的需要进行导入
// 更多插件参考：https://www.tiny.cloud/docs/plugins/
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/autosave";
import "tinymce/plugins/charmap"; // 特殊字符
import "tinymce/plugins/code"; // 查看源码
import "tinymce/plugins/codesample"; // 插入代码
import "tinymce/plugins/directionality";
import "tinymce/plugins/emoticons";
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help";
import "tinymce/plugins/image"; // 插入上传图片插件
import "tinymce/plugins/importcss"; //图片工具
import "tinymce/plugins/insertdatetime"; //时间插入
import "tinymce/plugins/link";
import "tinymce/plugins/lists"; // 列表插件
import "tinymce/plugins/media"; // 插入视频插件
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/pagebreak"; //分页
import "tinymce/plugins/preview"; // 预览
import "tinymce/plugins/quickbars";
import "tinymce/plugins/save"; // 保存
import "tinymce/plugins/searchreplace"; //查询替换
import "tinymce/plugins/table"; // 插入表格插件
import "tinymce/plugins/template"; //插入模板
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount"; // 字数统计插件
import "../assets/indent2em/plugin.js";
import { uploadFile, base64toBlob } from "@/api/system/oafile";
import "mammoth/mammoth.browser.js";
import mammoth from "mammoth";
import axios from "axios";
import { importWord } from "@/api/editor1";
// v-model
const props = defineProps({
  modelValue: String,
});
const apiUrl = ref(
  import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload"
);
const credentials = ref(true);
const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:modelValue"]);
const example_image_upload_handler = (blobInfo, progress) =>
  new Promise((resolve, reject) => {
    var formData;
    formData = new FormData();
    var file = blobInfo.blob(); //转化为易于理解的file对象
    formData.append("file", file, file.name);
    // uploadImg 就是引用的请求方法
    uploadFile(formData)
      .then((res) => {
        if (res.code == 200) {
          resolve(res.data.url);
          // 返回值根据实际返回写，根据需求处理
        }
      })
      .catch((err) => {});
  });
// 配置
const init = {
  selector: "#conTextarea",
  language_url: "/tinymce/langs/zh-Hans.js", // 中文语言包路径
  language: "zh-Hans",
  skin_url: "/tinymce/skins/ui/oxide", // 编辑器皮肤样式
  content_css: "/tinymce/skins/content/default/content.min.css",
  menubar: false, // 隐藏菜单栏
  autoresize_bottom_margin: 50,
  images_upload_base_path: "/",
  // images_upload_url:
  //   import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
  images_upload_handler: example_image_upload_handler,
  max_height: 500,
  min_height: 450,
  // height: 320,
  toolbar_mode: "none",
  selector: ".TinyMceTextEditor",
  // contextmenu
  plugins:
    " indent2em contextmenu wordcount visualchars visualblocks template searchreplace save quickbars preview  pagebreak nonbreaking media insertdatetime importcss image help fullscreen directionality codesample code charmap link code table lists advlist anchor autolink autoresize autosave image",
  toolbar:
    " formats undo redo  fontsizeselect fontselect ltr rtl searchreplace media | indent2em  outdent indent aligncenter alignleft alignright alignjustify lineheight underline quicklink h2 h3 blockquote numlist bullist table removeformat forecolor backcolor bold italic strikethrough hr link preview fullscreen |customUploadBtn ",
  content_style: "p {margin: 5px 0; font-size: 14px}",

  fontsize_formats: "12px 14px 16px 18px 24px 36px 48px 56px 72px",
  font_formats:
    "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方= PingFang SC, Microsoft YaHei, sans- serif; 宋体 = simsun, serif; 仿宋体 = FangSong, serif; 黑体 = SimHei, sans - serif; Arial = arial, helvetica, sans - serif;Arial Black = arial black, avant garde;Book Antiqua = book antiqua, palatino; ",
  branding: false,
  contextmenu: "paste | link image inserttable | cell row column deletetable",
  quickbars_selection_toolbar:
    "bold italic | quicklink h2 h3 blockquote quickimage quicktable",
  //视频
  file_picker_types: "media",
  // menubar: "insert",
  elementpath: false,
  resize: false, // 禁止改变大小
  statusbar: false, // 隐藏底部状态栏
  //视频
  file_picker_callback: function (cb, value, meta) {
    if (meta.filetype == "media") {
      //创建一个隐藏的type=file的文件选择input
      let input = document.createElement("input");
      input.setAttribute("type", "file");
      input.setAttribute("accept", ".mp4");
      input.onchange = function () {
        let file = this.files[0]; //只选取第一个文件。如果要选取全部，后面注意做修改
        new Promise((resolve, reject) => {
          var formData;
          formData = new FormData();
          console.log("666", file);
          formData.append("file", file, file.name);
          // uploadImg 就是引用的请求方法
          console.log("745", formData);
          var extension = file.name.slice(
            ((file.name.lastIndexOf(".") - 1) >>> 0) + 2
          );
          console.log("745", extension);
          if (extension == "mp4") {
            uploadFile(formData)
              .then((res) => {
                if (res.code == 200) {
                  // 返回值根据实际返回写，根据需求处理
                  cb(res.data.url, {
                    text: res.data.url,
                    title: res.data.name,
                  });
                }
              })
              .catch((err) => {});
          } else {
            alert("请上传视频文件!");
          }
        });
      };
      //触发点击
      input.click();
    }
  },
  setup: function (editor) {
    // 注册自定义按钮
    editor.ui.registry.addButton("customUploadBtn", {
      text: "上传Word",
      onAction: function () {
        var input = document.createElement("input");
        input.type = "file";
        input.accept = ".doc,.docx";
        // 执行上传文件操作
        input.addEventListener("change", handleFileSelect, false);

        //获取上传文件base64数据
        function arrayBufferToBase64(arrayBuffer) {
          var binary = "";
          var bytes = new Uint8Array(arrayBuffer);
          var len = bytes.byteLength;
          for (var i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          return window.btoa(binary);
        }

        function handleFileSelect(event) {
          var file = event.target.files[0];
          console.log("file", file);
          var fromDataf = new FormData();
          fromDataf.append("file", file);
          //获取上传文件后缀，如果是docx格式，则使用mammoth来进行解析，
          //如果不是则访问后台，将文件传输流base64传递到后台
          //生成文件，然后用java解析doc，并返回到前台
          var extension = file.name.slice(
            ((file.name.lastIndexOf(".") - 1) >>> 0) + 2
          );
          if (extension === "docx") {
            readFileInputEventAsArrayBuffer(event, function (arrayBuffer) {
              var base64Data = arrayBufferToBase64(arrayBuffer);
              console.log(base64Data);
              mammoth
                .convertToHtml({ arrayBuffer: arrayBuffer })
                .then(displayResult, function (error) {
                  console.error(error);
                });
            });
          } else if (extension === "doc") {
            importWord(fromDataf).then((res) => {
              proxy.$modal.loading("上传中，请稍后...");
              console.log(res);
              var result = res.data;
              tinymce.activeEditor.setContent(result);
              proxy.$modal.closeLoading();
            });
            // readFileInputEventAsArrayBuffer(event, function (arrayBuffer) {
            //   //base64文件流
            //   var base64Data = arrayBufferToBase64(arrayBuffer);
            //   var result = "后台请求";
            //   // alert(result);
            //   // console.log(base64Data);
            //   // alert("请上传后缀名为.docx的文件！");
            // });
            // //tinymce的set方法将内容添加到编辑器中
          }
        }

        function displayResult(result) {
          //tinymce的set方法将内容添加到编辑器中
          tinymce.activeEditor.setContent(result.value);
        }

        function readFileInputEventAsArrayBuffer(event, callback) {
          var file = event.target.files[0];
          var reader = new FileReader();
          reader.onload = function (loadEvent) {
            var arrayBuffer = loadEvent.target.result;
            callback(arrayBuffer);
          };
          reader.readAsArrayBuffer(file);
        }

        // 触发点击事件，打开选择文件的对话框
        input.click();
      },
    });
  },
};
tinymce.init({}); // 初始化
// 图片

////////////////////////////////////////////////////
const content = ref(props.modelValue);
watch(props, (newVal) => (content.value = newVal.modelValue));
watch(content, (newVal) => emit("update:modelValue", newVal));
</script>
<style>
.tox-tinymce-aux {
  z-index: 9999 !important;
}
</style>
