<template>
  <div>
    <article
      :id="id"
      v-loading="loading"
      :style="styles"
      element-loading-text="数据上传中，请稍后"
      element-loading-spinner="el-icon-loading"
    >
      <div v-show="isEmpty && !edit" class="text-edit">
        {{ emptyText }}
        <el-button type="text" @click="ImmediateAddition">{{ inputButton }}</el-button>
      </div>
      <div v-show="edit" class="editArticle" :class="fullScreen ? 'fullScreen' : ''">
        <span v-show="fullScreen" class="changeSizeBtn" @click="changeSize">
          <svg-icon
            icon-class="icon-sx"
            class="icon"
          />
        </span>
        <span v-show="!fullScreen" class="changeSizeBtn" @click="changeSize">
          <svg-icon
            icon-class="icon-qp"
            class="icon"
          />
        </span>
        <editor :id="'tinymce_'+id" v-model="inputValue" :class="'tinymce_'+id" :init="init" @input="changeText" />
      </div>
      <div v-show="!isEmpty && !edit">
        <el-tooltip effect="dark" content="单击‘编辑’" placement="bottom">
          <pre class="text-pre" @click="ImmediateAddition" v-html="handlerText(value)" />
        </el-tooltip>
      </div>
      <div :id="'inputUpload_'+id" style="display: none" @click.stop="blur_textarea" />
      <div v-show="edit" class="control">
        <el-button size="small" @click="edit=false">取消</el-button>
        <el-button type="primary" size="small" @click.stop="blur_textarea">确定</el-button>
      </div>
    </article>
  </div>
</template>
<script>
import { getContainImgHTMLNode } from '@/utils/handleTinymce'
import { keepLastIndex, uploadImg } from '@/utils/util'
import tinymce from 'tinymce/tinymce'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/themes/silver/theme'
import 'tinymce/icons/default/icons'
import 'tinymce/plugins/table'

import 'tinymce/plugins/image'
import 'tinymce/plugins/media'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import 'tinymce/skins/ui/oxide/skin.css'

