<!-- 聊天窗口 -->
<template>
        <div style="height:80%">
            <div class="title">{{userName}}</div>
            <div v-if="clickItem.type === 1 && pageType === '2'" id="ris-button" class="icon iconfont icon-huanzhejilu-cu-fill more-icon-2 cursor" @click="risButtonClick"></div>
            <div v-if="clickItem.type === 1" id="setting-button" class="iconfont icon-qunguanli more-icon cursor" @click="settingClick(true)"></div>
            <div class="content-micro">
                <div id="divContent">
                    <div v-for="(item,index) in chatList" :key="index">
                        <!--普通消息-->
                        <div class="left-chart one-chart" v-if="item.chatType === 0 && item.chatPosition === 'left'">
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                            <div class="name-chart">
                                <div class="left-name">{{item.sendUser.userName}}</div>
                                <div class="chart-line">
                                    <span v-html="item.content"></span>
                                </div>
                            </div>
                        </div>
                        <div class="right-chart one-chart" v-if="item.chatType === 0 && item.chatPosition === 'right'">
                            <div class="chart-line">
                                <span v-html="item.content"></span>
                            </div>
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                        </div>
                        <!--图片消息-->
                        <div class="left-chart one-chart" v-if="item.chatType === 1 && item.chatPosition === 'left'">
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                            <div class="name-chart">
                                <div class="left-name">{{item.sendUser.userName}}</div>
                                <div class="chart-line">
                                    <span>
                                        <el-image style="max-width:200px;width:auto;height:auto" :src="item.content" :preview-src-list="imgList"></el-image>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="right-chart one-chart" v-if="item.chatType === 1 && item.chatPosition === 'right'">
                            <div class="chart-line">
                                <span>
                                    <el-image style="max-width:200px;width:auto;height:auto" :src="item.content" :preview-src-list="imgList"></el-image>
                                </span>
                            </div>
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                        </div>
                        <!--语音-->
                        <div class="right-chart one-chart" v-if="item.chatType === 4 && item.chatPosition === 'right'">
                            <div class="chart-line cursor" @click="voiceLineClick(item)">
                                <span class="voice-block flex-right" :style="`width:${item.width}`">
                                    <div :class="['trumpet','trumpet-right',item.voicePlay ? 'voicePlay':'']"></div>
                                    <div class="inline-block">{{item.content.Time}}s</div>
                                </span>
                            </div>
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                        </div>
                        <div class="left-chart one-chart" v-if="item.chatType === 4 && item.chatPosition === 'left'">
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                            <div class="name-chart">
                                <div class="left-name">{{item.sendUser.userName}}</div>
                                <div class="chart-line cursor" @click="voiceLineClick(item)">
                                        <span class="voice-block flex-left" :style="`width:${item.width}`">
                                            <div class="inline-block">{{item.content.Time}}s</div>
                                            <div :class="['trumpet','trumpet-left',item.voicePlay ? 'voicePlay':'']"></div>
                                        </span>
                                </div>
                            </div>
                        </div>
                        <!--时间消息-->
                        <div class="time-msg" v-if="item.chatType === 9">{{item.createdTime}}</div>
                        <!--附件消息-->
                        <div class="right-chart one-chart" v-if="item.chatType === 2 && item.chatPosition === 'right'">
                            <span class="chart-line">
                                <div class="t-c file-box file-box-right">
                                    <img :src="require('../../assets/file/'+item.content.typeImg)"/>
                                    <div class="file-text">
                                        <div class="file-name">{{item.content.fileOriginName}}</div>
                                        <div class="file-size ft-l">{{item.content.fileSizeKb}}KB</div>
                                        <a class="inline-block ft-r" href="javascript:void(0);" @click="downloadFile(item.content.id,item.content.fileOriginName)">下载附件</a>
                                        <!-- <a class="inline-block ft-r mr-15" href="javascript:void(0);" @click="previewFile(item.content.id,item.content.fileOriginName)">在线预览</a> -->
                                    </div>
                                </div>
                            </span>
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                        </div>
                        <div class="left-chart one-chart" v-if="item.chatType === 2 && item.chatPosition === 'left'">
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                            <div class="name-chart">
                                <div class="left-name">{{item.sendUser.userName}}</div>
                                <span class="chart-line">
                                    <div class="t-c file-box">
                                        <img :src="require('../../assets/file/'+item.content.typeImg)"/>
                                        <div class="file-text">
                                            <div class="file-name">{{item.content.fileOriginName}}</div>
                                            <div class="file-size ft-r">{{item.content.fileSizeKb}}KB</div>
                                            <a class="inline-block ft-l" href="javascript:void(0);" @click="downloadFile(item.content.id,item.content.fileOriginName)">下载附件</a>
                                            <!-- <a class="inline-block ft-l ml-15" href="javascript:void(0);" @click="previewFile(item.content.id,item.content.fileSuffix)">在线预览</a> -->
                                        </div>
                                    </div>
                                </span>
                            </div>
                        </div>
                        <!--群组消息-->
                        <div class="other-msg" v-if="item.chatType === 5">
                            <span>{{item.content}}</span>
                        </div>
                        <!--评论消息-->
                        <div class="left-chart one-chart" v-if="item.chatType === 3 && item.chatPosition === 'left'">
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                            <div class="name-chart">
                                <div class="left-name">{{item.sendUser.userName}}</div>
                                <span class="chart-line" style="max-width: 360px;box-sizing: border-box;">
                                    <div class="mb-10 line-height-25">
                                        {{item.content.comment}}
                                        <a href="javascript:void(0);" @click="risButtonClick">详情></a>
                                    </div>
                                    <div class="file-box">
                                        <div class="ris-data">
                                            <img :src="require('../../assets/'+item.content.img)"/>
                                            <strong class="fs-15">{{item.content.patientName}}</strong>
                                            <div :class="`iconfont ${item.content.icon}`"></div>
                                            <div class="fs-13">{{item.content.age}}</div>
                                        </div>
                                        <div class="ris-content fs-15">{{item.content.projectName}}</div>
                                    </div>
                                </span>
                            </div>
                        </div>
                        <div class="right-chart one-chart" v-if="item.chatType === 3 && item.chatPosition === 'right'">
                            <span class="chart-line" style="max-width: 360px;box-sizing: border-box;">
                                <div class="mb-10 line-height-25">
                                    {{item.content.comment}}
                                    <a href="javascript:void(0);" @click="risButtonClick">详情></a>
                                </div>
                                <div class="file-box file-box-right">
                                    <div class="ris-data">
                                        <img :src="require('../../assets/'+item.content.img)"/>
                                        <strong class="fs-15">{{item.content.patientName}}</strong>
                                        <div :class="`iconfont ${item.content.icon}`"></div>
                                        <div class="fs-13">{{item.content.age}}</div>
                                    </div>
                                    <div class="ris-content fs-15">{{item.content.projectName}}</div>
                                </div>
                            </span>
                            <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                        </div>
                    </div>
                </div>
            </div>
            <audio id="audioVoice" autoplay class="hide"></audio>
            <ky-preview-dialog :url="url" :blob="blob" :visible.sync="visible" :type="previewType"></ky-preview-dialog>
        </div>
