<template>
  <div
    class="pub-chat-item"
    :class="{'current': item.session_id == curSession, 'top':item.is_pin==1}"
    @click="changeSessionId(item)"
    @contextmenu.prevent="onToolBtn"
  >
    <div class="avatar-wrap">
      <i class="mute mute-point" v-if="item.unread>0 && item.is_mute==1"></i>
      <i class="mute mute-num" v-else-if="item.unread>0 && item.is_mute==0">{{item.unread}}</i>
      <img v-if="item.cover_photo" class="user-avatar" :src="item.cover_photo" alt>
      <div
        v-else
        class="user-avatar"
        :class="`avatar_bg${bgColorNum(item.session_id)}`"
        :data-name="item.name && item.name.slice(0,2).toUpperCase()"
      ></div>
      <i class="icon-auth" v-if="item.is_auth==1"></i>
    </div>
    <div class="info">
      <h3>
        <i class="icon-group" v-if="item.is_group==1"></i>
        <span>{{item.name}}</span>
      </h3>
      <p><span v-if="item.unread>0 && item.is_mute==1">[{{item.unread}}{{$t('public.item')}}]</span>
      <template v-if="item.last_msg">
        <template v-if="item.last_msg.msg_type==5">
          <template v-if="item.last_msg.event_type=='grab_redpack'">
            {{(userInfo && userInfo.user_id) == item.last_msg.from ? $t('public.you') : item.last_msg.nick_name}} {{$t('redPacket.receiveRedpack')}}
          </template>
          <template v-else-if="item.last_msg.event_type=='join'">
            {{(userInfo && userInfo.user_id) == item.last_msg.from ? $t('public.you') : item.last_msg.nick_name}} {{$t('chat.joinGroup')}}
          </template>
        </template>
        <template v-else-if="item.is_group">
          {{item.last_msg.nick_name}}:{{item.last_msg.msg_type === 0? item.cont:item.last_msg.msg_type=== -1? $t('chat.revokeMsg'):`[${$t(`chat.msgType[${item.last_msg.msg_type - 1}]`)}]`}}
        </template>
        <template v-else>
          {{item.last_msg.msg_type === 0? item.cont:item.last_msg.msg_type=== -1?`${userId == item.last_msg.from ? $t('public.you'):item.last_msg.nick_name}${$t('chat.revokeMsg')}` :`[${$t(`chat.msgType[${item.last_msg.msg_type - 1}]`)}]`}}
        </template>
      </template>
      </p>
      <span class="time">{{ handleUpdate(item.update_time_int)}}</span>
      <i class="icon-mute" v-if="item.is_mute==1"></i>
    </div>
    <ul
      class="pub-pop-toolbar ext-session"
      v-if="item.session_id"
      v-show="showToolbar"
      :style="{left:toolBarLeft,top:toolBarTop}"
    >
      <li
        @click.stop="changePin(item.session_id,item.is_pin)"
      >{{item.is_pin==1?`${$t('public.cancel')}${$t('chat.sticky')}`:$t('chat.sticky')}}</li>
      <li
        @click.stop="changeMute(item.session_id,item.is_mute)"
      >{{item.is_mute==1?$t('group.cancelDisturb'):$t('group.doNotDisturb')}}</li>
      <li @click.stop="delSession(item.session_id)">{{$t('chat.deleteSession')}}</li>
    </ul>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import API from '@/api'
import { confirmPopup, formatMsgTime, getMeechatType, getAvatarBgColor } from '@/util/util'

