<template>
  <div id="editor-component">
    <div class="editor-box">
      <div v-if="template" class="model-list" style="height: 550px">
        <div v-for="(item, index) in modelList" :key="index" class="model-item" @click="addDom(item.dom)" v-html="item.dom" />
      </div>
      <div :style="template ? 'width: 63%' : 'width: 100%'">
        <!-- <el-table v-loading="true" style="width: 100%; height:100%"> -->
        <script :id="id" type="text/plain" style="width:100%;height: 100%;" />
        <!-- </el-table> -->
      </div>
    </div>

    <el-dialog
      class="dialog"
      title="预览"
      append-to-body
      :visible.sync="previewDialogShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="preview-container">
        <!-- <div class="preview-content" v-html="value" /> -->
        <Preview :value="{content: previewValue}" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
const UE = window.UE
import './addCustomize/addCustomizeCombox'
import { preview } from './addCustomize/addCustomizeButton'

// import axios from 'axios'

import Preview from '@/components/Preview/index.vue'

import { Loading } from 'element-ui'

import OSS from '@/utils/aliOSS'
import UUID from 'uuidjs'

export default {
  components: { Preview },
  props: {
    value: {
      type: String,
      default: ''
    },
    content: {
      type: String,
      default: ''
    },
    template: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      id: 'editor' + (new Date()).getTime(),
      hasChange: false,
      hasInit: false,
      ue: null,
      modelList: [
        {
          id: 1,
          dom: '<section style="display: flex;justify-content: center;"><section style="display: flex;flex-direction: column;align-items: center;"><section><img src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20191029/1572333131/61232800_0.png" alt="" style="display: block;max-width: 100%;" _src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20191029/1572333131/61232800_0.png"></section><section style="padding: 0 10px;border-top: 1px solid #df1223;border-bottom: 1px solid #df1223;margin-top: 3px;"><p style="margin: 0;text-align: center;font-size: 13px;color:#ff0000;line-height: 1.6;font-weight: 700;">不忘初心 砥砺前行</p></section></section></section>'
        },
        {
          id: 2,
          dom: '<section style="margin:0 10px;display: flex;justify-content: center;align-items: center;"><section style="display: flex;flex-direction:column;justify-content: center;align-items: center;padding: 18px;"><section style="display: flex;flex-direction:column;justify-content: center;align-items: center;border-radius: 10px;border: 1px solid RGB(225,7,7);padding: 10px;padding-bottom: 0;"><section style="flex-shrink: 0;align-self: flex-start;z-index: 2;display: flex;margin-bottom: 10px;align-items: center;"><section style="display: flex;padding-bottom: 1px;border-bottom: 1px solid RGB(225,7,7);"><p style="margin: 0;color: #333;padding-bottom: 4px;padding-right: 10px;border-bottom: 1px dashed RGB(225,7,7);">中国人民政治协商会议</p></section><img src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20200221/1582279829/91987200_0.png" alt="" style="vertical-align: middle;max-width: 100%;margin-left: -10px;" class="kolImg" _src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20200221/1582279829/91987200_0.png"></section><section style="padding:0 15px;box-sizing: border-box;"><p style="margin: 0px;text-align: left;font-size: 14px;color: #333;letter-spacing: 1.5px;line-height: 1.75;">中国人民政治协商会议（简称人民政协）是中国人民爱国统一战线的组织，是中国共产党领导的多党合作和政治协商的重要机构，是中国政治生活中发扬社会主义民主的一种重要形式。</p></section><section style="flex-shrink: 0;align-self: flex-end;"><img src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20200221/1582279829/91987200_1.png" alt="" style="vertical-align: middle;max-width: 100%;" class="kolImg" _src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20200221/1582279829/91987200_1.png"></section></section></section></section>'
        },
        {
          id: 3,
          dom: '<section style="display: flex;flex-direction: column;align-items: center;margin: 0 auto;overflow: hidden;box-sizing: border-box;width: 110px;height: 147px;background-image:url(https://editor-material.oss-cn-beijing.aliyuncs.com/style/20191029/1572333090/50547400_0.png);"><section style="width: 90px;margin-top: 30px;"><img src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20191029/1572333090/50547400_1.jpeg" style="max-width: 100%;vertical-align: middle;" class="KolImg" _src="https://editor-material.oss-cn-beijing.aliyuncs.com/style/20191029/1572333090/50547400_1.jpeg"></section><section><p style="margin: 0;text-align: center;line-height: 1.6;font-weight: 700;color: #e1313c;font-size: 13px;">长按扫码关注</p></section></section>'
        }
      ],
      previewDialogShow: false,
      previewValue: null
    }
  },
  watch: {
    value(val) {
      var that = this
      if (this.ue && !this.hasChange && this.hasInit) {
        this.$nextTick(() => {
          UE.getEditor(that.id).execCommand('insertHtml', val)
        })
      }
    },
    disabled(val) {
      if (val) {
        UE.getEditor(this.id).setDisabled('fullscreen')
      } else {
        UE.getEditor(this.id).setEnabled()
      }
    }
  },
  created() {
  },
  mounted() {
    var that = this
    preview(() => {
      that.previewValue = UE.getEditor(that.id).getContent()
      that.previewDialogShow = true
    })
    this.ue = UE.getEditor(that.id, {
      toolbars: [[
        // 'fullscreen', 'source', '|',
        'undo', 'redo', '|',
        'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
        'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
        'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
        'directionalityltr', 'directionalityrtl', 'indent', '|',
        'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
        'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
        'simpleupload', 'insertimage', 'emotion',
        // 'insertvideo',
        'background', '|',
        'horizontal', 'date', 'time', 'spechars', '|',
        'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
        'searchreplace'
      ]],
      imageUpload: that.uploader,
      videoUpload: that.videoUpload,
      // 拖拽自动上传
      autoUpload: that.autoUpload
    })
    this.ue.addListener('ready', function(editor) {
      that.hasInit = true
      // console.log(that.value)
      UE.getEditor(that.id, { autoHeightEnabled: false })
      that.ue.setHeight(500)
      // that.initEditor()
      if (that.value) that.ue.execCommand('insertHtml', that.value)
      if (that.disabled) that.ue.setDisabled('fullscreen')
    })
    this.ue.addListener('contentChange', function(editor) {
      that.hasChange = true
      that.$emit('input', that.ue.getContent())
      that.$emit('change', that.ue.getContent())
    })
  },
  methods: {
    addDom(dom) {
      var that = this
      if (that.hasInit) UE.getEditor(that.id).execCommand('insertHtml', dom)
    },
    uploader(form, callBack) {
      // const that = this
      var formData = new FormData(form)
      // const loadingInstance = Loading.service({ target: '#' + that.id, text: '文件上传中...' })
      this.upRequest(formData).then(res => {
        callBack(res)
        // loadingInstance.close()
      }).catch(() => {
        // loadingInstance.close()
      })
    },
    upRequest(formData) {
      const that = this
      const loadingInstance = Loading.service({ target: '#' + that.id, text: '文件上传中...' })
      // console.log(formData)
      // formData.forEach(item => {
      //   console.log(item)
      // })
      // return
      return new Promise((resolve, reject) => {
        // axios.post('http://120.77.82.246:6789/api/postUpLoadFiles', formData).then(res => {
        var file = formData[0]
        formData.forEach(item => {
          file = item
        })
        const suffix = file.name.split('.')[1]
        OSS(file, UUID.generate() + '.' + suffix).then(res => {
          resolve(res.url)
          loadingInstance.close()
        }).catch(() => {
          console.log('文件上传失败!')
          loadingInstance.close()
          reject()
        })
      })
    },
    videoUpload(uploader, files) {
      const that = this
      files.forEach(item => {
        const formData = new FormData()
        formData.append('file', item.source.source)
        that.upRequest(formData).then(res => {
          const response = {
            state: 'SUCCESS',
            url: res,
            type: item.type,
            original: ''
          }
          item.setStatus('COMPLETE')
          uploader.trigger('uploadSuccess', item, JSON.stringify(response))
        })
      })
    },
    autoUpload(file, callBack) {
      const that = this
      const formData = new FormData()
      formData.append('file', file)
      that.upRequest(formData).then(res => {
        callBack({ url: res })
      })
    }
  }
}
</script>

