<template>
  <div id="show-chat" class="show-chats scroll" @scroll="getMoreMessages">
    <!-- 消息 -->
    <div class="chat-item" v-for="(chat, index) in chats" :key="index">
      <!-- 时间 -->
      <div class="chat-time" v-text="$options.filters.timeFilter(chat.CreateTime)"></div>
      <!-- 内容 -->
      <div class="chat-content" :class="{ 'chat-content-send': chat.SenderId === currentWeChatId }">
        <img class="img" v-if="notShow.indexOf(chat.ContentType) < 0" :src="getAvatar(chat)" :alt="'好友头像'" />

        <!-- 群成员id -->
        <div
          class="member-info"
          v-if="currentFriend.Members && chat.SenderId !== currentWeChatId && notShow.indexOf(chat.ContentType) === -1"
        >
          <span v-text="chat.SenderName"></span>
          <el-button style="margin-left: 10px; color: #909399; padding: 5px" type="plant" @click="atSomebody(chat)">
            @Ta
          </el-button>
          <!-- <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="currentFriend.Owner && currentFriend.Owner === currentWeChatId"
            type="plant"

            :disabled="knicking"
            :loading="knicking"
            @click="knickSomeBody(chat)"
          >
            踢人
          </el-button> -->
        </div>

        <!-- content -->
        <div
          class="content-content"
          :class="[
            { 'triangle-send': chat.SenderId === currentWeChatId && notShow.indexOf(chat.ContentType) === -1 },
            { triangle: notShow.indexOf(chat.ContentType) === -1 && chat.SenderId !== currentWeChatId },
            {
              'chat-room':
                currentFriend.Members && chat.SenderId !== currentWeChatId && notShow.indexOf(chat.ContentType) === -1
            },
            { 'system-info': notShow.indexOf(chat.ContentType) > -1 }
          ]"
        >
          <div
            :class="[
              { 'chat-picture': chat.ContentType === 'Picture' || chat.ContentType === 2 },
              { 'chat-voice': chat.ContentType === 'Voice' || chat.ContentType === 3 },
              { 'chat-video': chat.ContentType === 'Video' || chat.ContentType === 4 },
              { 'chat-link': chat.ContentType === 'Link' || chat.ContentType === 6 },
              { 'chat-file': chat.ContentType === 'File' || chat.ContentType === 8 },
              { 'chat-namecard': chat.ContentType === 'NameCard' || chat.ContentType === 9 },
              { 'chat-luckmoney': chat.ContentType === 'LuckyMoney' || chat.ContentType === 11 },
              { 'chat-moneytran': chat.ContentType === 'MoneyTrans' || chat.ContentType === 12 },
              { 'chat-app': chat.ContentType === 'WeApp' || chat.ContentType === 13 },
              { 'chat-system': notShow.indexOf(chat.ContentType) > -1 }
            ]"
            v-html="decodeChat(chat)"
            @click="whatToDo(chat)"
          ></div>
        </div>

        <!-- 发送结果 -->
        <div
          class="send-state"
          :class="{
            'chat-room':
              currentFriend.Members && chat.SenderId !== currentWeChatId && notShow.indexOf(chat.ContentType) === -1
          }"
        >
          <!-- 发送状态 -->
          <el-button
            type="text"
            v-if="chat.SenderId === currentWeChatId && !chat.MsgId"
            class="el-icon-loading"
          ></el-button>

          <!-- 收藏 -->
          <el-button
            v-if="chat.MsgId && collectionType.indexOf(chat.ContentType) >= 0"
            style="margin-left: 10px; color: #909399; padding: 5px"
            type="plant"
            title="收藏之后可以发送好友"
            @click="collectionMsg(chat)"
          >
            收藏
          </el-button>
          <!-- 撤回 -->
          <el-button
            style="margin-left: 10px; color: #909399; padding: 5px"
            v-if="
              chat.SenderId === currentWeChatId &&
              chat.hasOwnProperty('MsgRemoteId') &&
              revokeMap.indexOf(chat.ContentType) >= 0
            "
            type="plant"
            :disabled="chat.IsRevoke"
            @click="revokeMessageTask(chat)"
          >
            <span v-text="chat.IsRevoke ? '已撤回' : '撤回'"></span>
          </el-button>
          <!-- 转发 -->
          <!-- <el-button
            style="margin-left:10px;color:#909399;padding:5px;"
            v-if="chat.msgSvrId && revokeMap.indexOf(chat.ContentType) >=0"
            type="plant"

            class="el-icon-s-promotion"
            @click="canTransform(chat)"
          >转发</el-button>-->
        </div>
      </div>
    </div>

    <!-- 如果没有内容 -->
    <div v-if="chats.length === 0" class="chat-no"></div>

    <!-- 大图 -->
    <div id="bigImage" class="demo-image__preview big-img-box">
      <el-image
        id="bigImageBox"
        style="width: 100px; height: 100px"
        :src="bigImageUrl"
        :preview-src-list="[bigImageUrl]"
      ></el-image>
    </div>

    <!-- 红包详情 -->
    <el-dialog class="hb-details" title="红包详情" :visible.sync="hbDetailVisible">
      <ul class="hb-detail">
        <li>当前微信：{{ hbDetail.WeChatId }}</li>
        <li>红包来源：{{ hbDetail.HbUrl | hbUrlFilter }}</li>
        <li>红包总数：{{ hbDetail.TotalNum }}</li>
        <li>红包总金额：{{ hbDetail.TotalAmount }}</li>
        <li>已抢的数量：{{ hbDetail.RecNum }}</li>
        <li>已抢的金额：{{ hbDetail.RecAmount }}</li>
        <li>
          抢红包的好友列表
          <ul>
            <li v-for="(item, index) in hbDetail.Records" :key="index">
              <div>{{ item }}</div>
            </li>
          </ul>
        </li>
      </ul>
      <div class="hb-btns">
        <el-button type="info" @click="hbDetailVisible = false">取消</el-button>
        <el-button type="primary" @click="takeLuckMoney(hb2detail)">打开红包</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'

