// pages/live.js
import api from '../../utils/Api.js'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    rooms: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getLiveRooms();
  },

  // 获取个人资料
  getLiveRooms: function(callback) {
    api.live.rooms().then(res => {
      if (!res.code) {
        // 渲染数据
        this.setData({
          rooms: res.data
        })
        this.getLiveStatus()
      }
      typeof callback == "function" && callback()
    })
  },

  // 获取直播室状态
  getLiveStatus: function() {
    console.log('liveStatus')
    let that = this
    // 引入获取直播状态接口
    let livePlayer = requirePlugin('live-player-plugin')
    // 首次获取立马返回直播状态，往后间隔1分钟或更慢的频率去轮询获取直播状态
    let rooms = that.data.rooms
    for (let i = 0; i < rooms.length; i++) {
      livePlayer.getLiveStatus({
          room_id: rooms[i].roomid
        })
        .then(res => {
          // 101: 直播中, 102: 未开始, 103: 已结束, 104: 禁播, 105: 暂停中, 106: 异常, 107：已过期 
          const liveStatus = res.liveStatus
          if (liveStatus == 101) {
            rooms[i].live_status_text = '直播中'
          } else if (liveStatus == 102) {
            rooms[i].live_status_text = '未开始'
          } else if (liveStatus == 103) {
            rooms[i].live_status_text = '已结束'
          } else if (liveStatus == 104) {
            rooms[i].live_status_text = '禁播'
          } else if (liveStatus == 105) {
            rooms[i].live_status_text = '暂停中'
          } else if (liveStatus == 106) {
            rooms[i].live_status_text = '异常'
          } else if (liveStatus == 107) {
            rooms[i].live_status_text = '已过期'
          }
          that.updateLiveStatus(rooms[i].roomid, rooms[i].live_status_text)
        })
        .catch(err => {
          console.log(err)
        })
    }
  },

  updateLiveStatus: function(rid, status) {
    let rooms = this.data.rooms
    for (let i = 0; i < rooms.length; i++) {
      if (rooms[i].roomid == rid) {
        rooms[i].live_status_text = status
        break
      }
    }
    this.setData({
      rooms: rooms
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading()
    this.getLiveRooms(() => {
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})