export default {
  components: {
    Editor
  },
  props: {
    styles: {
      type: Object,
      default: () => {
        return { padding: '0 30px 20px 30px' }
      },
      required: false
    },
    id: {
      type: String,
      default: '',
      required: true
    },
    value: {
      type: String,
      default: '',
      required: false
    },
    height: {
      type: Number,
      default: 200,
      required: false
    },
    emptyText: {
      type: String,
      default: '',
      required: false
    },
    inputButton: {
      type: String,
      default: '',
      required: false
    }
  },
  data() {
    return {
      fullScreen: false,
      loading: false,
      inputValue: '',
      edit: false,
      init: {
        auto_focus: true,
        language_url: '/tinymce/langs/zh_CN.js',
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide', // 编辑器需要一个skin才能正常工作，所以要设置一个skin_url指向之前复制出来的skin文件
        height: this.height,
        browser_spellcheck: true, // 拼写检查
        branding: false, // 去水印
        elementpath: false, // 禁用编辑器底部的状态栏
        statusbar: false, // 隐藏编辑器底部的状态栏
        paste_data_images: true, // 允许粘贴图像
        menubar: false, // 隐藏最上方menu
        fontsize_formats: '14px 16px 18px 20px 24px 26px 28px 30px 32px 36px', // 字体大小
        file_picker_types: 'image',
        images_upload_credentials: true,
        plugins: 'lists table textcolor wordcount contextmenu', // 引入插件
        toolbar: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent table | undo redo | removeformat formatselect ｜ fullscreen',
        table_toolbar: 'tableprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol | tablemergecells tablesplitcells ｜ fullscreen'
      }
    }
  },
  computed: {
    isEmpty() {
      return this.inputValue === null || this.inputValue.replace(/\s+/g, '') === ''
    }
  },
  watch: {
    value: {
      handler(newV, oldV) {
        this.inputValue = newV
      },
      immediate: true
    }
    // inputValue: {
    //   handler(newV, oldV) {
    //     this.resetImgSrc(newV)
    //   },
    //   immediate: true
    // }
  },
  mounted() {
    // 失去焦点保存功能
    // document.body.addEventListener('click', e => {
    //   if (!document.getElementById(this.id)) {
    //     return false
    //   }
    //   const isContain = document.getElementById(this.id).contains(e.target)
    //   if (!isContain) {
    //     document.getElementById(`inputUpload_${this.id}`).click()
    //   }
    // })
    tinymce.init({ selector: `.tinymce_${this.id}` })
  },
  methods: {
    async resetImgSrc(str) {
      if (!str) return
      let newStr = str
      const imgReg = /<img.*?(?:>|\/>)/gi
      const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
      const imgArr = newStr.match(imgReg)
      imgArr && imgArr.map(async t => {
        const src = t.match(srcReg)
        if (src[1] && src[1].includes('data:image')) {
          const newImgUrl = await uploadImg(src[1])
          newStr = newStr.replace(src[1], newImgUrl)
          this.inputValue = newStr
          // 光标最后
          this.$nextTick(() => {
            const ifra = document.getElementById(`tinymce_${this.id}_ifr`)
            keepLastIndex(ifra.contentWindow.document.getElementById(`tinymce`), ifra.contentWindow)
          })
        }
      })
    },
    async resetImgSrcAll(str) {
      if (!str) return str
      let newStr = str
      const imgReg = /<img.*?(?:>|\/>)/gi
      const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
      const imgArr = newStr.match(imgReg)
      imgArr && imgArr.map(async t => {
        const src = t.match(srcReg)
        if (src[1] && src[1].includes('data:image')) {
          const newImgUrl = await uploadImg(src[1])
          console.log(newImgUrl)
          newStr = newStr.replace(src[1], newImgUrl)
          // // 光标最后
          // this.$nextTick(() => {
          //   const ifra = document.getElementById(`tinymce_${this.id}_ifr`)
          //   keepLastIndex(ifra.contentWindow.document.getElementById(`tinymce`), ifra.contentWindow)
          // })
        }
      })
      return newStr
    },
    ImmediateAddition() { // 立即添加（编辑）
      this.edit = true
    },
    changeText(e) { // 富文本内容改变
      this.inputValue = e
    },
    async blur_textarea() {
      if (this.edit) {
        this.loading = true
        try {
          this.inputValue = await getContainImgHTMLNode(this.inputValue)
        } catch (error) {
          this.loading = false
          throw error
        }
        this.loading = false
        this.edit = false
        const val = await this.resetImgSrcAll(this.inputValue)
        this.$emit('update:value', val)
        this.$emit('change', val)
      }
    },
    handlerText(val) {
      if (val) {
        const reg = new RegExp(/<\/?p[^>]*>/gi)
        return val.replace(reg, '')
      }
    },
    changeSize() {
      this.fullScreen = !this.fullScreen
    }
  }
}
</script>
<style scoped lang="less">
.editArticle {
  position: relative;
  .changeSizeBtn {
    position: absolute;
    top: 3px;
    right: 0px;
    z-index: 1000;
    height: 34px;
    width: 24px;
    text-align: center;
    line-height: 34px;
    border-radius: 3px;
    .icon {
      color: #409eff;
      font-weight: 700;
      font-size: 18px;
    }
    &:hover {
      background: #c8cbcf;
      border: 0;
      box-shadow: none;
    }
  }
}
.fullScreen {
  position: fixed;
  top: 0px;
  bottom: 0;
  left: 225px;
  right: 0;
  z-index: 1000;
  height: 100vh!important;
  /deep/.tox-tinymce {
    height: 100vh!important;
  }
}
.text-edit {
  color: #666666;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.text-pre {
  white-space:pre-line;
  font-size: 14px;
  color: #333B4A;
  cursor: pointer;
}
/deep/ textarea {
  width: calc(100% - 40px);
  margin: auto;
}
.control {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
