<template>
  <div>
    <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

    function init() {
      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: '宋体=SimSun;黑体=SimHei;微软雅黑=Microsoft Yahei;微软正黑体=Microsoft JhengHei;楷体=KaiTi;新宋体=NSimSun;方正仿宋_GB2312=FangZhengFangSong_GB2312;方正小标宋=FangZhengXiaoBiaoSongJian;幼圆=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: '初号=56px 小初=48px 一号=34px 小一=32px 二号=29px 小二=24px 三号=21px 小三=20px 四号=18px 小四=16px 五号=14px 小五=12px 六号=10px 小六=8px 七号=7px 八号=6px',
        plugins: props.plugins.join(' '),
        content_style: 'body { font-family:方正仿宋_GB2312;font-size:21px;line-height:37px}',

        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;
        },
        // 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);
        //   }
        // }
      };
      tinymce.init(Object.assign(options, 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();
    })

    return {
      content
    }
  }

})
</script>
