<template>
  <div class="pages">
    <div class="head">
      <img class="logo" src="../../assets/images/bank-logo1.png" />
      <img class="logo" src="../../assets/images/bank-logo2.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.chapter_name}}</div>
              <div class="live-item-content__time">{{subitem.start_time}}</div>
              <div
                class="live-item-content__status"
                v-if="!(subitem.live_status === 103 && !subitem.enable_record)"
              >{{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() {
      // this.$router.push({ path: '/login/index' })
      cAction.Other.outLogin()
        .then(str => {
          window.G.UserInfo = {}
          this.$router.push({ path: '/login/index' })
        })
        .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
          }
        })
        // 取消报错提醒
        // .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) {
      const {
        live_status: liveStatus,
        live_type: liveType,
        start_time: liveTime
      } = data
      let message = this.calcTimeText(liveTime, liveStatus)
      if (liveStatus === 103 && data.enable_record !== 1) {
        message = this.$t('live.noPlayback')
      }
      if (liveType === 'cloud') {
        // 打开云课堂
        this.openCloudClass(data, message)
        return
      }
      if (liveType === 'live') {
        // 打开云直播
        this.openCloudLive(data, message)
        return
      }
      if (liveType === 'meeting') {
        // 打开腾讯会议
        this.openMeeting(data, message)
        return
      }
      // 其他直播类型直接打开
      if (liveStatus === 1) {
        // 进行中
        this.openNewWindow(data.join_url)
      } else if (liveStatus === 103) {
        // 查看回放
        this.openNewWindow(data.record_url)
      } else {
        this.message && this.message.close()
        this.message = this.$message({ type: 'warning', offset: 0, message })
      }
    },
    // 打开云课堂
    openCloudClass(data, message) {
      // https://doc.bokecc.com/class/developer/api/login.html
      const liveStatus = data.live_status
      data.viewer_name =
        data.viewer_name || window.G.UserInfo.student_info.personal_name
      if (liveStatus === 1) {
        // 进行中
        const url = `http://view.csslcloud.net/api/view/index?roomid=${data.room_id}&userid=${data.user_id}&autoLogin=true&viewername=${data.username}&viewertoken=${data.password}`
        this.openNewWindow(url)
      } else if (liveStatus === 103) {
        // 查看回放
        const replayUrl = data.record_url.replayUrl
        const url = replayUrl
          ? `${replayUrl}&autoLogin=true&viewername=${data.username}&viewertoken=${data.password}`
          : ''
        this.openNewWindow(url)
      } else {
        this.message && this.message.close()
        this.message = this.$message({ type: 'warning', offset: 0, message })
      }
    },
    // 打开云直播
    openCloudLive(data, message) {
      // https://doc.bokecc.com/live/Appendix_1.html
      const liveStatus = data.live_status
      data.viewer_name =
        data.viewer_name || window.G.UserInfo.student_info.personal_name
      if (liveStatus === 1) {
        // 进行中
        const url = `https://view.csslcloud.net/api/view/index?roomid=${data.room_id}&userid=${data.user_id}&autoLogin=true&viewername=${data.viewer_name}&viewertoken=${data.viewer_token}`
        this.openNewWindow(url)
      } else if (liveStatus === 103 && data.enable_record === 1) {
        // enable_record 0:不启用回放 1:开启回放
        // 查看回放
        const url = `https://view.csslcloud.net/api/view/callback?recordid=${data.record_id}&roomid=${data.room_id}&userid=${data.user_id}&autoLogin=true&viewername=${data.viewer_name}&viewertoken=${data.viewer_token}`
        this.openNewWindow(url)
      } else {
        this.message && this.message.close()
        this.message = this.$message({ type: 'warning', offset: 0, message })
      }
    },
    // 打开腾讯会议
    openMeeting(data, message) {
      if (data.join_url) {
        this.openNewWindow(data.join_url)
      } else {
        this.message && this.message.close()
        this.message = this.$message({ type: 'warning', offset: 0, message })
      }
    },
    // 新窗口打开
    openNewWindow(url) {
      url && window.open(url, '_blank')
    },
    // 计算日期
    calcTimeText(liveTime, liveStatus) {
      const map = {
        0: this.$t('live.notStarted'),
        1: this.$t('live.liveStreaming'),
        2: this.$t('live.liveEnd'),
        101: this.$t('live.liveEndNotVideo'),
        102: this.$t('live.liveEndNotVideo'),
        103: this.$t('live.watchReplay')
      }
      let result = map[liveStatus] || liveTime

      if (liveStatus === 0 && 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>
