<!-- 发送消息栏 -->
<template>
    <div class="input-content">
        <div id="microphone-block" v-show="microphoneShow">
                <div class="green-ball"></div>
                <span class="microphone-text">
                    正在录音...({{recordTime}})s
                </span>
                <div class="float-r mt-3">
                    <el-button size="mini" type="primary" plain @click="sendVoice">发送</el-button>
                    <el-button size="mini" @click="cancelVoice">取消</el-button>
                </div>
            </div>
        <div class="toolbar">
            <el-popover
                placement="top"
                width="400"
                trigger="click">
                <div class="cursor" style="font-size:24px">
                    <span v-for="(item,key) in emojis" :key="key" @click="setEmoji(item.char)">{{item.char}}</span>
                </div>
                <span id="smileSpan" class="fa fa-smile-o" slot="reference"></span>
            </el-popover>
            <span title="图片" id="picSpan" class="iconfont icon-fasongtupian" @click="pictureClick"></span>
            <span title="截图" id="screenShot" class="iconfont icon-jietu" @click="screenShoot"></span>
            <el-upload
                :action="action"
                :on-success="successUpload"
                :show-file-list="false"
                class="inline-block"
            >
                <span title="文件" id="fileSpan" class="iconfont icon-fasongwenjian"></span>
            </el-upload>
            <span title="语音" id="microphone" class="iconfont icon-yuyinliaotian" @click="microphoneClick"></span>
            <span title="聊天记录" id="history" class="iconfont icon-liaotianjilu" @click="historyClick(true)"></span>
            <button id="send" @click="sendMsg"><span class="iconfont icon-fasong-copy"></span>发送</button>
        </div>
        <div id="input-main" rows="5" contenteditable="true"></div>
        <input id="pic-input" type="file" accept="image/*" v-show="false" @change="picChooseChange"/>
    </div>
</template>

<script>
import recordUtils from '../../libs/recordUtils/voice-utils'
import emojis from '../../assets/emojis.json'
// import screenShotPlugin from 'js-web-screen-shot'
import screenShotPlugin from '../../libs/screenshotPlugin/screenShotPlugin.common.js'
const {voiceTime, API_ROOT} = require('../../../static/config.js')

