<template>
  <div class="pages">
    <div class="head">
      <img class="logo" src="../../assets/images/logo-header.png" />
      <div class="user">
        <div class="nickname">{{ nickName }}</div>
        <div class="logout" @click="logout">{{ $t('components.learnSysLayout.sideBar.outLogin') }}</div>
      </div>
    </div>
    <div class="hint" v-if="latest" @click="onClick(latest.live)">
      <div class="left">
        <div class="left-1">{{ $t('live.liveReminder') }}：</div>
        <div class="left-2">
          《{{ latest.course_name }}》{{ $t('live.startTime', { time: latest.live.start_time }) }}
        </div>
      </div>
      <div class="right">{{ $t('live.goLive') }}</div>
    </div>
    <div class="tips">{{ $t('live.replayTips') }}</div>
    <div class="live-list">
      <template v-for="item in dataList">
        <div class="live-item" :key="subitem.id" v-for="subitem in item.live" @click="onClick(subitem)">
          <h4 class="live-item-name">{{ item.course_name }}</h4>
          <div class="live-item-main">
            <img class="live-item-pic" :src="item.curriculum.curriculum_picture" />
            <div class="live-item-content">
              <div class="live-item-content__title">{{ subitem.topic }}</div>
              <div class="live-item-content__time">{{ subitem.start_time }}</div>
              <div class="live-item-content__status">{{ calcTimeText(subitem.start_time, subitem.live_status) }}</div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import cAction from '@action'
