<template>
  <view id="msg" class="page">
    <!-- 消息列表 -->
    <l-list :empty="msgCount <= 0" emptyTips="消息列表为空" nomoreTips="已显示全部消息" message nomore>
      <l-list-item
        v-for="item of msgList"
        @click="goTo(item)"
        :key="item.F_Id"
        :imgAvatar="avatarSrc(item)"
        :roundAvatar="roundAvatar"
        :extra="item.F_Content"
        iconAvatar="notice"
        iconStyle="background-color: #e4f2fd; color: #98c0da;"
      >
        <!-- 消息发送人 -->
        <text class="text-black">{{ msgTitle(item) }}</text>

        <!-- 消息时间 -->
        <view class="time" slot="time">
          <view class="text-right">{{ msgDateTime(item.F_Time)[0] }}</view>
          <view v-if="msgDateTime(item.F_Time)[1]" class="text-right">{{ msgDateTime(item.F_Time)[1] }}</view>
        </view>
      </l-list-item>
    </l-list>
  </view>
</template>

<script>
import moment from 'moment'
import keyBy from 'lodash/keyBy'

export default {
  data() {
    return {
      msgList: [],
      sysUserTable: {},
      timer: null,
      nextTime: '1888-10-10 10:10:10'
    }
  },

  async onLoad() {
    await this.init()
  },

  // 本页面开启下拉刷新，用于立即拉取消息
  onPullDownRefresh() {
    this.msgList = []
    this.nextTime = '1888-10-10 10:10:10'
    this.fetchMsg().then(() => {
      this.TOAST('已更新消息列表')
      uni.stopPullDownRefresh()
    })
  },

  // 页面添加定时器，自动收取消息
  onShow() {
    const intervalTime = this.CONFIG('pageConfig.msg.fetchMsg')
    this.timer = setInterval(this.fetchMsg, intervalTime)
  },

  // 离开页面后移除定时器
  onHide() {
    clearInterval(this.timer)
  },

  // 卸载页面后移除定时器
  onUnload() {
    clearInterval(this.timer)
  },

  methods: {
    // 页面初始化
    async init() {
      this.LOADING('读取消息列表')
      await this.fetchMsg()
      this.HIDE_LOADING()
    },

    // 拉取消息
    async fetchMsg() {
      const message = await this.HTTP_GET('/im/contacts', this.nextTime, '加载信息时通讯出错')
      if (!message) {
        return
      }

      this.nextTime = message.time
      this.sysUserTable = Object.assign(this.sysUserTable, keyBy(message.sysUserList, 'F_Code'))

      // 不在列表里的消息，则插入；已在列表里的消息，则替换
      // 最后按照时间排序，最后的消息在最上
      const newMsg = message.data
      const allMsg = this.msgList

      newMsg.forEach(item => {
        const idx = allMsg.findIndex(t => t.F_Id === item.F_Id)
        if (idx === -1) {
          allMsg.push(item)
          return
        }
        allMsg[idx] = item
      })

      this.msgList = allMsg.sort((a, b) => moment(b.F_Time).valueOf() - moment(a.F_Time).valueOf())
    },

    // 点击后，跳转到详细聊天页
    goTo(item) {
      const user = this.sysUserTable[item.F_OtherUserId] || this.userTable[item.F_OtherUserId]
      const sys = this.sysUserTable[item.F_OtherUserId] ? '&sys' : ''

      const query = `id=${item.F_OtherUserId}&name=${user.name || user.F_Name}${sys}`
      this.NAV_TO(`/pages/msg/chat?${query}`)
    },

    // 获取消息发送人名称显示
    msgTitle(item) {
      const user = this.sysUserTable[item.F_OtherUserId] || this.userTable[item.F_OtherUserId] || {}

      return user.F_Name || user.name || '(未知用户)'
    },

    // 格式化显示消息时间
    msgDateTime(date) {
      return this.TABLEITEM_DATEFORMAT(date)
    },

    // 获取用户头像 url
    avatarSrc(item) {
      const user = this.userTable[item.F_OtherUserId]
      if (!user) {
        return null
      }

      return this.API + `/user/img?data=${item.F_OtherUserId}`
    }
  },

  computed: {
    // 所用用户表
    userTable() {
      return this.GET_GLOBAL('user')
    },

    // msgList 消息数组的长度
    msgCount() {
      return this.msgList.length
    },

    // 头像圆形/方形显示参数
    roundAvatar() {
      return this.CONFIG('pageConfig.roundAvatar')
    }
  }
}
</script>

<style lang="less" scoped>
.avatar {
  width: 96rpx;
  height: 96rpx;
}

.time {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
</style>
