<template>
  <div>
    <editor ref="editor" v-model="content" :init="init" @dblclick="ondblclick" @click="onclick()" @mousedown="onclick" />
    <el-dialog :append-to-body="true" :visible.sync="dialogFileVisible" width="1000px" :title="titles[type]">
      <dk-attachment ref="attachment" :type="type" @change="onChange" />
      <div style="text-align: center">
        <el-button type="primary" :disabled="chooseFileList.length===0" @click="onSubmit()">确定</el-button>
        <el-button @click="dialogFileVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import DkAttachment from '../../DkForm/DkAttachment/index'
import init from '../../DkForm/DkTinyEditor/config'
import Editor from '@tinymce/tinymce-vue'
import './plugin/showImage'
import './plugin/ImageSize'

export default {
  name: 'DkTinyEditor',
  components: {
    Editor,
    DkAttachment
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 初始化配置
      content: this.value,
      init: init,
      dialogFileVisible: false,
      type: 1,
      chooseFileList: [],
      titles: {
        1: '选择图片',
        2: '选择音频',
        3: '选择视频'
      }
    }
  },
  computed: {
    tiny() {
      return this.$refs.editor.editor
    }
  },
  watch: {
    value(newValue) {
      this.content = newValue
    },
    content(newValue) {
      this.$emit('input', newValue)
    }
  },
  mounted() {
    this.tiny.on('showImage', () => {
      this.type = 1
      this.dialogFileVisible = true
    })
  },
  methods: {
    onChange(_, chooseFileList) {
      this.chooseFileList = chooseFileList
    },
    onclick() {
      console.log('onclick')
    },
    ondblclick(editor) {
      console.log(editor)
    },
    test() {
      console.log(this.$refs.editor)
    },
    onSubmit() {
      const list = this.$refs.attachment.chooseFileList
      let html = ''
      for (let i = 0; i < list.length; i++) {
        html += '<img src="' + list[i].url + '" alt="" width="100%">'
      }
      this.tiny.insertContent(html)

      this.dialogFileVisible = false
      this.$refs.attachment.refreshList()
    }
  }
}
</script>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 3000 !important;
}
</style>
