<template>
  <view id="chat" class="page">
    <!-- 聊天消息列表 -->
    <l-chat :nomore="false">
      <!-- 单条聊天消息 -->
      <l-chat-msg
        v-for="item of msgList"
        :key="item.F_MsgId"
        :content="item.F_Content"
        :type="item.F_SendUserId === chatUserId ? 'left' : 'right'"
        :date="dateDisplay(item.F_CreateDate)"
        :roundAvatar="roundAvatar"
        :imgAvatar="avatar(item.F_SendUserId)"
        iconAvatar="notice"
        iconStyle="background-color: #e4f2fd; color: #98c0da;"
      />
    </l-chat>

    <!-- 消息输入框 -->
    <l-chat-input
      v-model="msgInput"
      @sendMsg="sendMsg"
      :buttonDisabled="buttonDisabled"
      placeholder="输入要发送的消息内容"
    />
  </view>
</template>

<script>
import moment from 'moment'

export default {
  data() {
    return {
      chatUserId: null,
      isSystem: false,

      msgList: [],
      msgInput: '',

      earliestTimePoint: '',
      nextTime: '',

      timer: null,
      ready: false,
      buttonDisabled: false
    }
  },

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

  // 本页面开启下拉刷新，用于立即拉取消息
  onPullDownRefresh() {
    this.fetchBefore().then(uni.stopPullDownRefresh)
  },

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

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

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

  methods: {
    // 页面初始化
    async init({ id, name, sys }) {
      this.LOADING('加载消息…')

      this.chatUserId = id
      this.isSystem = sys
      this.SET_TITLE(name)

      const message = await this.HTTP_GET('learun/adms/im/msg/lastlist', id)
      // 记录最晚消息的时间点
      const nextTime = message[0] && message[0].F_CreateDate
      this.nextTime = moment(nextTime).format('YYYY-MM-DD HH:mm:ss')

      const msgList = message.reverse()

      // 记录最早消息的时间点
      const earliest = msgList[0] && msgList[0].F_CreateDate
      this.earliestTimePoint = moment(earliest)
        .subtract(1, 'second')
        .format('YYYY-MM-DD HH:mm:ss')

      this.msgList = msgList
      this.ready = true

      // 打开页面后，滚动到底部
      setTimeout(() => {
        uni.pageScrollTo({ scrollTop: 9999, duration: 100 })
      }, 500)
      this.HIDE_LOADING()
    },

    // 拉取消息
    async fetchMsg() {
      if (!this.ready) {
        return
      }

      const message = await this.HTTP_GET('learun/adms/im/msg/list2', {
        otherUserId: this.chatUserId,
        time: this.nextTime
      })

      if (message && message.length > 0) {
        // 记录最晚消息的时间点
        const nextTime = message[0] && message[0].F_CreateDate
        this.nextTime = moment(nextTime).format('YYYY-MM-DD HH:mm:ss')

        this.msgList = this.msgList.concat(message.reverse())
      }
    },

    // 拉取之前的消息，用于下拉加载
    async fetchBefore() {
      const message = await this.HTTP_GET('learun/adms/im/msg/list', {
        otherUserId: this.chatUserId,
        time: this.earliestTimePoint
      })

      const oldMsgList = message.reverse()
      if (oldMsgList.length > 0) {
        this.earliestTimePoint = moment(oldMsgList[0].F_CreateDate)
          .subtract(1, 'second')
          .format('YYYY-MM-DD HH:mm:ss')

        this.msgList = oldMsgList.concat(this.msgList)
      }
    },

    // 发送消息按钮
    async sendMsg() {
      if (this.msgInput.trim().length <= 0) {
        this.TOAST('发送的消息不能为空')
        return
      }

      this.ready = false
      this.buttonDisabled = true
      const result = await this.HTTP_POST(
        'learun/adms/im/send',
        { userId: this.chatUserId, content: this.msgInput },
        '消息发送失败'
      )

      if (!result) {
        return
      }

      this.msgList.push({
        F_Content: this.msgInput,
        F_CreateDate: result.time,
        F_IsSystem: null,
        F_MsgId: result.msgId,
        F_RecvUserId: this.chatUserId,
        F_SendUserId: this.GET_GLOBAL('loginUser').userId
      })
      this.nextTime = result.time
      this.msgInput = ''

      setTimeout(() => {
        uni.pageScrollTo({ scrollTop: 9999, duration: 100 })
      }, 10)

      this.buttonDisabled = false
      this.ready = true
    },

    // 格式化显示时间日期
    dateDisplay(date) {
      return this.TABLEITEM_DATEFORMAT(date).toString()
    },

    // 获取用户头像图片 url
    avatar(id) {
      return id === this.chatUserId && this.isSystem ? null : this.API + `/user/img?data=${id}`
    }
  },

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

<style lang="less">
page {
  padding-bottom: 100rpx;
  padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
}

/* #ifdef MP-ALIPAY */
.cu-chat {
  padding-top: 100rpx;
}

#chat {
  height: 100%;
  padding-bottom: 1rpx;
  margin-top: -100rpx;
  overflow: hidden;
}
/* #endif */
</style>
