<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import Editor from "@tinymce/tinymce-vue";

const props = defineProps({
  data: {
    type: String,
    required: true,
  }
});

const content = ref("");

const toolbar = [
  'undo redo',
  'blocks',
  'bold italic',
  'alignleft aligncenter alignright alignjustify',
  // 'indent outdent',
  'table',
  'image',
  'fullscreen'
];

const editInit = {
  language: 'zh_CN',
  skin: 'small',
  // icons: 'small',
  plugins: 'lists link image table code help wordcount fullscreen',
  contextmenu: false,
  toolbar: toolbar.join(' | '),
  menubar: false,
  branding: false,
  resize: true,
  file_picker_types: 'image',
  file_picker_callback: filePickerCallback,
  height: 260,
  init_instance_callback : function(editor:any){
    tinymce.value = editor
  }
}

/**
 * TinyMCE选择文件回调处理函数
 *
 * 参考 https://www.tiny.cloud/docs/tinymce/6/file-image-upload/#file_picker_callback
 * @param callback 回调函数
 */
function filePickerCallback(callback: any) {
  const input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/*');

  input.addEventListener('change', (e: any) => {
    const file = e.target.files[0];

    const reader = new FileReader();
    reader.addEventListener('load', () => {
      callback(reader.result, { title: file.name });
    });
    reader.readAsDataURL(file);
  });

  input.click();
}

const emits = defineEmits<{
  (e: "update:data", content: string): void;
  (e: "change", content: string): void;
}>();

function onChange() {
  emits("update:data", content.value);
  emits("change", content.value);
}

const editor = ref<any>(null)

const tinymce = ref<any>(null)

function onInit(event: any, editorIn: any) {
  editor.value = editorIn
}

function focus() {
  editor.value.focus()
}

function insert(text: string) {
  editor.value.insertContent(text)
}

function createErrorNotification() {
  if (tinymce.value) {
    tinymce.value.notificationManager.open({
      text: '该章节重复率过高',
      type: 'warning'
    });
  }
}

onMounted(() => {
  content.value = props.data;

  watch(
    () => props.data,
    (newData: string) => {
      content.value = newData
    }
  );
});

defineExpose({
  focus,
  insert,
  createErrorNotification
})
</script>

<template>
  <Editor
    api-key="ybn5lke39bgjhdehsamztepaxlch6nja25ekokjjav5nqdlq"
    :init="editInit"
    v-model="content"
    output-format="html"
    @change="onChange"
    @init="onInit"
  />
</template>