<style scoped>
#editor-component{
  line-height: normal;
}
.editor-box{
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.model-list{
  width: 35%;
  /* max-height: 100%; */
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
}
.model-list::-webkit-scrollbar{
  display: none;
}
.model-list .model-item:first-child{
  border-top: none;
}
.model-item{
  cursor: pointer;
  padding: 5px 10px;
  box-sizing: border-box;
  border-top: 1px dashed #ddd ;
}
.model-item:hover{
  box-shadow: 0 0 10px 2px #ececec;
}

.preview-container{
  width: 100%;
  display: flex;
  justify-content: center;
}
.preview-content{
  width: 375px;
  height: 667px;
  overflow: hidden;
  overflow-y: auto;
  border: 1px solid #dddddd;
  border-radius: 25px;
  box-sizing: border-box;
  user-select: none
}
.preview-content::-webkit-scrollbar {
  /*滚动条整体样式*/
  width : 3px;  /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.preview-content::-webkit-scrollbar-thumb {
/*滚动条里面小方块*/
  border-radius: 10px;
  box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.1);
  background   : #535353;
}
.preview-content::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  box-shadow   : inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 10px;
  background   : #ededed;
}
.dialog{
  z-index: 5000 !important;
  background: rgba(0, 0, 0, .3)
}

.el-loading-mask .is-fullscreen{
  z-index: 10000;
}
</style>

<style>
/* #editor-component .el-form-item--medium .el-form-item__content{
    line-height: 0 !important;
  }
#editor-component .el-form-item__content {
    line-height: 0 !important;
  } */
</style>
