<template>
  <div class="main">
    <div class="left-user">
      <ul id="allUserList">
        <!-- <li class="unlive name-li" id="123">
                        <img src="static/avatar.jpg"/>
                        <div class="message-circle"></div>
                        <span>徐医生</span>
                    </li> -->
      </ul>
    </div>
    <div class="right-main">
      <div style="height: 100%; flex: 1; min-width: 380px">
        <div class="title" id="userName"></div>
        <div class="content-micro">
          <div id="divContent">
            <div class="left-chart one-chart">
              <img src="static/avatar.jpg" />
              <div class="chart-line">
                <div class="triangle-left"></div>
                <span>hello</span>
              </div>
            </div>
            <div class="right-chart one-chart">
              <div class="chart-line">
                <div class="triangle-right"></div>
                <span
                  >What's your name?......................................</span
                >
              </div>
              <img src="static/avatar.jpg" />
            </div>
            <div class="right-chart one-chart">
              <div class="chart-line voice-line">
                <div class="triangle-right"></div>
                <span class="voice-block">
                  <div class="trumpet"></div>
                  <div class="inline-block">3s</div>
                </span>
              </div>
              <img src="static/avatar.jpg" />
            </div>
          </div>
          <div id="microphone-block" class="hidden">
            <div class="green-ball"></div>
            <span class="microphone-text"> 正在录音... </span>
            <div class="float-r mt-3">
              <button id="sendVoiceButton">发送</button>
              <button id="cancleVoiceButton">取消</button>
            </div>
          </div>
        </div>
        <div class="input-content">
          <div class="toolbar">
            <span
              title="图片"
              id="picSpan"
              class="glyphicon glyphicon-picture"
              @click="picSpanClick"
            ></span>
            <span
              title="截图"
              id="screenShot"
              class="glyphicon glyphicon-scissors"
            ></span>
            <span title="语音" id="microphone" class="fa fa-microphone"></span>
            <span
              title="聊天记录"
              id="history"
              class="glyphicon glyphicon-time"
              @click="historyChat"
            ></span>
            <input
              id="file-input"
              type="file"
              accept="image/*"
              style="display: none"
              @change="picChange"
            />
          </div>
          <div id="input-main" rows="5" contenteditable="true" @keyup="keyupSend"></div>
          <button id="send" @click="sendMsg">发送</button>
        </div>
      </div>
      <div class="history" v-if="showHistory">
        <div class="history-title">聊天记录</div>
        <div id="history-main" v-loading="historyLoading">
          <!-- <div class="one-history">
                            <div class="avatar" style="background:url(static/avatar.jpg) 0 0 no-repeat;background-size: contain;"></div>
                            <div class="info-data">
                                <div class="info">
                                    <span class="name">王医生</span>
                                    <span class="date">2021-06-09</span>
                                </div>
                                <span class="word-break">hhhhhhhhhhhhh</span>
                            </div>
                        </div> -->
        </div>
      </div>
    </div>
    <audio id="audioVoice" autoplay class="hidden"></audio>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      allUsers: null,
      clickUserId: '',
      clickUserName: '',
      clickAvatar: '',
      myUserId: '',
      myAvatar: '',
      myUserName: '',
      dataNodes: {},
      connection: null,
      viewer: null,
      historyView: null,
      notice: null,
      oldTitle: null,
      unVisibleMsg: 0,
      inputMsg: '', // 输入框的数据
      showHistory: false, // 展示聊天记录
      historyLoading: false
    }
  },
  methods: {
    sendMsg () {
      // 回车发送信息
      var userId = this.clickUserId
      var message = $('#input-main').html()
      if (userId == null || userId === '') {
        alert('请先选择一个用户')
        return
      }
      if (message == null || message === '' || message === '<div><br></div>') {
        alert('不能发送空白信息！')
        return
      }
      message = message.replace('<div><br></div>', '')// 去除掉回车带来的换行
      let reg = new RegExp('<img style="[^"]+"[^>]*>', 'g')
      let strArr = message.split(reg)
      // 发送文字
      for (let str of strArr) {
        if (str) {
          console.log('发送文字', str)
          let inputData = { 'UserId': userId, 'TextContent': str }
          this.sendMsgServer(inputData)
        }
      }
      // 发送图片-base64
      $('#input-main .local').each(function () {
        console.log('base64的图片')
        let base64 = $(this).attr('src')
        base64 = base64.replace('data:image/png', 'data:image/jpeg')
        base64 = base64.replace('data:image/gif', 'data:image/jpeg')
        // suofang(base64, 1.5, sendMsgServer)
        let inputData = { 'UserId': userId, 'ImageContent': base64 }
        this.sendMsgServer(inputData)
      })
      // 发送图片-在线图片
      $('#input-main .online').each(function () {
        console.log('网上的图片')
        let url = $(this).attr('src')
        let img = `<img style="max-width:200px;width:auto;height:auto" src="${url}"/>`
        // eslint-disable-next-line standard/object-curly-even-spacing
        let inputData = { UserId: userId, TextContent: img}
        this.sendMsgServer(inputData)
      })

      // 发送完毕消息清空输入框
      $('#input-main').html('')
    },
    sendMsgServer (param) {
      connection.invoke('Send', param)
        .then(function () {

        })
        .catch(function (err) {
          return console.error(err.toString())
        })
    },
    keyupSend (event) {
      if (event.keyCode === 13 && this.clickUserId) {
        event.preventDefault()
        this.sendMsg()
      }
      return false
    },
    historyChat () {
      if (this.showHistory) {
        this.showHistory = false
      } else {
        this.showHistory = true
        this.historyLoading = true
        connection.invoke('ChatLog', this.clickUserId)// 发起请求历史数据
          .then(function (message) {
            this.historyLoading = false
          })
          .catch(function (err) {
            this.historyLoading = false
            return console.error(err.toString())
          })
      }
    },
    picSpanClick () {
      $('#file-input').click()
    },
    picChange (e) {
      var reader = new FileReader()
      reader.onload = function (e) {
        const str =
                "<img style='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])
      $('#file-input').val('')
    },
    login () {
      connection = new signalR.HubConnectionBuilder().withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000]).withUrl(window.g.API_ROOT + '/hubs/chathub', { accessTokenFactory: () => userId }).build()
      connection.start().then(function () {

      }).catch(function (err) {
        return console.error(err.toString())
      })
      connection.on('selfMsg', function (message) {
        $('#divContent').append('<li><strong><i class="fas fa-long-arrow-alt-right"></i> ' + message + '</strong></li>')
      })
      // 接收数据
      connection.on('receive', function (message) {
        let items = ''
        if (message.userId === this.myUserId) { // 自己的消息
          if (message.chatType === 0) { // 文字消息
            items = `<div class="right-chart one-chart">
                    <div class="chart-line">
                        <div class="triangle-right"></div>
                        <span class="text-content">${message.content}</span>
                    </div>
                    <div class="avatar" style="background:url(${this.myAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                </div>`
          } else { // 图片消息
            items = `<div class="right-chart one-chart">
                    <div class="chart-line">
                        <div class="triangle-right"></div>
                        <span class="text-content">
                            <img style="max-width:200px;width:auto;height:auto" src="${message.content}"/>
                        </span>
                    </div>
                    <div class="avatar" style="background:url(${this.myAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                </div>`
          }
        } else if (message.userId === this.clickUserId) { // 对方的消息
          if (message.chatType === 0) { // 文字消息
            items = `<div class="left-chart one-chart">
                <div class="avatar" style="background:url(${this.clickAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                    <div class="chart-line">
                        <div class="triangle-left"></div>
                        <span>${message.content}</span>
                    </div>
                </div>`
          } else { // 图片消息
            items = `<div class="left-chart one-chart">
                <div class="avatar" style="background:url(${this.clickAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                    <div class="chart-line">
                        <div class="triangle-left"></div>
                        <span>
                            <img style="max-width:200px;width:auto;height:auto" src="${message.content}"/>
                        </span>
                    </div>
                </div>`
          }
          // 这里调用后台方法，告诉后台该clickUserId的消息变为已读
          connection.invoke('CheckMessages', [message.messageId])
            .then(function (message) {

            })
            .catch(function (err) {
              return console.error(err.toString())
            })
        } else { // 其他人的消息
          this.appendCircle(message.userId)// 添加小红点
        }
        if (!this.isVisibility()) { // 不为当前页面
          this.unVisibleMsg++
          let obj = this.allUsers.find((v) => {
            return v.user.userId === message.userId
          })
          this.iN.setFavicon(this.unVisibleMsg)
          this.iN.setTitle(true)
          this.iN.player()
          setTimeout(() => {
            this.iN.stopPlay()
          }, 10)
          this.iN.notify({
            title: '聊天室新通知',
            body: `${obj.user.userName}:${message.content}`,
            icon: 'static/消息.png',
            onclick: () => {
              window.focus()
              $('#' + message.userId).click()
              this.iN.setTitle()
              this.iN.faviconClear()
              this.unVisibleMsg = 0
            }
          })
          // showNotice(`收到${obj.userName}消息:${message.content}`,message.userId)//出通知
          // notice = sendNotificationFn('有新的通知', 500);//改标题
        }
        $('#divContent').append(items)
        $('#divContent').scrollTop(document.getElementById('divContent').scrollHeight)
        this.showImage()// 重新生成viewer对象
      })
      // 获取左侧列表
      connection.on('allUsers', function (data) {
        console.log(data)
        $('#allUserList').empty()
        if (data != null && data != undefined) {
          allUsers = data.allUsers
          data.allUsers && data.allUsers.forEach((v, i) => {
            let index = -1
            /* if (data.onlineUsers && data.onlineUsers.length > 0) {
                    index = data.onlineUsers.findIndex((k) => {
                        return k === v.user.userId
                    })
                } */
            let items = ''
            if (myUserId !== v.user.userId) {
              if (index < 0) {
                items += `<li class="unlive name-li" id="${v.user.userId}" onclick="getChart('${v.user.userId}',$(this))"><img src="${v.user.avatarImageUrl ? v.user.avatarImageUrl : 'static/avatar.jpg'}"/>${v.user.userName}<span>(离线)</span></li>`
              } else {
                items += `<li class="name-li" id="${v.user.userId}" onclick="getChart('${v.user.userId}',$(this))"><img src="${v.user.avatarImageUrl ? v.user.avatarImageUrl : 'static/avatar.jpg'}"/>${v.user.userName}<span>(在线)</span></li>`
              }
              $('#allUserList').append(items)
              if (v.hasUnReadLog) {
                appendCircle(v.user.userId)
              }
            } else {
              items += `<li class="name-li"><img src="${v.user.avatarImageUrl ? v.user.avatarImageUrl : 'static/avatar.jpg'}"/>${v.user.userName}(本人)</li>`
              myAvatar = v.user.avatarImageUrl
              myUserName = v.user.userName
              $('#allUserList').prepend(items)
            }
          })
          if (clickUserId) {
            $('#' + clickUserId).click()
          }
        } else {
          console.log('error,please restart ChatHub')
        }
      })

      connection.on('onlineUserChange', function (data) {
        console.log('在线人数', data)
        if (data != null && data != undefined) {
          $('#allUserList li').addClass('unlive')
          $('#allUserList li span').text('(离线)')
          for (let item of data.onlineUsers) {
            $(`#${item}`).removeClass('unlive')
            $(`#${item} span`).text('(在线)')
          }
          $('#allUserList li:first').removeClass('unlive')// 去除掉本人
        } else {
          console.log('error,please restart ChatHub')
        }
      })

      connection.on('chatLog', function (data) {
        $('#history-main').empty()
        if (data != null && data != undefined) {
          var str = ''
          data.forEach((value, index, array) => {
            let avatar = ''
            let name = ''
            let color = ''
            if (myUserId == value.sendUserId) {
              avatar = myAvatar
              name = myUserName
              color = 'green-color'
            } else {
              avatar = clickAvatar
              name = clickUserName
              color = 'blue-color'
            }

            if (value.chatType === 0) { // 文字消息
              str = `<div class="one-history">
                        <div class="avatar" style="background:url(${avatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                        <div class="info-data">
                            <div class="info">
                                <span class="name ${color}">${name}</span>
                                <span class="date ${color}">${dayjs(value.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                            </div>
                            <span class="word-break">${value.content}</span>
                        </div>
                    </div>`
            } else { // 图片消息
              str = `<div class="one-history">
                        <div class="avatar" style="background:url(${avatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                        <div class="info-data">
                            <div class="info">
                                <span class="name ${color}">${name}</span>
                                <span class="date ${color}">${dayjs(value.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
                            </div>
                            <span class="word-break">
                                <img style="max-width:200px;" src="${value.content}"/>
                            </span>
                        </div>
                    </div>`
            }
            $('#history-main').append(str)
          })
          $('#history-main').scrollTop(document.getElementById('history-main').scrollHeight)
          if (historyView) {
            historyView.viewer('destroy')
            historyView = null
          }
          historyView = $('#history-main').viewer({navbar: false})
        } else {
          console.log('error,please restart ChatHub')
        }
      })

      connection.on('unReadLog', function (data) {
        if (data != null && data != undefined && data.length > 0) {
          var str = ''
          let msgIdArr = []
          data.forEach(function (value, index, array) {
            let items = ''
            if (value.chatType === 0) { // 文字消息
              items = `<div class="left-chart one-chart">
                        <div class="avatar" style="background:url(${clickAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                            <div class="chart-line">
                                <div class="triangle-left"></div>
                                <span>${value.content}</span>
                            </div>
                        </div>`
            } else { // 图片消息
              items = `<div class="left-chart one-chart">
                <div class="avatar" style="background:url(${clickAvatar || 'static/avatar.jpg'}) 0 0 no-repeat;background-size: contain;"></div>
                    <div class="chart-line">
                        <div class="triangle-left"></div>
                        <span>
                            <img style="max-width:200px;width:auto;height:auto" src="${value.content}"/>
                        </span>
                    </div>
                </div>`
            }
            $('#divContent').append(items)
            msgIdArr.push(value.id)
          })
          $('#divContent').scrollTop(document.getElementById('divContent').scrollHeight)
          // 这里调用后台方法，告诉后台该clickUserId的消息变为已读
          if (msgIdArr.length > 0 && isVisibility()) {
            connection.invoke('CheckMessages', msgIdArr)
          }
        } else {
          /* $('#divContent').append("****无离线消息****"); */
          console.log('无离线消息')
        }
      })
    },
    appendCircle (userId) {
      // 添加小红点
      let ul = document.getElementById('allUserList')
      let doc = document.getElementById(userId)
      let node = doc.getElementsByClassName('message-circle')
      if (node.length === 0) {
        let circle = document.createElement('div')
        circle.className = 'message-circle'
        doc.appendChild(circle)
      }
      let firstLi = $(ul).children('li')[0]
      firstLi.after(doc)
    },
    isVisibility () {
      // 是否为当前页面
      var hiddenProperty = 'hidden' in document ? 'hidden'
        : 'webkitHidden' in document ? 'webkitHidden'
          : 'mozHidden' in document ? 'mozHidden'
            : null
      return !document[hiddenProperty]
    },
    getIN () {
      // 生成提示实例
      this.iN = new Notify({
        effect: 'flash',
        interval: 500,
        message: '有消息拉！',
        audio: {
          file: 'static/消息提示音.mp3'// 可以使用数组传多种格式的声音文件
        },
        notification: {
          title: '通知！',
          icon: '',
          body: '您来了一条新消息'
        }
      })
    },
    showImage () {
      if (this.viewer) {
        this.viewer.viewer('destroy')
        this.viewer = null
      }
      this.viewer = $('#divContent').viewer({navbar: false})
    }
  },
  created () {
    this.getIN()
    let person = this.$route.query.id
    if (person) {
      // var person = prompt("请输入用户id", "1");
      this.myUserId = person
      if (person != null && person != '') {
        this.login(person)
        this.clickUserId = window.localStorage.getItem('clickUserId')
        if (this.clickUserId) {
          setTimeout(() => {
            $('#' + this.clickUserId).click()
          }, 500)
        }
      }
    } else {
      alert('用户id不能为空')
    }
  }
}
</script>

<style scoped>

</style>