export default {
  name: 'msgItem',
  props: {
    item: {
      type: Object
    }
  },
  data () {
    return {
      toolBarLeft: 0,
      toolBarTop: 0,
      showToolbar: false,
      meechatType: getMeechatType()// meechat版本
    }
  },
  computed: {
    ...mapState(['curSession', 'userId']),
    userInfo () {
      return this.$store.state.userInfo
    }
  },
  methods: {
    changeSessionId (item) {
      let path =
        item.is_group == 1
          ? `/group/${item.session_id}`
          : `/pm/${item.session_id}`
      this.$router.push({ path })
    },
    bgColorNum (str) {
      return getAvatarBgColor(str, this.userId)
    },
    hideToolbar (event) {
      if (this.showToolbar !== false) {
        this.showToolbar = false
        document.body.removeEventListener('click', this.hideToolbar, false)
        document.body.removeEventListener('contextmenu', this.hideToolbar, false)
      }
    },
    getPagePos (target) {
      let current = target
      let actualX = 0
      let actualY = 0

      while (!/pub-chat-item/ig.test(current.getAttribute('class'))) {
        current = current.offsetParent
      }
      while (current != null) {
        actualX += current.offsetLeft
        actualY += current.offsetTop
        current = current.offsetParent
      }

      return {
        actualX, actualY
      }
    },
    onToolBtn (event) {
      if (this.showToolbar) {
        this.hideToolbar(event)
        return
      }

      let parentWidth = this.meechatType == 'h5' ? window.innerWidth : 276
      let popWidth = 100

      let { actualX } = this.getPagePos(event.target)
      let { pageX } = event
      let x = pageX - actualX

      let maxX = parentWidth - popWidth - 20
      this.toolBarLeft = x < maxX ? `${x}px` : `${maxX}px`

      setTimeout(() => {
        document.body.addEventListener('click', this.hideToolbar, false)
        document.body.addEventListener(
          'contextmenu',
          this.hideToolbar,
          false
        )
      }, 0)

      this.showToolbar = true
    },
    /**
     * @des 置顶聊天相关操作
     * @param {Number}
     * @param {String} val {1: 取消, 0: 置顶}
     */
    async changePin (sessionId, val) {
      let opt = val == 0 ? 'setPin' : 'cancelPin'
      let optRes = val == 0 ? 'updateSessionListByPin' : 'cancelSessionListByPin'

      let res = await API.session[opt]({
        session_id: sessionId
      })

      let data = res.data.data
      this.$store.commit('updatePin', val)
      this.hideToolbar()

      // 更新侧边栏的顺序
      this.$store.commit(optRes, {
        session_id: sessionId,
        is_pin: data.is_pin,
        pin_time_int: data.pin_time_int
      })
    },
    /**
     * @des 消息免打扰
     * @param {String} val 消息免打扰{1: 取消免打扰, 0: 免打扰}
     */
    async changeMute (sessionId, val) {
      let opt = val == 0 ? 'setMute' : 'cancelMute'
      let optRes = val == 0 ? 'updateSessionListByMute' : 'cancelSessionListByMute'

      await API.session[opt]({
        session_id: sessionId
      })

      this.hideToolbar()
      this.$store.commit('updateMute', val)

      // 更新侧边栏的顺序
      this.$store.commit(optRes, sessionId)
    },
    // 删除会话
    delSession (sessionId) {
      confirmPopup(this.$t('chat.closeSessionMsg')).then(() => {
        //        API.session
        //          .deleteSession({
        //            session_id: sessionId
        //          })
        //          .then(() => {
        //            this.$store.commit('removeSessionListById', sessionId)
        //            this.$showTips(this.$t('chat.quitSessionSucc'))
        //            this.hideToolbar()
        //            // 如果正在打开该会话，重置路由
        //            if (this.curSession == sessionId) {
        //              this.$store.commit('changeSessionId', 0)
        //              this.$router.push({ path: '/' })
        //            }
        //          })

        this.$store.commit('removeSessionListById', sessionId)
        this.hideToolbar()
        // 如果正在打开该会话，重置路由
        if (this.curSession == sessionId) {
          this.$store.commit('changeSessionId', 0)
          this.$router.push({ path: '/' })
        }
      })
    },
    handleUpdate (val) {
      return formatMsgTime(val, 1, this)
    }
  }
}
</script>