</template>

<script>
import {getChartData} from '../../api/api.js'
import {kyPreviewDialog} from 'kyui-plus'
const {voiceTime, API_ROOT} = require('../../../static/config.js')
export default {
  name: '',
  mixins: [],
  components: {kyPreviewDialog},
  props: {
    clickItem: {
      type: Object,
      default: () => {}
    },
    pageType: {
      type: String,
      default: ''
    },
    myUserId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      userName: '',
      chatList: [],
      timeChazhi: 5 * 60 * 1000, // 消息差的时长5分钟
      maxVoiceWidth: 200,
      voiceTimeout: null,
      lastChatTime: null,
      lastContentTime: null,
      canGetNext: true,
      imgList: [],
      url: '',
      blob: '',
      visible: false,
      previewType: ''
    }
  },
  watch: {
    clickItem: {
      handler (val) {
        if (val && val.id) {
          console.log('监听到clickItem', val)
          this.userName = this.clickItem.name
          console.log('clickItem', val)
          this.getFirstPageChat()
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {},
  created () {},
  mounted () {
    // 监听滚动条滚动
    document.getElementById('divContent').onscroll = (e) => {
      let scrollTop = e.target.scrollTop
      if (scrollTop <= 100 && scrollTop > 0) {
        let params = {
          userId: this.myUserId,
          otherId: this.clickItem.id,
          type: this.clickItem.type,
          startTime: this.lastContentTime,
          pageSize: 15
        }
        if (this.canGetNext) {
          this.getChatLog(params).then(res => {
            this.$nextTick(() => {
              let height2 = document.getElementById('divContent').scrollHeight
              document.getElementById('divContent').scrollTop = height2 - this.height1 + scrollTop
            })
          })
        }
      }
    }
  },
  methods: {
    risButtonClick () {
      let data = {
        type: 'openRis',
        data: {
          id: this.clickItem.id
        }
      }
      this.$chatUtils.postToParent(data)
    },
    settingClick (openFlag) {
    // 关闭历史记录，打开群管理页面
      this.$emit('settingClick', openFlag)
    },
    getFirstPageChat () {
      // 获取已有的聊天记录
      let params = {
        userId: this.myUserId,
        otherId: this.clickItem.id,
        type: this.clickItem.type,
        // eslint-disable-next-line no-undef
        startTime: this.$dayjs().format('YYYY-MM-DD HH:mm:ss'),
        pageSize: 15
      }
      this.lastChatTime = null
      this.chatList = []
      this.imgList = []
      this.getChatLog(params).then(res => {
        this.$nextTick(() => {
          setTimeout(() => {
            document.getElementById('divContent').scrollTop = document.getElementById('divContent').scrollHeight
          }, 10)
        })
      })
    },
    getChatLog (params) {
      return new Promise(async (resolve, reject) => {
        if (this.canGetNext) {
          this.canGetNext = false
          await getChartData(params).then(data => {
            if (data && data.length > 0) {
              this.lastContentTime = data[0].createdTime
              this.tempArr = []
              this.tempImgList = []
              data.forEach((el, i) => {
                if (i === 0) {
                  this.setChatListFunc(el, false, true)
                } else {
                  this.setChatListFunc(el, false, false)
                }
              })
              this.chatList = this.tempArr.concat(this.chatList)
              this.imgList = this.tempImgList.concat(this.imgList)
              this.height1 = document.getElementById('divContent').scrollHeight
              resolve()
            }
          }).finally(() => {
            this.canGetNext = true
          })
        }
      })
    },
    setChatListFunc (el, isAddToList, isAddToTime) { // 设置聊天消息 -- 聊天数据，receive来的数据直接追加到最后一条 isAddToList:是否追加消息   isAddToTime：是否追加时间
      // 设置时间
      let chazhi = new Date(el.createdTime).getTime() - new Date(this.lastChatTime).getTime()

      if (chazhi > this.timeChazhi || !this.lastChatTime || isAddToTime) { // 两条消息间隔时长大于5分钟则画时间
        let obj = {
          chatType: 9,
          createdTime: el.createdTime
        }
        let dayType = this.$chatUtils.judgeTime(el.createdTime)
        if (dayType === 0) { // 今天发的消息只显示时分秒
          obj.createdTime = el.createdTime.substring(10)
        }

        if (isAddToList) {
          this.chatList.push(obj)
        } else {
          this.tempArr.push(obj)
        }
      }
      this.lastChatTime = el.createdTime

      // 设置消息
      if (el.chatType !== 5) { // 不是其余消息就处理放两侧
        let content = this.dealContent(el.content, el.chatType)
        el.content = content
        if (el.sendUser.id === this.myUserId) {
          el.chatPosition = 'right'
        } else { // 别人的消息
          el.chatPosition = 'left'
        }
        if (el.chatType === 1) {
          this.dealToImgList(content, isAddToList)// 图片的话要放进预览里
        }
        if (isAddToList) {
          this.chatList.push(el)
          this.$nextTick(() => {
            document.getElementById('divContent').scrollTop = document.getElementById('divContent').scrollHeight
          })
        } else {
          this.tempArr.push(el)
        }
      } else {
        if (isAddToList) {
          this.chatList.push(el)
          this.$nextTick(() => {
            document.getElementById('divContent').scrollTop = document.getElementById('divContent').scrollHeight
          })
        } else {
          this.tempArr.push(el)
        }
      }
    },
    dealToImgList (content, isAddToList) {
      if (isAddToList) {
        this.imgList.push(content)
      } else {
        this.tempImgList.push(content)
      }
    },
    dealContent (content, chatType) {
      if (chatType === 2) { // 文件消息
        let obj = JSON.parse(content)
        console.log('附件obj', content)
        if (obj) {
          let typeImg = this.getFileType(obj.fileSuffix)
          obj.typeImg = typeImg
        } else {
          obj = {
            typeImg: '文件_未知.png'
          }
        }
        return obj
      } else if (chatType === 3) { // 评论消息
        let obj = JSON.parse(content)
        let img = ''
        let icon = ''
        if (obj.sex === '1') {
          img = '男士.png'
          icon = 'icon-xingbie-nan'
        } else if (obj.sex === '2') {
          img = '女士.png'
          icon = 'icon-xingbie-nv'
        } else {
          img = '未知.png'
          icon = 'icon-xingbie_weizhi'
        }
        let comment = obj.comment
        if (comment.length > 42) {
          obj.comment = comment.substring(0, 44)
          obj.comment += '...'
        }
        obj.img = img
        obj.icon = icon

        return obj
      } else if (chatType === 4) { // 语音消息
        let obj = JSON.parse(content)
        let width = this.maxVoiceWidth * (Number(obj.Time) / voiceTime)
        obj.width = width
        return obj
      } else {
        return content
      }
    },
    getFileType (fileSuffix) {
      let typeImg = ''
      let suffix = fileSuffix.toLowerCase()
      if (['txt'].includes(suffix)) {
        typeImg = '文件_txt.png'
      } else if (['mp4', 'avi', 'flv', 'm3u8', 'rmvb', 'mvb'].includes(suffix)) {
        typeImg = '文件_avi.png'
      } else if (['xls', 'xlsx', 'et', 'ett', 'xlt', 'xlsm', 'dbf', 'xml'].includes(suffix)) {
        typeImg = '文件_Excel.png'
      } else if (['mp3', 'wma'].includes(suffix)) {
        typeImg = '文件_MP3.png'
      } else if (['pdf'].includes(suffix)) {
        typeImg = '文件_pdf.png'
      } else if (['ppt', 'pptx'].includes(suffix)) {
        typeImg = '文件_ppt.png'
      } else if (['doc', 'docx'].includes(suffix)) {
        typeImg = '文件_world.png'
      } else if (['zip', 'rar'].includes(suffix)) {
        typeImg = '文件_zip.png'
      } else {
        typeImg = '文件_未知.png'
      }
      return typeImg
    },
    previewFile (id, fileSuffix) { // 在线预览
      this.url = `${API_ROOT}/sysFileInfo/download?id=${id}`
      this.visible = true
      this.previewType = fileSuffix.split('.')[1] || fileSuffix

      /*  var x = new XMLHttpRequest()
      x.open('GET', `${API_ROOT}/sysFileInfo/download?id=${id}`, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        this.blob = x.response
      }
      x.send() */
    },
    downloadFile (id, fileName) {
      var x = new XMLHttpRequest()
      x.open('GET', `${API_ROOT}/sysFileInfo/download?id=${id}`, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = fileName
        a.click()
      }
      x.send()
    },
    voiceLineClick (item) {
      let audio = document.getElementById('audioVoice')
      if (item.voicePlay) {
      // 关闭
        this.$set(item, 'voicePlay', false)
        audio.pause()
        if (this.voiceTimeout) {
          clearTimeout(this.voiceTimeout)
        }
      } else {
      // 打开
        if (this.lastVoice) { // 有上一个就先关闭上一个
          this.$set(this.lastVoice, 'voicePlay', false)
        }
        this.$set(item, 'voicePlay', true)
        this.lastVoice = item
        audio.setAttribute('src', item.content.Data)// 放上录音地址
        this.voiceTimeout = setTimeout(function () {
          this.$set(item, 'voicePlay', false)
          this.voiceTimeout = null
          this.lastVoice = null
        }, item.content.Time * 1000)
      }
    }
  },
  beforeDestroy () {},
  destroyed () {},
  beforeUpdate () {},
  updated () {}
}
</script>
<style lang='scss' scoped>

    .title{
        width:100%;
        height:54px;
        border-bottom: 1px solid rgba(0,0,0,0.2);
        text-align: center;
        line-height: 54px;
        background: #fff;
    }
    .flex-right{
        justify-content: flex-end!important;
    }
    .file-text .file-name{
        margin-bottom: 5px;
        color: #1D2129;
        max-width:180px;
        white-space:nowrap;
        overflow:hidden;
        text-overflow:ellipsis;
    }
    .file-text .file-size{
        color: rgba(134, 144, 156, 1);
        display: inline-block;
        font-size: 12px;
    }
    .file-text .file-size-right{
        color: #e5e5e5bd;
    }
    #divContent{
        height: 100%;
        overflow: auto;
        .one-chart{
            padding: 10px 15px;
        }
        .one-chart .unRead{
            color:#7FBC56;
            font-size:12px;
        }
        .one-chart .read{
            color:#B2B3B5;
            font-size:12px;
        }
        .right-chart{
            text-align: right;
            .avatar{
                float: right;
                margin-left: 5px;
                width: 35px;
                height: 35px;
                border-radius: 5px;
                background-size: contain!important;
            }
            .file-text {
                float: right;
                margin-right: 5px;
            }
            span {
                padding: 9px 12px;
                border-radius: 10px 10px 0 10px;
                /* margin-right: 4px; */
                display: inline-block;
                text-align: left;
                word-break: break-word;
                background: #0FC6C2!important;
                color: #fff;
            }

        }
        .left-chart{
            .avatar{
                float: left;
                margin-right: 5px;
                width: 35px;
                height: 35px;
                border-radius: 5px;
                margin-top: 6px;
                background-size: contain!important;;
            }
            .name-chart{
                margin-left: 40px;
            }
            .left-name{
                font-size: 12px;
                color: #707070;
            }
            span {
                background: #fff;
                padding: 9px 12px;
                border-radius: 10px 10px 10px 0px;
                display: inline-block;
                text-align: left;
                word-break: break-word;
            }
            .file-text{
                float: left;
                margin-right: 5px;
            }
        }
        .one-chart .chart-line{
            display: inline-block;
            position: relative;
        }
        .chart-line .ris-detail{
            position: absolute;
            top: 30px;
            right: 20px;
        }
        .voice-block{
            width: 150px;
            text-align: right!important;
            display: flex!important;
            align-items: center;
            div{
                margin:0 3px;
            }
        }
        .trumpet-right{
            background:url('../../assets/声音-white.png') right 0 no-repeat;
            transform: rotate(180deg);
        }
        .trumpet-left{
            background:url('../../assets/声音-black.png') right 0 no-repeat;
        }
        .trumpet {
            width: 16px;
            height: 16px;
            background-size: 400%;
            display: inline-block;
        }
        .time-msg {
            text-align: center;
            color: #86909C;
        }
        .other-msg {
            text-align: center;
            padding: 10px;
            span {
                margin: auto;
                font-size: 12px;
                color: #606060;
                padding: 8px;
                background: #d1d1d1;
                border-radius: 8px;
            }
        }
        .file-box{
            width: auto;
            background: #00000008;
            padding: 9px;
            border: 1px solid #ddd0;
            overflow: hidden;
            border-radius: 6px;
            a{
                color: #3371a7;
                text-decoration: none;
                font-size: 12px;
            }
        }
        .file-box-right{
            background: #F7F8FA!important;
        }
        .ris-data{
            line-height: 23px;
            text-align: left;
            color: #1D2129;
            div,strong{
                display: inline-block;
                margin: 0 3px;
            }
            img{
                float: left;
                margin: 0 3px;
            }
        }
        .ris-content{
            margin-top: 8px;
            font-weight: 600;
            color: #1D2129;
        }
    }
    .content-micro{
        height: calc(100% - 55px);
        position: relative;
        // background: #dddddd52;
        background: #f3f3f352;
    }
    .more-icon{
        position: absolute;
        right: 20px;
        top: 15px;
    }
    .more-icon-2{
        position: absolute;
        right: 50px;
        top: 15px;
    }
    .voicePlay {
    animation-name: voicePlay;
    animation-duration: 1s;
    animation-direction: normal;
    animation-iteration-count: infinite;
    animation-timing-function: steps(3);
    }

    @keyframes voicePlay {
        0% {
            background-position: 0;
        }
        100% {
            background-position: 100%;
        }
    }
    a {
        color: #3371a7;
        text-decoration: none;
    }
    /deep/ .el-image__inner--center{
        position:static;
        transform: none;
    }

</style>
