<template>
  <Editor
    v-bind="$attrs"
    :id="id"
    ref="richText"
    :value="value"
    :class="['rich-text', isBorder ? 'is-border' : '']"
    :init="init"
    @input="updateValue"
    v-on="$listeners"
  />
</template>

<script>
import 'tinymce/tinymce';
import Editor from '@tinymce/tinymce-vue';

import 'tinymce/icons/default/icons';
import 'tinymce/themes/silver';
// 引入富文本编辑器主题的js和css
import 'tinymce/themes/silver/theme.min';
import 'tinymce/skins/ui/oxide/skin.min.css';
// 扩展插件
import 'tinymce/plugins/image';
import 'tinymce/plugins/link';
// import 'tinymce/plugins/code';
// import 'tinymce/plugins/table';
import 'tinymce/plugins/lists';
// import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/plugins/media'; // 插入视频插件
// import 'tinymce/plugins/template'; // 模板插件
// import 'tinymce/plugins/fullscreen'; // 全屏插件
// import 'tinymce/plugins/paste';
// import 'tinymce/plugins/preview'; // 预览插件
import 'tinymce/plugins/hr';
import 'tinymce/plugins/autoresize'; // 自动调整大小插件
import 'tinymce/plugins/ax_wordlimit'; // 字数限制插件

import { getRandomNumber } from '@/utils';
import { fileUpload } from '@/api/app';

export default {
  name: 'RichText',
  components: {
    Editor,
  },
  inheritAttrs: false,
  props: {
    inline: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '输入内容',
    },
    value: {
      type: String,
      required: true,
    },
    height: {
      type: [Number, String],
      default: 110,
    },
    isBorder: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      id: getRandomNumber(),
      init: {
        inline: this.inline,
        language_url: `${process.env.BASE_URL}tinymce/langs/zh_CN.js`,
        placeholder: this.placeholder,
        language: 'zh_CN',
        skin_url: `${process.env.BASE_URL}tinymce/skins/ui/oxide`,
        // height: this.height,
        content_css: `${process.env.BASE_URL}tinymce/skins/content/index.css`,
        min_height: 52,
        width: '100%',
        autoresize_bottom_margin: 0,
        plugins: 'link lists image hr media autoresize ax_wordlimit',
        /* eslint-disable max-len */
        toolbar:
          'fontselect fontsizeselect forecolor backcolor | underline | bold italic strikethrough alignleft aligncenter alignright | bullist numlist | image media | link blockquote hr',
        menubar: false,
        branding: false,
        statusbar: false,
        // 字数限制
        ax_wordlimit_num: 500,
        ax_wordlimit_callback(editor) {
          editor.execCommand('undo');
        },
        /**
         * 图片上传自定义逻辑函数
         * @param {object} blobInfo 文件数据
         * @param {Function} success 成功回调函数
         * @param {Function} fail 失败回调函数
         */
        images_upload_handler(blobInfo, success, fail) {
          let file = blobInfo.blob();
          const formData = new FormData();
          formData.append(file.name, file, file.name);
          fileUpload('Mid', formData)
            .then(({ file_info_list }) => {
              if (file_info_list.length > 0) {
                success(file_info_list[0].file_url);
              } else {
                fail('上传失败');
              }
            })
            .catch(() => {
              fail('上传失败');
            });
        },
        file_picker_types: 'media', // 文件上传类型
        /**
         * 文件上传自定义逻辑函数
         * @param {Function} callback
         * @param {String} value
         * @param {object} meta
         */
        file_picker_callback(callback, value, meta) {
          if (meta.filetype === 'media') {
            let filetype = '.mp3, .mp4';
            let input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', filetype);
            input.click();
            input.addEventListener('change', () => {
              let file = input.files[0];
              const formData = new FormData();
              formData.append(file.name, file, file.name);
              fileUpload('Mid', formData)
                .then(({ file_info_list }) => {
                  if (file_info_list.length > 0) {
                    callback(file_info_list[0].file_url);
                  } else {
                    callback('');
                  }
                })
                .catch(() => {
                  callback('');
                });
            });
          }
        },
      },
    };
  },
  methods: {
    updateValue(data) {
      this.$emit('update:value', data);
    },
  },
};
</script>

<style lang="scss" scoped>
.rich-text {
  :deep + .tox {
    .tox-sidebar-wrap {
      border: 1px solid $fill-color;
      border-radius: 4px;

      &:hover {
        border-color: #c0c4cc;
      }
    }

    &.tox-tinymce {
      border-width: 0;
      border-radius: 0;

      .tox-edit-area__iframe {
        background-color: $fill-color;
      }
    }

    &:not(.tox-tinymce-inline) .tox-editor-header {
      box-shadow: none;
    }
  }

  :deep &.is-border + .tox.tox-tinymce {
    border-width: 2px;
    border-radius: 10px;
  }
}
</style>