export default {
  data() {
    return {
      latest: null,
      dataList: [],
      loading: null,
      message: null,
      timer: null
    }
  },
  computed: {
    user() {
      return window.G.UserInfo ? window.G.UserInfo.student_info : {}
    },
    nickName() {
      return this.user.personal_name || '匿名'
    }
  },
  methods: {
    /* 退出登录 - 跳转方法 */
    logout() {
      cAction.Other.outLogin()
        .then(str => {
          window.G.UserInfo = {}
          // this.$router.push({ path: '/login/index' })
          window.location.href = webConf.others.loginUrl
        })
        .catch(e => {
          this.$message.error(e.message)
        })
    },
    getNewLiveMsg() {
      // 获取最新直播提醒
      cAction.Player.getNewLiveMsg()
        .then(response => {
          if (response.status === 200 && !Array.isArray(response.data)) {
            this.latest = response.data
          } else {
            this.latest = null
          }
        })
        .finally(() => {
          this.loading && this.loading.close()
        })
    },
    getLiveList() {
      // 获取最新直播列表
      cAction.Player.getLiveList()
        .then(response => {
          if (response.status === 200) {
            this.dataList = response.data.map(data => {
              // 兼容老的数据结构
              if (!Array.isArray(data.live)) {
                data.live = [data.live]
              }
              return data
            })
          }
        })
        // 取消报错提醒
        // .catch(e => {
        //   this.$message.error(e.message)
        // })
        .finally(() => {
          if (this.loading) {
            this.loading.close()
            this.loading = null
          }
        })
    },
    dealRender: () => {
      ;(function (win, doc) {
        const wWidth =
          win.screen.width > 0
            ? win.innerWidth >= win.screen.width || win.innerWidth === 0
              ? win.screen.width
              : win.innerWidth
            : win.innerWidth
        const wFsize = ((wWidth > 640 ? 640 : wWidth) / 375) * 100
        // wFsize = wFsize > 32 ? wFsize : 32;
        doc.documentElement.style.fontSize = wFsize + 'px'
      })(window, document)
    },
    onClick(data) {
      data.live_status = parseInt(data.live_status)
      const { live_status: liveStatus, type: liveType } = data
      const hasRecordUrl = data.enable_record && data.record_url
      if ([3, 5].includes(liveStatus) && !hasRecordUrl) {
        this.message && this.message.close()
        this.message = this.$message({ type: 'warning', offset: 0, message: this.$t('live.liveEnd') })
        return
      }
      if (liveType === 5) {
        // 打开云直播
        this.openCloudLive(data)
        return
      }
      if (liveType === 'cloud') {
        // 打开云课堂
        this.openCloudClass(data)
        return
      }
      this.openNewWindow(data.record_url || data.join_url)
    },
    // 打开云课堂
    openCloudClass(data) {
      // https://doc.bokecc.com/class/developer/api/login.html
      const liveStatus = data.live_status
      data.user_name = data.user_name || window.G.UserInfo.student_info.personal_name
      if (liveStatus === 3) {
        // 查看回放
        const replayUrl = data.record_url.replayUrl
        const url = replayUrl
          ? `${replayUrl}&autoLogin=true&viewername=${data.username}&viewertoken=${data.password}`
          : ''
        this.openNewWindow(url)
      } else {
        // 进行中
        const url = `http://view.csslcloud.net/api/view/index?roomid=${data.room_id}&userid=${data.account_id}&autoLogin=true&viewername=${data.username}&viewertoken=${data.password}`
        this.openNewWindow(url)
      }
    },
    // 打开云直播
    openCloudLive(data) {
      // https://doc.bokecc.com/live/Appendix_1.html
      const liveStatus = data.live_status
      data.user_name = data.user_name || this.nickName
      if (liveStatus === 3) {
        // 查看回放
        // const url = `https://view.csslcloud.net/api/view/callback?recordid=${data.record_id}&roomid=${data.room_id}&userid=${data.account_id}&autoLogin=true&viewername=${data.user_name}&viewertoken=${data.play_pass}`
        this.openNewWindow(data.record_url)
      } else {
        // 查看直播
        const url = `https://view.csslcloud.net/api/view/index?roomid=${data.room_id}&userid=${data.account_id}&autoLogin=true&viewername=${data.user_name}&viewertoken=${data.play_pass}`
        this.openNewWindow(url)
      }
    },
    // 新窗口打开
    openNewWindow(url) {
      url && window.open(url, '_blank')
    },
    // 计算日期
    calcTimeText(liveTime, liveStatus) {
      const map = {
        1: this.$t('live.notStarted'),
        2: this.$t('live.liveStreaming'),
        3: this.$t('live.liveEnd'),
        4: this.$t('live.start'),
        5: this.$t('live.liveEnd')
      }
      let result = map[liveStatus] || liveTime

      if (liveStatus === 1 && liveTime) {
        liveTime = liveTime.replace(/-/g, '/')
        const time = (new Date(liveTime).getTime() - new Date().getTime()) / 1000 || 0
        if (time <= 5 * 60) {
          result = this.$t('live.start')
        } else if (time <= 1 * 60 * 60) {
          result = this.$t('live.startInMinutes', {
            minutes: parseInt(time / 60)
          })
        } else if (time <= 24 * 60 * 60) {
          result = this.$t('live.startInHours', {
            h: parseInt(time / (60 * 60)),
            min: parseInt((time / 60) % 60)
          })
        } else {
          result = this.$t('live.startInDay', {
            day: parseInt(time / (24 * 60 * 60))
          })
        }
      }
      return result
    }
  },
  mounted() {
    this.loading = this.$loading({
      lock: true,
      text: '',
      spinner: '',
      background: 'rgba(255, 255, 255, 0.9)'
    })
    this.dealRender()
    this.getNewLiveMsg()
    this.getLiveList()
    this.timer = setInterval(() => {
      this.getNewLiveMsg()
      this.getLiveList()
    }, 10000)
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer)
  }
}
</script>
<style>
html {
  font-size: 100px;
}
body {
  padding: 0;
  margin: 0;
}
.float-left {
  float: left;
}
.float-right {
  float: right;
}
</style>
<style scoped>
.pages {
  min-height: 100vh;
  font-size: 0.14rem;
  background-color: #fff;
}
.head {
  display: flex;
  align-items: center;
  padding: 0.2rem 0.2rem 0.16rem;
}
.head .logo {
  width: 0.9rem;
  /* height: 0.3rem; */
}
.head .logo:nth-child(2) {
  margin-left: 0.1rem;
}
.head .user {
  display: flex;
  flex: 1;
}
.nickname {
  flex: 1;
  padding: 0 0.1rem;
  color: #587fff;
  text-align: right;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.logout {
  color: #999;
}
.hint {
  display: flex;
  padding: 0.1rem 0.2rem;
  background: rgba(176, 28, 61, 0.1);
  justify-content: space-between;
  font-size: 0.14rem;
  cursor: pointer;
}
.hint .left {
  flex: 1;
  padding-right: 0.08rem;
}
.hint .left .left-1 {
  line-height: 0.2rem;
}

.hint .left .left-2 {
  margin-left: -0.08rem;
  margin-top: 0.05rem;
}
.hint .right {
  color: #b01c3d;
  align-self: center;
}
.tips {
  height: 0.4rem;
  line-height: 0.4rem;
  padding: 0 0.2rem;
  color: #999;
  font-size: 0.14rem;
  overflow: hidden;
}
.live-list {
  padding: 0 0.2rem;
}
.live-item {
  width: 100%;
  padding-top: 0.05rem;
  height: 1.2rem;
  border-bottom: 1px solid #ccc;
}
.live-item-name {
  padding: 0;
  margin: 0;
  font-size: 0.14rem;
  line-height: 0.4rem;
  color: #333;
}
.live-item-main {
  display: flex;
  width: 100%;
  height: 0.6rem;
  cursor: pointer;
}
.live-item-pic {
  width: 0.86rem;
  height: 0.6rem;
}
.live-item-content {
  padding-left: 10px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.live-item-content__title {
  font-size: 0.12rem;
  color: #333;
}
.live-item-content__status {
  color: #b01c3d;
}
</style>