const errorImg = require('assets/svg/conversation-image-error.svg')
import { triggerHistoryMsgPushTask, downloadFileByMsgIdTask, MsgRevokeTask } from '@/api/webSocketApi'
import { addResources } from '@/api/httpApi'
import bus from '@/utils/bus'

import phiz from '@/utils/phiz.js'
import base64 from '@/utils/base64.js'

export default {
  data() {
    return {
      notShow: ['System', 'Sys_LuckyMoney', 'RoomSystem', 5, 16, 17], // 符合条件的将不显示头像
      revokeMap: ['Text', 'NameCard', 'Picture', 'Voice', 'Video', 'File', 'Link', 'WeApp'], // 符合的才显示撤回按钮
      bigImageUrl: 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png', // 大图的地址
      collectionType: [6, 13, 'Link', 'WeApp', 'Text', 'Picture'], // 能收藏的消息类型
      knicking: false, // 正在踢人
      hb2detail: {} // 群成员详情,
    }
  },
  computed: {
    ...mapGetters({
      currentMode: 'currentMode', // pc还是web
      currentUser: 'currentUser', // 当前用户信息
      currentWechat: 'conversation/currentWechat',
      currentChats: 'conversation/currentChats', // 聊天记录
      currentFriend: 'conversation/currentFriend', // 当前联系人
      currentFriendId: 'conversation/currentFriendId', // 当前联系人
      currentWeChatId: 'conversation/currentWeChatId', // 当前wxid
      contactsMap: 'conversation/contactsMap',
      hbDetail: 'conversation/hbDetail',
      luckMoneyMap: 'nedb/luckMoneyMap',
      atContent: 'conversation/content'
    }),
    // 默认显示10条聊天记录
    chats() {
      let chatsList = []
      if (this.currentChats.Messages) {
        // chatsList = JSON.parse(JSON.stringify(this.currentChats.Messages))
        chatsList = [...this.currentChats.Messages]
        chatsList = chatsList.sort((a, b) => {
          if (a.MsgRemoteId && b.MsgRemoteId) {
            return a.MsgRemoteId - b.MsgRemoteId
          } else {
            return a.CreateTime - b.CreateTime
          }
        })
        chatsList = chatsList.map((x) => {
          let xi = { ...x }
          try {
            if (x.Content) {
              let dContent = base64.decode(x.Content)
              xi.Content = dContent
              let regJson = new RegExp(/^{.+}$/)
              if (typeof dContent === 'string' && regJson.test(dContent)) {
                xi.jContent = JSON.parse(dContent)
              }
            } else {
              console.log('没有content的消息', x)
            }
          } catch (error) {
            console.log(error)
          }
          return xi
        })
      }
      return chatsList
    },
    // 群成员map
    membersMap() {
      let mm = {}
      if (this.currentFriend.Members) {
        this.currentFriend.Members.forEach((x) => {
          mm[x.RemoteId] = x
        })
      }
      return mm
    },
    // 显示红包详情
    hbDetailVisible: {
      get() {
        return this.$store.getters['conversation/hbDetailVisible']
      },
      set(v) {
        this.$store.commit('conversation/SET_HB_DETAIL_VISIBLE', v)
        if (!v) {
          this.$store.commit('conversation/SET_HB_DETAIL', {
            WeChatId: '', // 所属微信号
            Success: false,
            ErrMsg: '',
            HbUrl: '', //
            TotalNum: null, // 红包总个数
            TotalAmount: null, // 红包总金额
            RecNum: null, // 已收红包个数
            Records: [], // 已收红包个数
            RecAmount: null // 已收红包金额
          })
          this.hb2detail = {}
        }
      }
    }
  },
  watch: {
    // 监听好友变化
    currentFriendId(newId) {
      // 先重置聊天记录
      this.$store.commit('conversation/RESET_CURRENT_CHATS', this.currentWeChatId)
      if (newId) {
        triggerHistoryMsgPushTask(this.currentWeChatId, newId, 0, 0)
        let stt = setTimeout(() => {
          this.setBottom()
          clearTimeout(stt)
          stt = null
        }, 500)
      }
    }
  },
  mounted() {
    bus.$on('setScrollBottom', () => {
      let docSC = document.getElementById('show-chat')
      if (docSC) {
        let sh = document.getElementById('show-chat').scrollHeight
        let ch = document.getElementById('show-chat').clientHeight
        let st = document.getElementById('show-chat').scrollTop
        if (sh - ch - st < 20) {
          let stt = setTimeout(() => {
            this.setBottom()
            clearTimeout(stt)
            stt = null
          }, 100)
        }
      }
    })
  },
  methods: {
    // 获取聊天的头像
    getAvatar(chat) {
      let sid = chat.SenderId
      // 自己发的消息
      if (sid === this.currentWeChatId) {
        return this.currentWechat.Avatar
      } else {
        // 如果是群好友发的
        if (this.currentFriend.Members) {
          if (this.membersMap[sid]) {
            return this.membersMap[sid].Avatar || errorImg
          } else if (this.contactsMap[sid]) {
            return this.contactsMap[sid].Avatar || errorImg
          } else {
            return errorImg
          }
        } else {
          return this.currentFriend.Avatar || errorImg
        }
      }
    },
    // scroll消息置底
    setBottom() {
      let docSC = document.getElementById('show-chat')
      if (docSC) {
        let sh = document.getElementById('show-chat').scrollHeight
        let ch = document.getElementById('show-chat').clientHeight
        document.getElementById('show-chat').scrollTop = sh - ch
      }
    },
    // 获取更多消息
    getMoreMessages() {
      let st = document.getElementById('show-chat').scrollTop
      let sh = document.getElementById('show-chat').scrollHeight
      let ch = document.getElementById('show-chat').clientHeight
      if (st === 0 && sh > ch) {
        const { WxId, ConvId, Messages, HasMore } = this.currentChats
        if (HasMore) {
          let refMsgId = Messages ? Messages[Messages.length - 1].MsgRemoteId : ''
          triggerHistoryMsgPushTask(WxId, ConvId, refMsgId, 0)
          let sct = setTimeout(() => {
            document.getElementById('show-chat').scrollTop = 5
            clearTimeout(sct)
            sct = null
          }, 100)
        } else {
          this.$message({
            type: 'warning',
            message: '没有更多数据！',
            duration: 1000
          })
        }
      }
    },
    // 收藏
    collectionMsg(chat) {
      const { ContentType, Content, MsgRemoteId, jContent } = chat
      if (ContentType === 'Picture') {
        if (!jContent.url) {
          this.$message.warning('请先获取大图，再收藏！')
          return
        }
      }
      addResources(this.currentUser.SupplierId, Content, ContentType, MsgRemoteId)
        .then((res) => {
          if (res.code === 0) {
            this.$message.success('添加到素材库成功！')
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // base64解码 & 不同类型的消息解读
    decodeChat(chat) {
      const { ContentType, Content, jContent } = chat
      switch (ContentType) {
        // 文本 1
        case 'Text':
        case 1:
          return phiz.qqFaceImgMap(Content)
        // 图片 2
        case 'Picture':
        case 2:
          if (jContent) {
            if (jContent.url && jContent.url.startsWith('http://')) {
              // 大图
              return `<img style="max-width:200px;max-height:200px;" src="${jContent.url}" title="点击查看大图" alt="图片"/>`
            } else if (jContent.thumbUrl && jContent.thumbUrl.startsWith('http://')) {
              // 缩略图
              return `<img style="max-width:200px;max-height:200px;" src="${jContent.thumbUrl}" title="点击查看大图" alt="图片"/>`
            } else {
              // 没有图 或者 https://地址
              return `<img style="max-width:200px;max-height:200px;" src="${errorImg}" title="点击获取图片" alt="图片"/>`
            }
          } else {
            return `<img style="max-width:200px;max-height:200px;" src="${Content}" title="点击查看大图" alt="图片"/>`
          }
        // 语音 3
        case 'Voice':
        case 3:
          if (jContent) {
            if (jContent.url && jContent.url.endsWith('.mp3')) {
              return ` <audio src="${jContent.url}" alt="语音" controls></audio>`
            } else {
              return ` <p>${jContent.url}[语音]文件地址错误，点击重新获取</p>`
            }
          } else {
            return ` <audio src="${Content}" alt="语音" controls></audio>`
          }
        // 视频 4
        case 'Video':
        case 4:
          if (jContent) {
            if (jContent.url && jContent.url.startsWith('http://')) {
              return `<video style="max-width:300px;max-height:300px;" src="${jContent.url}" type="video/mp4" alt="视频" controls></video>`
            } else if (jContent.thumbUrl && jContent.thumbUrl.startsWith('http')) {
              return `<img style="max-width:300px;max-height:300px;"  src="${jContent.thumbUrl}"  alt="视频" />
                      <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击获取视频"></i>`
            } else {
              return `<img style="max-width:300px;max-height:300px;" src="${errorImg}"  alt="视频" />
                      <i class="fa fa-play-circle-o fa-2x play-video" aria-hidden="true" title="点击获取视频"></i>`
            }
          } else {
            return `<video style="max-width:300px;max-height:300px;" src="${Content}" type="video/mp4" alt="视频" controls></video>`
          }
        // 系统消息 5 ok
        case 'System':
        case 5:
          if (Content) {
            return Content
          } else {
            return '系统消息，内容没有获取到！'
          }
        // 链接消息 6
        case 'Link':
        case 6:
          if (jContent.TypeStr === '[聊天记录]') {
            return `<span class="link-title">${jContent.Title}</span><div class="link-content"><span class="link-des">${jContent.Des}...</span></div><div class="link-type">聊天记录</div>`
          } else if (jContent.title) {
            return `<span class="link-title">${jContent.title}</span><div class="link-content"><span class="link-des">${
              jContent.desc
            }</span><img class="link-img" src="${
              jContent.thumbUrl && jContent.thumbUrl.startsWith('http://www') ? jContent.thumbUrl : errorImg
            }" alt="链接图片" /></div><div class="link-type">链接</div>`
          } else {
            return jContent
          }
        // 扩展的链接消息（小程序分享等），内容为xml格式，暂未使用 7
        case 'LinkExt':
        case 7:
          return `LinkExt消息：${jContent}`
        // 文件 8
        case 'File':
        case 8:
          if (jContent) {
            let size = 0
            if (jContent.size) {
              if (jContent.size < 1024) {
                size = jContent.size + 'B'
              } else if (jContent.size < 1024 * 1024) {
                size = parseInt(jContent.size / 1024) + 'KB'
              } else {
                size = parseInt(jContent.size / (1024 * 1024)) + 'MB'
              }
            }
            let fileSize = jContent.Des ? jContent.Des.replace(/,.*/, '') : jContent.size ? size : ''
            let fileTitle = jContent.Title ? jContent.Title : jContent.name ? jContent.name : ''
            let fileType = jContent.Des
              ? jContent.Des.replace(/.*,/, '').trim()
              : jContent.name
              ? jContent.name.replace(/.*\./, '')
              : ''
            let fileSource = jContent.Source ? jContent.Source : '手机'
            let fileIcon = 'fa-question-circle-o'
            switch (fileType) {
              case 'doc':
              case 'docx':
                fileIcon = 'fa-file-word-o'
                break
              case 'xls':
              case 'xlsx':
                fileIcon = 'fa-file-excel-o'
                break
              case 'ppt':
              case 'pptx':
                fileIcon = 'fa-file-powerpoint-o'
                break
              case 'zip':
              case 'rar':
                fileIcon = 'fa-file-archive-o'
                break
              case 'text':
              case 'txt':
                fileIcon = 'fa-file-text-o'
                break
              case 'mp3':
                fileIcon = 'fa-file-sound-o'
                break
              default:
                fileIcon = 'fa-question-circle-o'
                break
            }
            return `<span class="file-title">${fileTitle}</span>
                    <div class="file-content">
                        <span class="file-des">${fileSize}</span>
                        <i class="fa ${fileIcon} file-icon" aria-hidden="true"></i>
                    </div>
                    <div class="file-type">${fileSource}</div>`
          } else {
            return Content
          }
        // 名片 9
        case 'NameCard':
        case 9:
          if (jContent) {
            return `<div class="namecard-info">
                      <img class="namecard-img" src="${jContent.avatar || errorImg}" alt="好友头像" />
                      <span class="namecard-nickname ellipsis2">${jContent.name || ''}</span>
                    </div>
                    <div class="namecard-tip">个人名片</div>`
          } else if (this.contactsMap[Content]) {
            return `<div class="namecard-info">
                        <img class="namecard-img" src="${
                          this.contactsMap[Content].Avatar || errorImg
                        }" alt="好友头像" />
                        <span class="namecard-nickname ellipsis2">${this.contactsMap[Content].Name || ''}</span>
                      </div>
                      <div class="namecard-tip">个人名片</div>`
          } else {
            return Content
          }
        // 位置信息 10
        case 'Location':
        case 10:
          return `位置消息：${Content}`
        // 红包 11
        case 'LuckyMoney':
        case 11:
          return `<div class="luck-info">
                    <span class="luck-img" > &nbsp;&nbsp;🧧 </span>
                    <span class="luck-wish ellipsis2" >${jContent.Title || '恭喜发财，大吉大利'}</span>
                    <span class="luck-flag ellipsis2" >${this.luckMoneyMap[chat.msgSvrId] ? '已领取' : ''}</span>
                    </div>
                    <div class="luckmoney-tip">微信红包</div>`
        // 转账 12
        case 'MoneyTrans':
        case 12: {
          let moneyTransFlag = ''
          let money = 0
          if (jContent.Feedesc) {
            money = jContent.Feedesc
          }
          switch (jContent.PaySubType) {
            case 1:
              if (chat.SenderId === this.currentWeChatId) {
                moneyTransFlag = `转账给${this.currentFriend.FriendNick}`
              } else {
                moneyTransFlag = '转账给你'
              }
              break
            case 3:
              moneyTransFlag = '已收钱'
              break
            default:
              break
          }
          let imgUrl = require('assets/svg/conversation-transfer-money.svg')

          if (jContent.PaySubType === 3) {
            return `
                          <div class="moneytran-info">
                              <img class="moneytran-img" src="${imgUrl}" alt />
                              <span class="moneytran-feed" >${money}</span>
                              <span class="moneytran-flag">${moneyTransFlag}</span>
                              <span class="moneytran-flag"></span>
                          </div>
                          <div class="moneytran-tip">微信转账</div>
                      `
          } else {
            let flag = this.luckMoneyMap[chat.msgSvrId] ? '已被领取' : ''
            return `
                          <div class="moneytran-info">
                              <img class="moneytran-img" src="${imgUrl}" alt />
                              <span class="moneytran-feed" >${money}</span>
                              <span class="moneytran-flag">${moneyTransFlag}</span>
                              <span class="moneytran-flag">${flag}</span>
                          </div>
                          <div class="moneytran-tip">微信转账</div>
                    `
          }
        }
        // 小程序 13
        case 'WeApp':
        case 13: {
          let appIcon = jContent.iconUrl ? jContent.iconUrl : errorImg
          let appSource = jContent.appName ? jContent.appName : '无效小程序'
          let appTitle = jContent.title ? jContent.title : '无效小程序'
          let appDes = jContent.desc ? jContent.desc : ''
          let appThumb = jContent.thumbUrl && jContent.thumbUrl.startsWith('http://www') ? jContent.thumbUrl : errorImg
          let appTypeStr = jContent.type === 2 ? '小程序' : jContent.type
          return `
                      <div class="app-des">
                      <img class="app-icon" src="${appIcon}" alt="icon" />
                      <span class="app-source ellipsis">${appSource}</span>
                      </div>
                      <div class="app-title ellipsis">${appTitle}</div>
                      <div class="app-content">
                          <span class="app-des">${appDes}</span>
                          <img class="app-img" src="${appThumb}" />
                      </div>
                      <div class="app-typestr">${appTypeStr}</div>
                       `
        }
        // Emoji 14
        case 'Emoji':
        case 14: {
          if (jContent.url) {
            return `<img style="width:100px;height:100px;" src="${jContent.url}" title="点击看大图" alt="图片"/>`
          }
          return Content
        }
        // 群管理消息 15
        case 'RoomManage':
        case 15:
          //   return content
          return 'RoomManage'
        // 红包系统消息 16
        case 'Sys_LuckyMoney':
        case 16:
          return jContent.Title || Content
        // 群系统消息 17 ok
        case 'RoomSystem':
        case 17:
          return jContent.title || Content
        // 公众号文章
        case 'BizLink':
        case 18:
          return Content
        // 语音通话
        case 'AudioCall':
        case 19:
          return Content
        // 视频通话
        case 'VideoCall':
        case 20:
          return Content
        // 服务通知
        case 'NotifyMsg':
        case 21:
          return `<span class="link-title">${jContent.source}</span>
                <div class="link-content">
                <span class="link-des">${jContent.title}...</span>
                </div>
                <div class="link-type">${jContent.des}</div>`
        // 引用通知
        case 'QuoteMsg':
        case 22:
          return Content
        // 转发的消息记录
        case 'ForwardMsg':
        case 23:
          return Content
        // 朋友圈通知
        case 'SnsNotify':
        case 24:
          return Content
        // 不支持的消息
        default:
          return `不支持的消息${chat.ContentType}：${Content}`
      }
    },
    // 点击事件
    whatToDo(chat) {
      switch (chat.ContentType) {
        case 'Voice':
        case 'Picture':
        case 'Video':
        case 'File':
          this.getChatDetail(chat)
          break
        case 'Link':
        case 6:
          this.openLink(chat)
          break
        case 'LuckyMoney':
        case 'MoneyTrans':
          // 查看红包
          this.queryHbDetailTask(chat)
          break
        default:
          console.log(chat)
          break
      }
    },
    // 下载文件
    fetchDetail(chat) {
      downloadFileByMsgIdTask(this.currentWeChatId, chat.MsgId, chat.MsgRemoteId, 0)
      this.$message({
        type: 'info',
        message: '正在从手机获取资源，请稍后再试！',
        duration: 1000
      })
    },
    // 获取聊天中各种资源的地址
    getChatDetail(chat) {
      const { ContentType, jContent } = chat
      if (jContent && jContent.url && jContent.url.startsWith('http://')) {
        const { url } = jContent
        if (ContentType === 'Picture') {
          // 展示大图
          this.bigImageUrl = url
          const imgDom = document.getElementById('bigImageBox')
          if (imgDom) {
            imgDom.click()
          }
        } else if (ContentType === 'File') {
          this.$confirm('下载该文件?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              // 下载文件 方法1
              // window.location.href = url
              // 下载文件 方法2
              const a = document.createElement('a')
              a.setAttribute('href', url)
              a.setAttribute('target', '_blank')
              a.setAttribute('id', 'file_a')
              // 防止反复添加
              if (document.getElementById('file_a')) {
                document.body.removeChild(document.getElementById('file_a'))
              }
              document.body.appendChild(a)
              a.click()
            })
            .catch(() => {})
        } else {
          return
        }
      } else {
        this.fetchDetail(chat)
      }
    },

    // 打开链接
    openLink(chat) {
      this.$message('打开链接，待实现！请联系开发者！')
      //   switch (jContent.TypeStr) {
      //     case '[聊天记录]':
      //       break
      //     default:
      //       if (jContent.Title === '邀请你加入群聊' || jContent.Title === '邀请您加入群聊') {
      //         let contentMsg = {
      //           WeChatId: chat.WeChatId, // 商家个人微信内部全局唯一识别码
      //           Talker: chat.FriendId, // 邀请者
      //           MsgSvrId: chat.msgSvrId, // 邀请消息的msgSvrId
      //           MsgContent: JSON.stringify(jContent) // 回传邀请信息的内容（json）
      //         }
      //         // 同意加入群聊
      //         this.$store.dispatch('websocket/AgreeJoinChatRoomTask', contentMsg)
      //       } else {
      //         let url = jContent.url
      //         if (this.currentMode === 'electron') {
      //           const { shell } = window.require('electron')
      //           shell.openExternal(url)
      //         } else {
      //           var a = document.createElement('a')
      //           a.setAttribute('href', url)
      //           a.setAttribute('target', '_blank')
      //           a.setAttribute('id', 'js_a')
      //           //防止反复添加
      //           if (document.getElementById('js_a')) {
      //             document.body.removeChild(document.getElementById('js_a'))
      //           }
      //           document.body.appendChild(a)
      //           a.click()
      //         }
      //       }
      //       break
      //   }
    },
    // 消息撤回
    revokeMessageTask(chat) {
      if (parseInt(new Date().getTime() / 1000, 10) - chat.CreateTime >= 60 * 2) {
        this.$message.warning('消息发出超过2分钟，不能测回！')
        return
      }
      MsgRevokeTask(chat.SenderId, chat.MsgRemoteId)
    },
    // @群成员
    atSomebody(chat) {
      const { SenderId, SenderName } = chat
      this.$store.commit('conversation/SET_REMARK', SenderId)
      this.$store.commit('conversation/SET_CONTENT', `${this.atContent}@${SenderName}\u2005`)
    },
    // 查看红包详情
    queryHbDetailTask(chat) {
      //   this.hb2detail = chat
      //   let content = ''
      //   let regJson = new RegExp(/^{.+}$/)
      //   content = chat.Content
      //   //   if (chat.FriendId.indexOf('@chatroom') > 0) {
      //   //     content = content.replace(/\S+?:/, '').replace(/^\n+|\n+$/g, "")
      //   //   }
      //   if (typeof content === 'string' && regJson.test(content)) {
      //     content = JSON.parse(content)
      //   }
      //   if (!content.Key || !chat.WeChatId) return
      //   // 获取详情
      //   this.$store.dispatch('websocket/QueryHbDetailTask', {
      //     WeChatId: chat.WeChatId,
      //     HbUrl: content.Key
      //   })
      //   this.$message({
      //     type: 'info',
      //     message: '正在获取红包详情！',
      //     duration: 1000
      //   })
    },
    // 收红包
    takeLuckMoney(chat) {
      //   let content = ''
      //   let regJson = new RegExp(/^{.+}$/)
      //   content = chat.Content
      //   if (typeof content === 'string' && regJson.test(content)) {
      //     let jContent = JSON.parse(content)
      //     let time = parseInt(new Date().getTime() / 1000)
      //     if (chat.SenderId === this.currentWeChatId) {
      //       // 如果是收转账的提示 不做处理
      //       if (jContent.PaySubType && jContent.PaySubType === 3) {
      //         return
      //       }
      //     } else {
      //       // 判断是否打开过
      //       // 如果该消息已经打开
      //       if (this.luckMoneyMap[chat.msgSvrId]) {
      //         // 转账本身已经显示状态和金额 就不再弹框展示
      //         // 这是弹框展示红包的金额
      //         if (chat.ContentType === 'LuckyMoney') {
      //           let amount = 0
      //           amount = '￥：' + this.luckMoneyMap[chat.msgSvrId].Amount
      //           this.$alert('金额' + amount + ' 分', '已经打开', {
      //             confirmButtonText: '确定',
      //             callback: (action) => {
      //               return true
      //             }
      //           })
      //         }
      //       } else {
      //         // 收转账的消息 不做处理
      //         if (chat.ContentType === 'MoneyTrans' && jContent.PaySubType === 3) return
      //         // 红包或者转账过期 不再处理
      //         if (time - content.InvalidTime >= 24 * 60 * 60) {
      //           this.$message.warning('已过期')
      //         } else {
      //           // 打开红包
      //           let msgContent = {
      //             WeChatId: chat.WeChatId,
      //             FriendId: chat.FriendId,
      //             MsgSvrId: chat.MsgSvrId ? chat.MsgSvrId : chat.msgSvrId,
      //             MsgKey: jContent.Key
      //           }
      //           this.$store.dispatch('websocket/TakeLuckyMoneyTask', msgContent)
      //         }
      //       }
      //     }
      //   }
    }
    // // 能转发
    // canTransform(chat) {
    //   let validType = [1, 2, 3, 6, 13, 'Text', 'Picture', 'Voice', 'Link', 'WeApp']
    //   this.$message.info('改功能待实现！')
    //   //   if (validType.indexOf(chat.ContentType) >= 0) {
    //   //     // 能转发
    //   //   } else {
    //   //     // 不能转发
    //   //   }
    // },
    // // 踢人
    // knickSomeBody(chat) {
    //   // 先判断该好友是否还在群里
    //   let memberId = chat.Content.split(':')[0]
    //   let memberName = this.getMemberName(chat.Content)
    //   this.$confirm(`是否确认删除成员 ${memberName} ?`, '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       this.knicking = true
    //       let message = {
    //         WeChatId: this.currentWeChatId, //string 商家所属微信号
    //         ChatRoomId: this.currentFriend.UserName, //string 群聊id
    //         Action: 3, //EnumChatRoomAction 指令
    //         Content: memberId //string 指令内容
    //       }
    //       this.$store.dispatch('websocket/ChatRoomActionTask', message)
    //       setTimeout(() => {
    //         this.knicking = false
    //       }, 2000)
    //     })
    //     .catch(() => {
    //       this.$message({
    //         type: 'info',
    //         message: '已取消删除'
    //       })
    //     })
    // }
  }
}
</script>

<style lang="scss" scoped>
.big-img-box {
  position: absolute;
  top: 0;
  right: -200px;
}

.show-chats {
  height: 65%;
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;

  .chat-item {
    display: flex;
    flex-direction: column;
    margin: 5px;

    .chat-time {
      width: 160px;
      height: 20px;
      font-size: 14px;
      line-height: 20px;
      border-radius: 5px;
      color: white;
      margin: 5px auto;
      align-self: center;
      text-align: center;
      background: #dadada;
    }

    .chat-content {
      display: flex;
      position: relative;
      padding-top: 10px;
      font-size: 12px;
      color: $font-color-base;

      .img {
        width: 42px;
        height: 42px;
        margin: 5px 5px 5px 0;
        // margin: 5px;
        font-size: 14px;
      }

      .member-info {
        max-width: 60%;
        position: absolute;
        color: $font-color-2;
        top: 0;
        left: 58px;
      }
      .content-content {
        max-width: 60%;
        min-height: 40px;
        line-height: 25px;
        padding: 5px;
        margin-left: 7px;
        border-radius: 5px;
        display: flex;
        align-items: center;
        position: relative;
        background: white;
        word-break: break-all;
        border: 1px solid #e7e7e7;

        .chat-picture {
          display: flex;
          align-items: center;
        }
        .chat-voice {
          width: 300px;
          max-width: 100%;
          display: flex;
          align-items: center;
        }
        ::v-deep .chat-video {
          display: flex;
          align-items: center;
          position: relative;
          .play-video {
            color: #98e165;
            position: absolute;
            font-size: 50px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            cursor: pointer;
          }
        }
        ::v-deep .chat-system {
          color: gray;
          a {
            color: #41c0fc;
          }
        }
        ::v-deep .chat-link {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .link-title {
            font-size: 16px;
            font-weight: 600;
          }
          .link-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .link-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 14px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }
            .link-img {
              max-width: 50px;
              max-height: 50px;
              min-height: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
          }
          .link-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }
        ::v-deep .chat-file {
          flex-direction: column;
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .file-title {
            font-size: 16px;
            font-weight: 600;
          }
          .file-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .file-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 14px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }
            .file-icon {
              font-size: 30px;
              margin-right: 20px;
            }
          }
          .file-type {
            color: #aaaaaa;
            margin-top: 5px;
            text-align: start;
            border-top: solid #e8eaec 1px;
          }
        }
        ::v-deep .chat-app {
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          display: flex;
          flex-direction: column;
          .app-des {
            display: flex;
            .app-icon {
              width: 20px;
              height: 20px;
            }
            .app-source {
              width: 100%;
              font-size: 12px;
              margin-left: 5px;
              color: gray;
            }
          }
          .app-title {
            width: 100%;
            height: 30px;
            font-size: 14px;
            font-weight: 600;
            line-height: 30px;
          }
          .app-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .app-des {
              flex: auto;
              color: #aaaaaa;
              font-size: 14px;
              margin-right: 5px;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
              word-wrap: break-word;
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 3;
            }
            .app-img {
              max-width: 50px;
              max-height: 50px;
              min-height: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
          }
          .app-img {
            align-self: center;
            max-width: 200px;
          }
          .app-typestr {
            height: 25px;
            margin-top: 5px;
            line-height: 25px;
            color: gray;
            text-align: start;
            border-top: solid #aaaaaa 1px;
          }
        }
        ::v-deep .chat-namecard {
          width: 300px;
          max-width: 100%;
          cursor: pointer;
          .namecard-info {
            display: flex;
            align-items: center;
            .namecard-img {
              height: 50px;
              width: 50px;
              min-width: 50px;
              border-radius: 5px;
            }
            .namecard-nickname {
              width: 250px;
              font-size: 14px;
              margin-left: 5px;
            }
          }
          .namecard-tip {
            color: gray;
            margin-top: 5px;
            border-top: #aaaaaa solid 1px;
          }
        }
        ::v-deep .chat-luckmoney {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;
          .luck-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;
            .luck-img {
              max-width: 50px;
            }

            .wish-open {
              display: flex;
              flex-direction: column;
            }

            .luck-wish {
              width: 200px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .luck-flag {
              width: 60px;
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }

            .money-opened {
              margin-left: 10px;
              color: white;
            }
          }
          .luckmoney-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }
          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }
        ::v-deep .chat-moneytran {
          width: 300px;
          max-width: 100%;
          background: #fa9d3b;
          cursor: pointer;
          .moneytran-info {
            display: flex;
            align-items: center;
            height: 60px;
            width: 100%;
            .moneytran-img {
              max-width: 30px;
              margin-left: 10px;
            }
            .moneytran-feed,
            .moneytran-flag {
              font-size: 14px;
              margin-left: 10px;
              color: white;
            }
          }
          .moneytran-tip {
            color: gray;
            background: white;
            margin-top: 5px;
          }
          &:hover {
            background: rgba($color: #fa9d3b, $alpha: 0.9);
          }
        }
      }

      .send-state {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .chat-room {
        margin-top: 20px;
      }
      .triangle {
        &::before {
          content: '';
          border: 6px solid transparent;
          border-right: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          left: -13px;
        }
        &::after {
          content: '';
          border: 6px solid transparent;
          border-right: 6px solid white;
          position: absolute;
          top: 10px;
          left: -12px;
        }
        &:hover {
          background-color: #f6f6f6;
          &::after {
            content: '';
            border: 6px solid transparent;
            border-right: 6px solid #f6f6f6;
            position: absolute;
            top: 10px;
            left: -12px;
          }
        }
      }
      .triangle-send {
        margin-right: 7px;
        background: #9eea6a;
        &::before {
          content: '';
          border: 6px solid transparent;
          border-left: 6px solid #e7e7e7;
          position: absolute;
          top: 10px;
          right: -13px;
        }
        &::after {
          content: '';
          border: 6px solid transparent;
          border-left: 6px solid #9eea6a;
          position: absolute;
          top: 10px;
          right: -12px;
        }

        &:hover {
          background-color: #98e165;
          &::after {
            border-left: 6px solid #98e165;
          }
        }
      }
      .system-info {
        border: none;
        max-width: 80%;
        margin: 0 auto;
        background: inherit;
      }
    }

    .chat-content-send {
      flex-direction: row-reverse;
      .img {
        margin: 5px 0 5px 5px;
      }
    }
  }
  ::v-deep .detail-dialog {
    overflow: hidden;
    .el-dialog {
      overflow: hidden;
      height: 500px;
      min-width: 500px;
      display: flex;
      flex-direction: column;

      .el-dialog__body {
        overflow: hidden;
        margin: auto;
        flex: 1 1 auto;
        display: flex;
        align-items: center;
        justify-content: center;

        .detail-dialog-img {
          @include scroll;
          max-height: 100%;
          max-width: 100%;
          overflow: auto;
        }
        .detail-dialog-video {
          max-height: 100%;
          width: auto;
        }
      }
    }
  }
  .chat-no {
    width: 100%;
    height: 100%;
    background-image: url(~@/assets/images/kdd64.png);
    background-repeat: no-repeat;
    background-color: $bg-color-content-base;
    background-position: center;
  }
  .member-detail {
    display: flex;
    flex-direction: column;
    ::v-deep .el-dialog {
      width: 500px;
      .el-dialog__body {
        padding: 20px;
      }
    }
    .member-detail-info {
      display: flex;
      .member-detail-text {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20px;
        overflow: hidden;
      }
    }
    .member-detail-btns {
      display: flex;
      justify-content: space-around;
      margin-top: 20px;
    }
  }
  .hb-details {
    display: flex;
    flex-direction: column;
    ::v-deep .el-dialog {
      width: 500px;
      .el-dialog__body {
        padding: 20px;
      }
    }
    .hb-btns {
      margin-top: 10px;
    }
  }
}
</style>
