<template>
  <div :class="{fullscreen:fullscreen}" class="sk-tinymce-container" :style="{width:containerWidth}">
    <textarea :id="tinymceId" class="tinymce-textarea"></textarea>
    <div v-if="hasInit" class="editor-custom-btn-container">
      <slot></slot>
    </div>
  </div>
</template>

<script lang="ts">
import {
  computed, defineComponent, nextTick,
  onMounted, reactive, toRefs, watch, onActivated,
  onDeactivated, onBeforeUnmount, provide,
} from 'vue'
import { ElMessage } from 'element-plus'
import plugins from './hooks/plugins'
import toolbar from './hooks/toolbar'
import load from './hooks/dynamicLoadScript'
const TinymceCDN = 'https://cdn.jsdelivr.net/npm/tinymce@5.8.1/tinymce.min.js'
export default defineComponent({
  name: 'SkTinymce',
  props: {
    toolbar: {
      type: Array,
      required: false,
      default: (): string[] => {
        return []
      },
    },
    width: {
      type: [Number, String],
      required: false,
      default: 'auto',
    },
    tinymceId: {
      type: String,
      default: 'vue-tinymce-' + +new Date(),
    },
    height: {
      type: [Number, String],
      required: false,
      default: 360,
    },
    modelValue: {
      type: String,
      default: '',
    },
    menubar: {
      type: String,
      default: 'file edit insert view format table',
    },
    options: {
      type: Object,
      default: () => ({

      }),
    },
    plugins: {
      type: Array,
      default: () => ([]),
    },
  },
  emits: ['update:modelValue', 'load'],
  setup(props, { emit }) {
    const states = reactive({
      hasInit: false,
      hasChange: false,
      fullscreen: false,
    })
    const languageTypeList = {
      'zh': 'zh_CN',
      'es': 'es_MX',
      'ja': 'ja',
      'en': 'en',
    }

    function initTinymce () {
      const delArr = ['setup', 'init_instance_callback', 'toolbar', 'height', 'menubar', 'plugins', 'selector']
      let op = {
        // images_upload_url: uploadUrl,
        selector: `#${props.tinymceId}`,
        language: languageTypeList['zh'],
        language_url: 'https://cdn.jsdelivr.net/npm/tinymce-i18n@19.2.11/langs/zh_CN.js',
        height: props.height,
        body_class: 'panel-body ',
        object_resizing: false,
        toolbar: props.toolbar.length > 0 ? props.toolbar : toolbar,
        menubar: props.menubar,
        plugins: props.plugins.length > 0 ? props.plugins : plugins,
        end_container_on_empty_block: true,
        powerpaste_word_import: 'clean',
        code_dialog_height: 450,
        code_dialog_width: 1000,
        advlist_bullet_styles: 'square',
        advlist_number_styles: 'default',
        imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
        default_link_target: '_blank',
        link_title: false,
        nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
        init_instance_callback: editor => {
          provide('editorInstance', editor)
          provide('id', props.tinymceId)
          if (props.modelValue) {
            editor.setContent(props.modelValue)
          }
          states.hasInit = true
          emit('load', { tinymceId: props.tinymceId, editor })
          editor.on('NodeChange Change KeyUp SetContent', () => {
            states.hasChange = true
            emit('update:modelValue', editor.getContent())
          })
        },
        setup (editor) {
          editor.on('FullscreenStateChanged', e => {
            states.fullscreen = e.state
          })
        },
      }
      for (const key in props.options) {
        if(delArr.includes(key)) {
          delete props.options[key]
        }
      }
      (window as any).tinymce.init({ ...op, ...props.options })
    }

    function init () {
      load(TinymceCDN, err => {
        if (err) {
          ElMessage.warning('加载出错,请检查网络！')
          return
        }
        initTinymce()
      })
    }

    function destroyTinymce() {
      const tinymce = (window as any).tinymce.get(props.tinymceId)
      if (states.fullscreen) {
        tinymce.execCommand('mceFullScreen')
      }
      if (tinymce) {
        tinymce.destroy()
      }
    }

    const containerWidth = computed(() => {
      const width = props.width.toString()
      if (/^[\d]+(\.[\d]+)?$/.test(width)) { // matches `100`, `'100'`
        return `${width}px`
      }
      return width
    })

    watch(() => props.modelValue, val => {
      if (!states.hasChange && states.hasInit) {
        nextTick(() =>
          (window as any).tinymce.get(props.tinymceId).setContent(val || ''))
      }
    }, { deep: true })
    onMounted(() => {
      init()
    })
    onActivated(() => {
      if ((window as any).tinymce) {
        initTinymce()
      }
    })
    onDeactivated(() => {
      destroyTinymce()
    })
    onBeforeUnmount(() => {
      destroyTinymce()
    })

    return {
      ...toRefs(states),
      containerWidth,
    }
  },
})
</script>
