<template>
  <div class="chat-item"
    :class="{'current': item.session_id == curSession, 'moblie': isMoblie}"
    @click="changeSessionId(item)"
    @contextmenu.prevent="onToolBtn">
    <div class="avatar-wrap">
      <i class="ext" v-if="item.unread>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>
    </div>
    <div class="info">
      <h3>{{item.name}}</h3>
      <p>{{item.cont}}</p>
    </div>
    <ul
      class="pub-pop-toolbar ext-session"
      v-if="item.session_id"
      v-show="showToolbar"
      :style="{left:toolBarX,top:toolBarY,bottom:toolBarBottom}"
    >
      <li class="split-line" @click.stop="changePin(item.session_id,item.is_pin)">{{item.is_pin==1?"取消置顶":"置顶"}}</li>
      <li class="split-line" @click.stop="changeMute(item.session_id,item.is_mute)">{{item.is_mute==1?"取消免打扰":"消息免打扰"}}</li>
      <li @click.stop="delSession(item.session_id)">删除会话</li>
    </ul>
  </div>
</template>

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

export default {
  name: 'msgItem',
  props: {
    item: {
      type: Object
    },
    isMoblie: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      toolBarX: 0,
      toolBarY: 0,
      toolBarBottom: 0,
      showToolbar: false
    }
  },
  computed: {
    ...mapState(['curSession', 'userId']),
    ...mapMutations(['setSessionItemUnread']),
    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 })

      this.$store.commit('setSessionItemUnread', {
        session_id: item.session_id,
        unread: 0,
        curSession: this.curSession
      })
    },
    bgColorNum (str) {
      if (str.match('-')) {
        let num = 0
        str.split('-').forEach(e => {
          if (e !== this.userId) {
            num = e % 9
          }
        })
        return num
      } else {
        return str % 9
      }
    },
    hideToolbar (event) {
      if (this.showToolbar !== false) {
        this.showToolbar = false
        document.body.removeEventListener('click', this.hideToolbar, false)
        document.body.removeEventListener('contextmenu', this.hideToolbar, false)
      }
    },
    onToolBtn (event) {
      if (this.showToolbar) {
        this.hideToolbar(event)
        return
      }

      let winWidth = window.innerWidth
      let winHeight = window.innerHeight
      let clientX, clientY

      if (event instanceof MouseEvent) {
        clientX = event.clientX
        clientY = event.clientY
        this.toolBarX = event.layerX > 170 ? 170 : event.layerX + 20
        this.toolBarY = event.layerY

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

      if (clientX > winWidth * 0.5) {
        this.toolBarX = this.toolBarX - 120
      }
      this.toolBarX += 'px'

      if (clientY > winHeight / 2) {
        this.toolBarBottom = this.toolBarY + 'px'
        this.toolBarY = 'auto'
      } else {
        this.toolBarBottom = 'auto'
        this.toolBarY += 'px'
      }

      this.showToolbar = true
    },
    /**
     * @des 置顶聊天相关操作
     * @param {Number}
     * @param {String} val {1: 取消, 0: 置顶}
     */
    changePin (sessionId, val) {
      if (val == 0) {
        API.session.setPin({
          session_id: sessionId
        }).then(() => {
          if (this.curSession == sessionId) this.$store.commit('updatePin', '1')

          // 更新侧边栏的顺序
          this.$store.commit('updateSessionListByPin', sessionId)
          this.hideToolbar()
        })
      } else {
        API.session.cancelPin({
          session_id: sessionId
        }).then(() => {
          if (this.curSession == sessionId) this.$store.commit('updatePin', '0')

          // 更新侧边栏的顺序
          this.$store.commit('cancelSessionListByPin', sessionId)
          this.hideToolbar()
        })
      }
    },
    /**
     * @des 消息免打扰
     * @param {String} val 消息免打扰{1: 取消免打扰, 0: 免打扰}
     */
    changeMute (sessionId, val) {
      if (val == 0) {
        API.session.setMute({
          session_id: sessionId
        }).then(() => {
          if (this.curSession == sessionId) this.$store.commit('updateMute', '1')
          this.$store.commit('updateSessionListByMute', sessionId)
          this.hideToolbar()
        })
      } else {
        API.session.cancelMute({
          session_id: sessionId
        }).then(() => {
          if (this.curSession == sessionId) this.$store.commit('updateMute', '0')
          this.$store.commit('cancelSessionListByMute', sessionId)
          this.hideToolbar()
        })
      }
    },
    // 删除会话
    delSession (sessionId) {
      confirmPopup('确认删除当前会话？').then(() => {
        API.session.deleteSession({
          session_id: sessionId
        }).then(() => {
          this.$store.commit('removeSessionListById', sessionId)
          this.$showTips('已退出该会话')
          this.hideToolbar()
          // 如果正在打开该会话，重置路由
          if (this.curSession == sessionId) {
            this.$store.commit('changeSessionId', 0)
            this.$router.push({ path: '/' })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.chat-item{
  padding: 10px 13px 10px 20px;
  height: 40px;
  cursor: pointer;
  position: relative;
  @include webkitbox(1);
  &:hover{
    background: #383b41;
  }
  &.current{
    background: #3f424c;
    cursor: default;
  }
  .ext{
    position: absolute;
    background-color: #f12f28;
    color: #fff;
    text-align: center;
  }
  .info{
    @include flex(1);
    margin-right: 20px;
    margin-left: 10px;
    h3{
      font-size: 13px;
      color: #fff;
      line-height: 20px;
      @include ellipsis;
    }
    p{
      font-size: 12px;
      line-height: 20px;
      color: #7c8ca5;
      @include ellipsis;
    }
  }
  .avatar-wrap{
    position: relative;
    .ext{
      position: absolute;
      top: -7px;
      right: -7px;
      background: #ff0000;
      color: #fff;
      font-size: 12px;
      padding: 2px 5px;
      border-radius: 12px;
      z-index: 99;
    }
  }
  img.user-avatar{
    display: block;
    background: #ccc;
  }
  &.moblie{
    padding: px2rem(24) px2rem(32);
    height: px2rem(90);
    &.current{
      background-color: #fff;
    }
    .info{
      margin-left: px2rem(28);
      h3{
        font-size: px2rem(32);
        color: #020202;
        margin-bottom: px2rem(14);
      }
      p{
        font-size: px2rem(24);
        color: #9b9b9b;
      }
    }
    .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: "";
      pointer-events: none;
      box-sizing: border-box;
      position: absolute;
      width: 200%;
      height: 200%;
      left: px2rem(24+90+28);
      top: 0;
      border-bottom:1px solid #d8d8d8;
      transform:scale(0.5);
      transform-origin: 0 0;
    }
  }
}
</style>
