<!-- 历史记录 -->
<template>
  <div class="history">
        <div id="back-to-main" class="el-icon-arrow-left more-icon-3 cursor hide" @click="backToChart"></div>
        <div class="history-title">聊天记录</div>
        <div id="history-main" v-loading="loading">
            <div v-for="(item,index) in historyData" :key="index">
                <!--文字消息-->
                <div class="one-history" v-if="item.chatType === 0">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <span class="word-break fs-15">{{item.content}}</span>
                    </div>
                </div>
                <!--图片消息-->
                <div class="one-history" v-else-if="item.chatType === 1">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <span class="word-break">
                            <el-image style="max-width:100%;" :src="item.content" :preview-src-list="imgList"></el-image>
                        </span>
                    </div>
                </div>
                <!--附件消息-->
                <div class="one-history" v-else-if="item.chatType === 2">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <div class="left-chart one-chart">
                            <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 fs-12">{{item.content.fileSizeKb}}KB</div>
                                        <a class="inline-block ft-l fs-12" href="javascript:void(0);" @click="downloadFile(item.content.id,item.content.fileOriginName)">下载附件</a>
                                    </div>
                                </div>
                            </span>
                        </div>
                    </div>
                </div>
                <!--评论消息-->
                <div class="one-history" v-else-if="item.chatType === 3">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <div class="left-chart one-chart">
                            <span class="chart-line">
                                <div style="position:relative">
                                    <span>{{item.content.comment}}</span>
                                    <a href="javascript:void(0);" @click="risButtonClick">详情></a>
                                </div>
                                <div class="t-c 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 ellipse text-left">{{item.content.projectName}}</div>
                                </div>
                            </span>
                        </div>
                    </div>
                </div>
                <!--语音消息-->
                <div class="one-history" v-else-if="item.chatType === 4">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <div class="left-chart one-chart">
                            <div class="chart-line cursor" @click="voiceLineClick(item)">
                                <div class="triangle-left"></div>
                                <span class="voice-block flex-left" :style="`width:${item.content.width}px`">
                                    <div class="inline-block">{{item.content.Time}}s</div>
                                    <div :class="['trumpet','trumpet-left',item.voicePlay ? 'voicePlay':'']"></div>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <!--群组消息-->
                <div class="one-history" v-else-if="item.chatType === 5">
                    <div class="avatar" :style="`background:url(${item.sendUser.avatarImageUrl ? item.sendUser.avatarImageUrl :require('../../../static/avatar.jpg')}) 0 0 no-repeat;`"></div>
                    <div class="info-data">
                        <div class="info">
                            <span :class="['name',item.color]">{{item.sendUser.userName}}</span>
                            <span :class="['date',item.color]">{{item.createdTime}}</span>
                        </div>
                        <div class="other-msg">
                            <span>{{item.content}}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <ky-preview-dialog :url="url" :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: {
    myUserId: {
      String,
      default: ''
    },
    clickItem: {
      Object,
      default: () => {}
    },
    historyShow: {
      Boolean,
      default: false
    }
  },
  data () {
    return {
      historyData: [],
      loading: false,
      imgList: [],
      url: '',
      visible: false,
      previewType: ''
    }
  },
  watch: {
    historyShow (val) {
      if (val) {
        this.getHistoryData()
      }
    },
    clickItem (val) {
      if (val && this.historyShow) {
        this.getHistoryData()
      }
    }
  },
  computed: {},
  created () {},
  mounted () {
    // 监听滚动条滚动
    document.getElementById('history-main').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
        }
        getChartData(params).then(data => {
          if (data && data.length > 0) {
            this.height1 = document.getElementById('history-main').scrollHeight
            let arr = this.dealHistoryData(data)
            this.dealToImgList(data)
            this.historyData = arr.concat(this.historyData)
            this.lastContentTime = data[0].createdTime
            this.$nextTick(() => {
              let height2 = document.getElementById('history-main').scrollHeight
              document.getElementById('history-main').scrollTop = height2 - this.height1 + scrollTop
            })
          }
        })
      }
    }
  },
  methods: {
    backToChart () {
      this.$emit('update:historyShow', false)
    },
    risButtonClick () {
      let data = {
        type: 'openRis',
        data: {
          id: this.clickItem.item.groupId
        }
      }
      this.$chatUtils.postToParent(data)
    },
    getHistoryData () {
      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: 20
      }
      this.historyData = []
      this.loading = true
      this.imgList = []
      getChartData(params).then(data => {
        this.loading = false
        if (data && data.length > 0) {
          this.historyData = this.dealHistoryData(data)
          this.dealToImgList(data)
          this.lastContentTime = data[0].createdTime
          this.$nextTick(() => {
            setTimeout(() => {
              document.getElementById('history-main').scrollTop = document.getElementById('history-main').scrollHeight
            }, 10)
          })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    dealToImgList (data) {
      let arr = []
      data.forEach(value => {
        if (value.chatType === 1) {
          arr.push(value.content)
        }
      })
      this.imgList = arr.concat(this.imgList)
    },
    dealHistoryData (data) {
      data.forEach(value => {
        if (this.myUserId === value.sendUserId) {
          value.color = 'orange-color'
        } else {
          value.color = 'gray-color'
        }
        if (value.chatType === 3) { // 评论消息
          let obj = JSON.parse(value.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'
          }
          obj.img = img
          obj.icon = icon
          let comment = obj.comment
          if (comment.length > 42) {
            comment = comment.substring(0, 44)
            comment += '...'
            obj.comment = comment
          }
          value.content = obj
        } else if (value.chatType === 2) { // 附件消息
          let obj = JSON.parse(value.content)
          if (obj) {
            obj.typeImg = this.getFileType(obj.fileSuffix)
          } else {
            obj = {
              typeImg: '文件_未知.png'
            }
          }
          value.content = obj
        } else if (value.chatType === 4) { // 语音消息
          let content = JSON.parse(value.content)
          let width = this.maxVoiceWidth * (Number(content.Time) / voiceTime)
          content.width = width
          value.content = content
          value.voicePlay = false
        }
      })
      return data
    },
    dealContent (content, chatType) {
      if (chatType === 2) { // 文件消息
        let obj = JSON.parse(content)
        console.log('附件obj', content)
        let typeImg = this.getFileType(obj.fileSuffix)
        obj.typeImg = typeImg
        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
      }
    },
    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()
    },
    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
    },
    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>
.history{
    width: 479px;
    border-left: 1px solid rgba(0,0,0,0.2);
    background: #fff;
    height: 100%;
    position: relative;
    .one-history{
        margin: 0px 18px;
        padding: 10px 0;
        border-bottom: 1px solid #ddd;
        display: flex;
        .avatar{
            width: 35px;
            height: 35px;
            margin-right: 5px;
            border-radius: 5px;
            background-size: contain!important;
        }
        .info-data{
            width: 100%;
            .info{
                .name{
                    font-size: 12px;
                }
                .date{
                    font-size: 12px;
                    float: right;
                }
            }
            .left-chart{
                position: relative;
                .file-text{
                    float: left;
                    margin-right: 5px;
                }
                .name-chart{
                    margin-left: 40px;
                }
                .avatar{
                    float: left;
                    margin-top: 6px;
                }
                .left-name{
                    font-size: 12px;
                    color: #707070;
                }
                span{
                    background: #fff;
                    padding: 9px 12px;
                    border-radius: 10px 10px 10px 0px;
                    /* margin-left: 4px; */
                    display: inline-block;
                    text-align: left;
                    word-break: break-word;
                }
            }
            .one-chart .chart-line{
                display: inline-block;
                position: relative;
                /* max-width: 78%; */
            }
            .file-box{
                width: auto;
                background: #00000008;
                padding: 9px;
                border: 1px solid #ddd0;
                overflow: hidden;
                border-radius: 6px;
                .file-name{
                    margin-bottom: 5px;
                    /* min-width: 160px; */
                    max-width:180px;
                    white-space:nowrap;
                    overflow:hidden;
                    text-overflow:ellipsis;
                }
                .file-size{
                    color: #86909C;
                    display: inline-block;
                }
            }
            .ris-data div,.ris-data strong{
                display: inline-block;
                margin: 0 3px;
            }
            .ris-data{
                line-height: 23px;
                text-align: left;
                img{
                    float: left;
                    margin: 0 3px;
                }
            }
            .ris-content{
                margin-top: 8px;
                font-weight: 600;
            }
        }
        .word-break{
            word-break: break-word;
        }
        .voice-block{
            /* width: 150px; */
            text-align: right!important;
            display: flex!important;
            align-items: center;
            min-width: 70px;
            div{
                margin:0 3px;
            }
        }
    }
    #history-main{
        overflow: auto;
        height: calc(100% - 55px);
        color: #000;
    }
    .history-title{
        text-align: center;
        height: 54px;
        line-height: 54px;
        border-bottom: 1px solid rgba(0,0,0,0.2);
        background:#fff
    }
    .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: #337ab7;
        text-decoration: none;
    }

    .trumpet-left{
        background:url('/@/assets/声音-black.png') right 0 no-repeat;
    }
    .trumpet {
        width: 16px;
        height: 16px;
        background-size: 400%;
        display: inline-block;
    }
     .more-icon-3{
        position: absolute;
        top: 20px;
        left: 15px;
    }
    .other-msg {
        padding: 10px;
        span {
            margin: auto;
            font-size: 12px;
            color: #606060;
            padding: 8px;
            background: #d1d1d1;
            border-radius: 8px;
        }
    }
    /deep/ .el-image__inner--center{
        position:static;
        transform: none;
    }
}
</style>