export default {
  name: '',
  mixins: [],
  components: {},
  props: {
    clickItem: {
      Object,
      default: () => {}
    }
  },
  data () {
    return {
      microphoneShow: false,
      recordTime: voiceTime,
      action: API_ROOT + '/sysFileInfo/upload',
      emojis: emojis
    }
  },
  watch: {},
  computed: {},
  created () {},
  mounted () {
    this.sendByKeyup()
    this.pasteContent()
  },
  methods: {
    sendByKeyup () {
      // 按回车发送聊天内容
      document.getElementById('input-main').onkeyup = (event) => {
        if (event.keyCode === 13) {
          event.preventDefault()
          this.sendMsg()
        }
        return false
      }
    },
    pasteContent () {
      // 粘贴
      const target = document.querySelector('#input-main')
      //   let that = this
      target.addEventListener('paste', (e) => {
        if (!(e.clipboardData && e.clipboardData.items)) {
          return
        }
        for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
          var item = e.clipboardData.items[i]
          console.log('item', item)
          if (item.kind === 'file' && item.type.match(/^image\//i)) {
            var f = item.getAsFile()
            var reader = new FileReader()
            reader.onload = function (e) {
              let img = document.createElement('img')
              img.setAttribute('style', 'max-width:100px')
              img.setAttribute('class', 'local')
              img.setAttribute('src', e.target.result)
              document.getElementById('input-main').appendChild(img)// 将img添加到div中
              //   that.insertCont(img)
            }
            reader.readAsDataURL(f)// 读取为DataURL,改为上传图片的话需要blob,方法改为readAsBinaryString,onload就会获取到blob
          }
          if (item.kind === 'string' && item.type === 'text/plain') {
            let span = document.createElement('span')
            let text = document.createTextNode(e.clipboardData.getData('text'))
            span.appendChild(text)
            document.getElementById('input-main').appendChild(span)
            // that.insertCont(span)
          }
          if (item.kind === 'string' && item.type === 'text/html') { // samesite同站策略问题，不保存图片地址了
            item.getAsString((e) => { // 获取到粘贴的html
              console.log('getAsString', e)
              if (e.indexOf('base64') > -1) {
                let startIndex = e.indexOf('src="') + 5
                let endIndex = e.indexOf('"', startIndex)
                let src = e.substring(startIndex, endIndex)
                let img = document.createElement('img')
                img.setAttribute('style', 'width:100px')
                img.setAttribute('class', 'online')
                img.setAttribute('src', src)
                document.getElementById('input-main').appendChild(img)
                // that.insertCont(img)
              }
            })
          }
        }
        e.preventDefault()

        this.$nextTick(() => {
          setTimeout(() => {
            this.moveTo()// 把光标移至最后
          }, 300)
        })
      })
    },
    sendMsg (type, params) {
      let id = this.clickItem.id
      let message = document.getElementById('input-main').innerHTML
      let inputData = {
        receiveUserId: id,
        chatReceiveType: this.clickItem.type,
        // chatType:4,
        // content: params.data,
        atUserIds: ''
      }
      if (type === 'audio') {
        // 语音文件
        inputData.chatType = 4
        inputData.content = JSON.stringify(params)
        console.log('inputData', inputData)
        this.$emit('sendMsgServer', inputData)
      } else if (type === 'file') {
        // 附件
        inputData.chatType = 2
        inputData.content = params
        console.log('inputData', inputData)
        this.$emit('sendMsgServer', inputData)
      } else if (type === 'comment') {
        // 评论
        inputData.chatType = 3
        inputData.content = JSON.stringify(params)
        console.log('inputData', inputData)
        this.$emit('sendMsgServer', inputData)
      } else {
        // 其他数据
        if (message == null || message === '' || message === '<div><br></div>' || message === '<div><br></div><div><br></div>') {
          this.$message.warning('不能发送空白信息')
          document.getElementById('input-main').innerHTML = '' // 清空一下消息
          return
        }
        message = message.replace(/<p>|<\/p>|<div>|<\/div>|<br\/>|<br>/g, '')// 去除掉回车带来的换行
        // let reg = new RegExp('<img style="[^"]+"[^>]*>', 'g')
        let reg = new RegExp('<img .*?>', 'g')
        console.log('获得的数据', message)
        let strArr = message.split(reg)// 处理文字中夹杂的图片
        console.log('处理出来的文字', strArr)
        // 发送文字
        for (let str of strArr) {
          if (str) {
            inputData.chatType = 0
            inputData.content = str
            console.log('发送文字', str, inputData)//
            this.$emit('sendMsgServer', inputData)
          }
        }
        // 发送图片-base64
        let imgLocalNodes = document.querySelectorAll('#input-main .local')
        imgLocalNodes.forEach((e) => {
          let base64 = e.getAttribute('src')
          base64 = base64.replace('data:image/png', 'data:image/jpeg')
          base64 = base64.replace('data:image/gif', 'data:image/jpeg')
          inputData.chatType = 1
          inputData.content = base64
          console.log('base64的图片', inputData)
          this.$emit('sendMsgServer', inputData)
        })

        // 发送图片-在线图片
        let imgInlineNodes = document.querySelectorAll('#input-main .online')
        imgInlineNodes.forEach((e) => {
          let url = e.getAttribute('src')
          let img = `<img style="max-width:200px;width:auto;height:auto" src="${url}"/>`
          inputData.chatType = 2
          inputData.content = img
          console.log('网上的图片', inputData)
          this.$emit('sendMsgServer', inputData)
        })

        // 发送完毕消息清空输入框
        document.getElementById('input-main').innerHTML = ''
      }
    },
    microphoneClick () {
      if (this.microphoneShow) { // 打开状态
        this.cancelVoice()
      } else { // 关闭状态
        this.microphoneShow = true
        recordUtils.onStartVoice((time) => {
          this.recordTime = time
          if (this.recordTime === 0) { // 倒计时结束就自动发送语音
            this.sendVoice()
          }
        })
      }
    },
    sendVoice () {
      this.microphoneShow = false
      recordUtils.onEndVoice((params) => {
        this.sendMsg('audio', params)
      })
    },
    cancelVoice () {
      this.microphoneShow = false
      recordUtils.stop()
    },
    pictureClick () {
      // 图片click
      document.getElementById('pic-input').click()
    },
    picChooseChange (e) {
      // 图片选择
      var reader = new FileReader()
      reader.onload = function (e) {
        const str =
                "<img style='max-width:100px' class='local' src='" +
                e.target.result +
                "'/>"
        let ele = document.querySelector('#input-main')
        ele.innerHTML = ele.innerHTML + str
      }
      reader.readAsDataURL(e.target.files[0])
      document.getElementById('pic-input').value = ''
    },
    fileClick () {
      document.getElementById('file-input').click()
    },
    successUpload (response, file, fileList) {
      if (response.statusCode === 200) {
        this.sendMsg('file', JSON.stringify(response.data))
      } else {
        this.$message.error(response.errors)
      }
    },
    smileSpanClick () {

    },
    // 向聊天框填入表情
    setEmoji (char) {
    //   let node = document.createElement('img')
    //   node.setAttribute('src', require(`../assets/emoji/${number}.gif`))
      document.getElementById('input-main').innerHTML += char
    //   this.insertCont(char)
    },
    screenShoot () {
      // 截图
      // eslint-disable-next-line no-new
      new screenShotPlugin({enableWebRtc: false, completeCallback: this.screenShootCallBack})
    },
    screenShootCallBack (base64) {
      // 把图片放到粘贴板里
      let node = document.createElement('img')
      node.setAttribute('style', 'max-width:100px')
      node.setAttribute('src', base64)
      node.setAttribute('class', 'local')
      // 把图片放到输入框里
      document.getElementById('input-main').appendChild(node) // 将img添加到div中

      this.$nextTick(() => {
        this.moveTo()// 把光标移至最后
      })

      // 复制图片节点
      let img2 = document.createElement('img')
      img2.setAttribute('style', 'width:100px;position: fixed; top: -5000px;')
      img2.setAttribute('src', base64)
      img2.setAttribute('class', 'screenShotImg')

      document.body.appendChild(img2)

      let target2 = document.querySelector('.screenShotImg')
      this.getSelect(target2)
      document.execCommand('copy')
      document.body.removeChild(target2)
    },
    // 选中图片
    getSelect (targetNode) {
      if (window.getSelection) {
        // chrome等主流浏览器
        let selection = window.getSelection()
        let range = document.createRange()
        range.selectNode(targetNode)
        selection.removeAllRanges()
        selection.addRange(range)
      } else if (document.body.createTextRange) {
        // ie
        let range = document.body.createTextRange()
        range.moveToElementText(targetNode)
        range.select()
      }
    },
    historyClick () {
      this.$emit('historyClick')
    },
    moveTo (type = 'end') { // 移动光标到最后面
      let el = document.getElementById('input-main')
      el.focus()
      if (window.getSelection) { // ie11 10 9 ff safari
        let range = window.getSelection() // 创建range
        range.selectAllChildren(el) // 选择el子项
        if (type === 'start') {
          range.collapseToStart() // 光标移至开头
        } else {
          range.collapseToEnd() // 光标移至最后
        }
      } else if (document.selection) { // ie10 9 8 7 6 5
        let range = document.selection.createRange() // 创建选择对象
        range.moveToElementText(el) // range定位到ele
        if (type === 'start') {
          range.collapse() // 光标移至开头
        } else {
          range.collapse(false) // 光标移至最后
        }
        range.select()
      }
    },
    insertCont (html) { // 在光标处插入内容
      let el = document.getElementById('input-main')
      el.focus()
      if (document.selection) { // IE 10,9,8,7
        document.selection.createRange().pasteHTML(html)
      } else if (window.getSelection) {
        var sel = window.getSelection()
        if (sel.getRangeAt && sel.rangeCount) {
          var range = sel.getRangeAt(0)
          range.deleteContents()
          var div = document.createElement('div')
          div.innerHTML = html
          let frag = document.createDocumentFragment()
          let node
          let lastNode
          while ((node = div.firstChild)) {
            lastNode = frag.appendChild(node)
          }
          range.insertNode(frag)
          if (lastNode) {
            range = range.cloneRange()
            range.setStartAfter(lastNode)
            range.collapse(true)
            sel.removeAllRanges()
            sel.addRange(range)
          }
        }
      }
    }
  },
  beforeDestroy () {},
  destroyed () {},
  beforeUpdate () {},
  updated () {}
}
</script>
<style lang='scss' scoped>
.input-content{
        height: 20%;
        border-top: 1px solid rgba(0,0,0,0.2);
        position: relative;
        box-sizing: border-box;
        .toolbar{
            height: 40px;
            line-height: 40px;
            padding: 0 25px;
            span{
                margin: 0 8px;
                cursor: pointer;
                transform: scale(1.3);
            }
        }
        #input-main{
            width: 100%;
            height: calc(100% - 60px);
            border: none;
            resize: none;
            outline: none;
            padding: 5px 30px;
            overflow: auto;
            box-sizing: border-box;
        }
        #send{
            border: 0px;
            background: #f2f3f5;
            color: rgba(255, 125, 0, 1);
            font-size: 14px;
            width: 70px;
            float: right;
            height: 30px;
            line-height: 30px;
            margin-top: 5px;
            width: 90px;
            cursor: pointer;
        }
        #emoji-box{
            width: 342px;
            height: 195px;
            position: absolute;
            top: -205px;
            left: 15px;
            background: #fff;
            box-shadow: 2px 0px 15px #bfbfbf;
            padding: 5px;
        }
        #emoji-box img{
            margin: 1px 3px;
        }
        #microphone-block{
            position: absolute;
            top: -32px;
            width: 100%;
            height: 32px;
            padding: 0px 10px;
            background: #cdcdcd;
            box-sizing: border-box;
        }
        .microphone-text {
            display: inline-block;
            line-height: 32px;
        }
        .green-ball {
            width: 8px;
            height: 8px;
            display: inline-block;
            border-radius: 10px;
            animation: colorChange 2s infinite;
        }
        @keyframes colorChange {
            0% {
                background: green;
            }
            50%{
                background: rgb(0, 206, 0);
            }
            100% {
                background: green;
            }
        }
    }
</style>