<style lang="scss">
.pub-chat-item {
  padding: 10px 13px 10px 20px;
  height: 40px;
  cursor: pointer;
  position: relative;
  @include webkitbox(1);
  &:hover {
    background: #383b41;
  }
  &:before{
    content: "";
    position: absolute;
    top: 10px;
    right: 2px;
    display: none;
    @include triangle-topright(4px,#1c93ec)
  }
  &.top{
    &:before{
      display: block;
    }
  }
  &.current {
    background: #3f424c;
    cursor: default;
  }
  .ext {
    position: absolute;
    background-color: #f12f28;
    color: #fff;
    text-align: center;
  }
  .info {
    @include flex(1);
    position: relative;
    padding-right: 27px;
    margin-left: 10px;
    h3 {
      font-size: 13px;
      color: #fff;
      line-height: 20px;
      @include ellipsis;
      span {
        display: inline-block;
        max-width: 130px;
        @include ellipsis;
        vertical-align: middle;
      }
      .icon-group {
        display: inline-block;
        vertical-align: middle;
        width: 15px;
        height: 12px;
        margin-right: 4px;
        background: url("../../assets/icon-chat-group.png") center center;
      }
    }
    p {
      font-size: 12px;
      line-height: 20px;
      color: #7c8ca5;
      @include ellipsis;
    }
    .time{
      position: absolute;
      top: 0;
      right: 0;
      font-size: 12px;
      line-height: 20px;
      color: #7c8ca5;
    }
  }
  .icon-mute {
    position: absolute;
    right: 0;
    bottom: 2px;
    width: 12px;
    height: 13px;
    margin-left: 4px;
    background: url("../../assets/icon-chat-mute.png");
  }
  .avatar-wrap {
    position: relative;
    .mute {
      position: absolute;
      top: -7px;
      right: -7px;
      background: #ff0000;
      color: #fff;
      font-size: 12px;
      padding: 2px 5px;
      border-radius: 12px;
      z-index: 2;
    }
    .mute-point{
      width: 12px;
      height: 12px;
      padding: 0;
      border-radius: 50%;
      top: -6px;
      right: -6px;
    }
    .icon-auth {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 14px;
      height: 13px;
      background: url("../../assets/icon-chat-auth.png");
    }
  }
  img.user-avatar {
    display: block;
  }
}

.h5-wrap{
  .pub-chat-item{
    padding: px2rem(24) px2rem(32);
    height: px2rem(90);
    &:before{
      top: 0;
      right: 0;
    }
    &.current {
      background-color: #fff;
    }
    &:hover{
      background-color: #f8f8f8;
    }
    .time{
      font-size: px2rem(24);
      color: #999999;
    }
    .info {
      position: relative;
      margin-left: px2rem(28);
      h3 {
        font-size: px2rem(32);
        color: #020202;
        margin-bottom: px2rem(14);
        line-height: px2rem(40);
        .icon-mute{
          width: px2rem(24);
          height: px2rem(26);
          background-size: 100%;
          background: url(../../assets/icon-chat-mute.png) 0 center /100% no-repeat;
        }
        .icon-group{
          width: px2rem(32);
          height: px2rem(28);
          background: url(../../assets/h5/icon-chat-group.png) 0 center /100% no-repeat;
        }
        span{
          max-width: px2rem(390);
        }
      }
      p {
        font-size: px2rem(24);
        color: #9b9b9b;
        line-height: px2rem(40);
      }
    }
    .ext {
      right: -px2rem(15);
      top: -px2rem(15);
      padding: 0 px2rem(8);
      height: px2rem(30);
      border-radius: px2rem(15);
      line-height: px2rem(30);
      font-size: px2rem(24);
    }
    &::after {
      content: "";
      position: absolute;
      right: 0;
      bottom: 0;
      left: px2rem(24+90+28);
      pointer-events: none;
      border-bottom: 1px solid #d8d8d8;
      transform: scaleY(0.5);
      transform-origin: 0 0;
    }
  }
}
</style>
