<template>
  <div>
    <el-upload :http-request="handleUploadClick" action="#" class="inline-block">
      <el-button type="primary" :loading="uploading" style="margin-bottom: 4px;">上传word</el-button>
      <template #file><div style="display: none;"></div></template>
    </el-upload>
    <textarea :id="id">{{ content }}</textarea>
  </div>
</template>

<script>
import { defineComponent, onBeforeUnmount, onMounted, ref } from '@vue/composition-api';
import tinymce from "tinymce"
import request from '~/utils/request';
export default defineComponent({
  props: {
    'id': {
      type: String,
      default: `tiny-${Date.now()}-${~~(Math.random() * 10000)}`
    },
    'htmlClass': { default: '', type: String },
    'value': { default: '' },
    'plugins': {
      default: function () {
        return [
          'advlist autolink lists link image charmap preview anchor pagebreak',
          'searchreplace wordcount visualblocks visualchars code fullscreen',
          'insertdatetime media nonbreaking save table directionality',
          'template help emoticons'
        ];
      }, type: Array
    },
    toolbar1: { default: 'formatselect fontfamily fontsize |  bold italic  strikethrough  forecolor backcolor | link | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat', type: String },
    toolbar2: { default: '', type: String },
    other_options: {
      default: function () {
        return {};
      }, type: Object
    }
  },
  model: {
    event: 'update'
  },
  emits: ['update'],
  setup(props, context) {
    const content = ref('')
    let editor = null
    let checkerTimeout = null
    let isTyping = false
    let options = {
      selector: '#' + props.id,
      base_url: window.GLOBAL_CONFIG.origin + '/tiny',
      language: 'zh-Hans',
      // skin: false,
      toolbar1: props.toolbar1,
      toolbar2: props.toolbar2,
      font_family_formats: '宋体=宋体;黑体=SimHei;微软雅黑=Microsoft Yahei;微软正黑体=Microsoft JhengHei;楷体=KaiTi;新宋体=NSimSun;仿宋_GB2312=仿宋_GB2312;方正小标宋简体=方正小标宋简体;幼圆=YouYuan;隶书=LiSu;华文细黑=STXihei;华文楷体=STKaiti;华文宋体=STSong;华文仿宋=STFangsong;华文中宋=STZhongsong;Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbat',
      font_size_formats: '初号=42pt 小初=36pt 一号=26pt 小一=24pt 二号=22pt 小二=18pt 三号=16pt 小三=15pt 四号=14pt 小四=12pt 五号=10.5pt 小五=9pt 六号=7.5pt 小六=6.5pt 七号=5.5pt 八号=5pt',
      plugins: props.plugins.join(' '),
      content_style: 'body {  font-family:仿宋_GB2312;font-size:21px;line-height:37px; } .mce-content-body .mce-item-anchor:empty{display:none!important;} .divider{ height: 2px;border-top: 2px solid red;border-bottom: 6px solid red; }',
      paste_webkit_styles: 'all',
      menu: {
        file: { title: 'File', items: 'newdocument restoredraft | export print | deleteallconversations' },
        edit: { title: 'Edit', items: 'undo redo | cut copy paste pastetext | selectall | searchreplace' },
        view: { title: 'View', items: 'code | visualaid visualchars visualblocks | spellchecker | fullscreen | showcomments' },
        insert: { title: 'Insert', items: 'image link media addcomment pageembed template codesample inserttable | charmap emoticons hr | pagebreak nonbreaking anchor tableofcontents | insertdatetime' },
        format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript codeformat | styles blocks fontfamily fontsize align lineheight | forecolor backcolor | language | removeformat' },
        tools: { title: 'Tools', items: 'spellchecker spellcheckerlanguage | a11ycheck code wordcount' },
        table: { title: 'Table', items: 'inserttable | cell row column | advtablesort | tableprops deletetable' },
        help: { title: 'Help', items: 'help' }
      },
      autosave_restore_when_empty: true,
      init_instance_callback: (_editor) => {
        _editor.on('KeyUp', (e) => {
          submitNewContent();
        });
        _editor.on('Change', (e) => {
          if (_editor.getContent() !== props.value) {
            submitNewContent();
          }
        });
        _editor.on('init', (e) => {
          _editor.setContent(content.value);
          // emits('input', content.value);
        });
        editor = _editor;
        console.log('editor :>> ', editor);
      },
      // TODO: change here
      automatic_uploads: false,
      images_upload_handler: (blobInfo, progress) => {
        const file = blobInfo.blob();
        return request({
          // $type: 'upload',
          url: 'upload/main/file',
          data: {
            filedata: file
          },
          timeout: 1000 * 180,
          onUploadProgress(progressEvent) {
            progress(~~(progressEvent.loaded / progressEvent.total * 100 | 0))
          },
          transformRequest: [(data) => {
            const formData = new FormData()
            Object.keys(data).forEach(key => formData.append(key, data[key]))
            return formData;
          }]
        }).then(res => {
          if (res.code === '1') {
            return window.GLOBAL_CONFIG.oss + (res.data.url)
          } else {
            return ('')
          }
        })
      },
      // to solve a third party URL
      // paste_preprocess: (editor, args) => {
      //   if (/^https?\:\/\/.+(png|jpg)$/.test(args.content)) {
      //     args.content = uploadByThirdPartyUrl(args.content);
      //   }
      // }
      // smart_paste: false
    };
    function init(d) {

      tinymce.init(Object.assign(options, d, props.other_options));
    }

    function submitNewContent() {
      isTyping = true;
      if (checkerTimeout !== null) { clearTimeout(checkerTimeout); }
      checkerTimeout = setTimeout(() => {
        isTyping = false;
      }, 300);
      context.emit('update', editor.getContent());
    }

    onMounted(() => {
      content.value = props.value
      init()
    })

    onBeforeUnmount(() => {
      editor.destroy();
    })

    const uploading = ref(false)
    const handleUploadClick = ({ file }) => {
      uploading.value = true
      return request({
        url: '/openapi/word2html.php',
        data: { filedata: file },
        timeout: 1000 * 180,

        transformRequest: [(data) => {
          const formData = new FormData()
          Object.keys(data).forEach(key => formData.append(key, data[key]))
          return formData;
        }]
      }).then((res) => {
        const resData = res.data
        // console.log('content',resData.content)
        // editor.dom.addStyle(resData.style)
        editor.insertContent(`${resData.content}`)
        uploading.value = false
        return res
      })
    }

    return {
      content,
      handleUploadClick,
      uploading
    }
  }

})
</script>

<style scoped >
.divider {
  height: 12px;
  border-top: 2px solid red;
  border-bottom: 8px solid red;
}
</style>
