<template>
  <div>
    <div class="editor" :style="styles" ref="editor"></div>
    <!--    <div class="code">-->
    <!--      <el-button @click="openCode">源码</el-button>-->
    <!--    </div>-->


    <el-dialog title="编辑详情" :visible="codeShow" width="1100px" :close-on-click-modal="false" @close="codeShow = false"
               append-to-body>
      <textarea
        class="textarea"
        rows="50"
        cols="50"

        v-model="code"></textarea>

      <el-button @click="codeSuccess">完成</el-button>
    </el-dialog>
  </div>
</template>

<script>
import Editor from 'wangeditor'
import { htmlFormat } from './fromat'
import { getToken } from '../../utils/auth'
import axios from 'axios'

export default {
  name: 'Editor',
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: ''
    },
    /* 高度 */
    height: {
      type: Number,
      default: null
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null
    },
    meanArray: {
      // 自定义菜单
      type: Array,
      default: null
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },

  computed: {
    styles() {
      let style = {}
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`
      }
      if (this.height) {
        style.height = `${this.height + 50}px`
      }
      return style
    }
  },
  watch: {
    value: function(value) {
      if (value !== this.editor.txt.html()) {
        this.editor.txt.html(this.value)
      }
    }
    // value为编辑框输入的内容，这里我监听了一下值，当父组件调用得时候，如果给value赋值了，子组件将会显示父组件赋给的值
  },
  data() {
    return {
      code: null,
      codeShow: false,
      // 默认有这么多菜单，meanArray有值以meanArray为准
      defaultMeanus: [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo'
      ],
      editor: ''
    }
  },
  methods: {



    pack(s){
      s = s.replace(/\/\*(.|\n)*?\*\//g, "");
      s = s.replace(/\s*([\{\}\:\;\,])\s*/g, "$1");
      s = s.replace(/\,[\s\.\#\d]*\{/g, "{");
      s = s.replace(/;\s*;/g, ";");
      s = s.replace(/;\s*}/g, "}");
      s = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
      return (s == null) ? "" : s[1];
    },

    openCode() {
      this.code = null
      this.code = htmlFormat(this.value)
      // this.code = this.value.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/ /g, "&nbsp;")
      // console.log(this.code,"this.code)")
      // let text =  this.editor.txt.text().replace(/&lt;/ig, "<").replace(/&gt;/ig, ">").replace(/&nbsp;/ig, " ")
      // console.log(text,"text")
      this.codeShow = true
    },
    codeSuccess(){
      console.log(this.code)


      // let packer = new Packer;
      // let output = packer.pack(this.value, 0, 0);
      // console.log(output, "output")
      // let output=  packageFormat(this.code)
      //  this.setHtml(output)
      //  this.editor.dangerouslyInsertHtml(this.code)
      this.code = null
      this.codeShow = false
    },
    init() {
      const _this = this
      this.editor = new Editor(this.$refs.editor)
      this.editor.config.uploadImgAccept = ['doc', 'docx', 'png', 'img', 'gif', 'bmp', 'webp']
      // this.editor.config.uploadImgShowBase64 = true // 使用 base64 保存图片
      // this.editor.config.uploadImgServer = process.env.VUE_APP_BASE_API + "/web/images"
      // this.editor.config.uploadFileName = "file"
      // this.editor.config.uploadImgParams= {
      //
      // }

      this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        // resultFiles 是 input 中选中的文件列表
        // insertImgFn 是获取图片 url 后，插入到编辑器的方法
        let forms = new FormData()
        let configs = {
          headers:{
            'Content-Type':'multipart/form-data',
            Authorization: getToken()
          }
        };
        forms.append('file',resultFiles[0])

        axios.post(
          process.env.VUE_APP_BASE_API + "/sist/article/images",
          forms ,configs).then(res=>{
          console.log(res)
          let img = "<p></p><img src='"+res.data.data.href+"' alt='"+res.data.data.url+"'></p>"
          _this.setHtml(_this.getHtml() + img)
        })
        // 上传图片，返回结果，将图片插入到编辑器中
      }
      this.editor.config.height = this.height
      this.editor.config.pasteFilterStyle = false
      this.editor.config.zIndex = 10
      // this.editor.config.uploadImgHooks = {
      //   customInsert: function (insertImg, result, editor2) {
      //     // uploadResult(result);
      //     console.log(result)
      //     insertImg(result.data.url);
      //   }
      // }
      this.setMenus() // 设置菜单
      this.editor.config.onchange = (html) => {
        _this.$emit('change', html) // 将内容同步到父组件中
      }
      this.editor.create() // 创建编辑器
    },
    setMenus() {
      // 设置菜单
      if (this.meanArray) {
        this.editor.config.menus = this.meanArray
      } else {
        this.editor.config.menus = this.defaultMeanus
      }
    },
    getHtml() {
      // 得到文本内容
      return this.editor.txt.html()
    },
    setHtml(txt) {
      // 设置富文本里面的值
      // this.editor.txt.html(txt)
      this.editor.txt.text(txt)

    }
  },
  mounted() {
    const that = this
    that.$nextTick(function() {
      that.init()
    })
  }
}
</script>

<style scoped lang="scss">

.editor {
  z-index: 1 !important;
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.code {
  margin-top: 3rem;

}
.textarea{
  width: 1036px;
  height: 750px;
}

</style>
