<template>
    <div
        class="conversation-item-container"
        :class="{ 'choose': conversation.conversationID === currentConversation.conversationID }"
        @click="selectConversation"
    >
      <div class="close-btn">
        <span class="tim-icon-close" title="删除会话" @click="deleteConversation"></span>
      </div>
      <div class="warp">
        <div class="avatar-wrapper">
          <avatar :src="avatar" :type="conversation.faceURL" class="avatar" />
          <img v-if="avatarBorder" :src="avatarBorder" class="avatar-border" />
        </div>
        <div class="c-content">
          <div class="row-1">
            <div class="name">
              <div class="text-ellipsis">
                <span :title="conversation.showName || conversation.userID"
                      v-if="conversation.conversationType ===  1"
                >{{conversation.remark || conversation.showName || conversation.userID}}
                </span>
<!--                <span :title="conversation.groupProfile.name || conversation.groupProfile.groupID"
                  v-else-if="conversation.type ===  TIM.TYPES.CONV_GROUP"
                  >{{conversation.groupProfile.name || conversation.groupProfile.groupID}}
                </span>-->
                <span
                  v-else-if="conversation.conversationType === 4"
                  >系统通知
                </span>
              </div>
            </div>
            <div class="unread-count">
              <span class="badge" v-if="showUnreadCount">
                {{conversation.unreadCount > 99 ? '99+' : conversation.unreadCount}}
              </span>
            </div>
          </div>
          <div class="row-2">
            <div class="summary">
              <div v-if="conversation.conversationID" class="text-ellipsis">
                <span class="remind" v-if="hasMessageAtMe">{{ messageAtMeText }}</span>
                <span class="text" :title="messageForShow">
                  {{ messageForShow }}
                </span>
              </div>
            </div>
            <div class="date">
              {{date}}
            </div>
          </div>
        </div>
      </div>
    </div>

</template>

<script>
import { mapGetters, mapState } from 'vuex'
import { isToday, getDate, getTime } from '../../utils/date'
import { getOpenIM } from '@/utils/openIM';
import doctorBorder from '@/assets/doctor.svg'
import guanjiaBorder from '@/assets/guanjia.svg'

export default {
  name: 'conversation-item',
  props: ['conversation'],
  data() {
    return {
      popoverVisible: false,
      showMessageAtMe_text:'',
      OpenIM: null,
      lastMsg : {},
    }
  },
  computed: {
    avatarBorder() {
      if (this.conversation.userID?.startsWith('D')) {
        return doctorBorder
      } else if (this.conversation.userID?.startsWith('C')) {
        return guanjiaBorder
      }
      return null
    },
    hasMessageAtMe() {
      return (
              this.currentConversation.conversationID !==
              this.conversation.conversationID && this.conversation.groupAtInfoList && this.conversation.groupAtInfoList.length > 0
      )
    },
    messageAtMeText() {
      let text = ''
      if (this.conversation.groupAtInfoList.length > 0) {
        this.conversation.groupAtInfoList.forEach((item) => {
          if (item.atTypeArray[0] === 1) {
            text.indexOf('[@所有人]') !== -1 ? text = '[@所有人][有人@我]' : text = '[有人@我]'
          }
          if (item.atTypeArray[0] === 2) {
            text.indexOf('[有人@我]') !== -1 ? text = '[有人@我][@所有人]' : text = '[@所有人]'
          }
          if (item.atTypeArray[0] === 3) {
            text = '[@所有人][有人@我]'
          }
        })
      }
      return text
    },
    showUnreadCount() {
      if (this.$store.getters.hidden) {
        return this.conversation.unreadCount > 0
      }
      // 是否显示未读计数。当前会话和未读计数为0的会话，不显示。
      return (
        this.currentConversation.conversationID !==
          this.conversation.conversationID && this.conversation.unreadCount > 0
      )
    },
    date() {
      if (
        !this.conversation.latestMsg ||
        !this.conversation.latestMsgSendTime
      ) {
        return ''
      }
      const date = new Date(this.conversation.latestMsgSendTime)
      if (isToday(date)) {
        return getTime(date)
      }
      return getDate(date)
    },
    avatar: function() {
      switch (this.conversation.conversationType) {
        case 3:
          return this.conversation.faceURL
        case 1:
          return this.conversation.faceURL
        default:
          return ''
      }
    },
    conversationName: function() {
      if (this.conversation.conversationType === 1) {
        return this.conversation.showName || this.conversation.userID
      }
      if (this.conversation.conversationType === 3) {
        return this.conversation.groupProfile.name || this.conversation.groupProfile.groupID
      }
      if (this.conversation.conversationType === 4) {
        return '系统通知'
      }
      return ''
    },
    showGrayBadge() {
      if (this.conversation.conversationType !== 4) {
        return false
      }
      return (
        this.conversation.groupProfile.selfInfo.messageRemindType ===
        'AcceptNotNotify'
      )
    },
    messageForShow() {
      this.lastMsg = JSON.parse(this.conversation.latestMsg)
      /*if (this.lastMsg.contentType === 2101) {
        if (this.lastMsg.sendID === this.$store.getters.userID) {
          return '你撤回了一条消息'
        }
        if (this.lastMsg.sessionType === 1) {
          return '对方撤回了一条消息'
        }
        return `${this.lastMsg.sendID}撤回了一条消息`
      }*/
      let text = ''
      switch (this.lastMsg.contentType) {
        case 2101:
          if (this.lastMsg.sendID === this.$store.getters.userID) {
            return '你撤回了一条消息'
          }
          if (this.lastMsg.sessionType === 1) {
            return '对方撤回了一条消息'
          }
          return `${this.lastMsg.sendID}撤回了一条消息`
        case 101:
          text = this.lastMsg.textElem.content || ''
          if (text.length > 20) {
            text = text.slice(0, 20)
          }
          return text
        case 107:
          return '[聊天记录]'
        case 102:
          return '[图片]'
        case 103:
          return '[音频]'
        case 104:
          return '[视频]'
        case 110:
          return '[自定义消息]'
        case 105:
          return '[文件]'
        case 115:
          return '[动画表情]'
        case 1701:
          return '[阅后即焚]'
        case 1201:
          return '[成为好友通知]'
        case 114:
          return '[引用消息]'
      }
      //return  this.lastMsg.textElem.content
    },
    ...mapState({
      currentConversation: state => state.conversation.currentConversation,
      currentUserProfile: state => state.user.currentUserProfile,
      userID: state => state.imuser.userID,
    }),
    ...mapGetters(['toAccount'])
  },
  mounted() {
    this.OpenIM = getOpenIM()
  },
  methods: {
    selectConversation() {
      //console.log("this.currentConversation.conversationID"+this.currentConversation.conversationID)
      if (this.conversation.conversationID !== this.currentConversation.conversationID) {
        console.log("用户id"+this.conversation.userID)
        console.log("会话类型"+this.conversation.conversationType)
        this.$store.dispatch(
          'checkoutConversation',
          this.conversation,
        )
      }
    },
    deleteConversation(event) {
      // 停止冒泡，避免和点击会话的事件冲突
      event.stopPropagation()
      this.OpenIM
        .deleteConversationAndDeleteAllMsg(this.conversation.conversationID)
        .then(() => {
          this.$store.commit('showMessage', {
            message: `会话【${this.conversationName}】删除成功!`,
            type: 'success'
          })
          this.popoverVisible = false
          this.$store.commit('resetCurrentConversation')
        })
        .catch(error => {
          this.$store.commit('showMessage', {
            message: `会话【${this.conversationName}】删除失败!, error=${error.message}`,
            type: 'error'
          })
          this.popoverVisible = false
        })
    },
    showContextMenu() {
      this.popoverVisible = true
    },
  }
}
</script>

<style lang="stylus" scoped>
  .avatar-wrapper
    position relative
    width 40px
    height 40px
    margin-right 10px
    flex-shrink 0

  .avatar
    width 100%
    height 100%
    border-radius 50%
    display block

  .avatar-border
    position absolute
    top 0
    left 0
    width 100%
    height 100%
    pointer-events none

  .conversation-item-container
    padding 15px 20px
    cursor pointer
    position relative
    overflow hidden
    transition .2s
    &:hover
      background-color $background
      .close-btn
        right 3px

  .close-btn
    position absolute
    right -20px
    top 3px
    color $font-dark
    transition all .2s ease
     &:hover
       color $danger

  .warp
    display flex

  .avatar
    width 40px
    height 40px
    margin-right 10px
    border-radius 50%
    flex-shrink 0
  .c-content
    flex 1
    height 40px
    overflow hidden

    .row-1
      display flex
      line-height 21px

       .name
         color $font-light
         flex 1
         min-width 0px

       .unread-count
         padding-left 10px
         flex-shrink 0
         color $font-dark
         font-size 12px

         .badge
           vertical-align bottom
           background-color $danger
           border-radius 10px
           color #FFF
           display inline-block
           font-size 12px
           height 18px
           max-width 40px
           line-height 18px
           padding 0 6px
           text-align center
           white-space nowrap

    .row-2
      display flex
      font-size 12px
      padding-top 3px

      .summary
        flex 1
        overflow hidden
        min-width 0px
        color $secondary

        .remind
          color $danger

        .date
          padding-left 10px
          flex-shrink 0
          text-align right
          color $font-dark

    .choose
     background-color $background

    .context-menu-button
      padding 10px
      border 2px solid $primary
      border-radius 8px
</style>
