<template>
  <div class="main-container" v-if="loaded">
    <div class="course-title">{{detail.course_name}}</div>
    <van-tabs
      class="main-tabs"
      v-model="tabActive"
      color="#c62245"
      :line-height="2"
      :swipeable="true"
    >
      <van-tab title="按章节学习">
        <template v-if="detail.chapters && detail.chapters.length">
          <course-chapter :courseId="courseId" :data="detail.chapters"></course-chapter>
        </template>
        <van-empty description="暂无内容" v-else />
      </van-tab>
      <van-tab title="按考点学习">
        <div class="tab-content">
          <course-tag :courseId="courseId"></course-tag>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { random } from 'lodash'
import CourseChapter from './components/courseChapter.vue'
import CourseTag from '../tag/index.vue'
import * as api from '@/api/course.js'
export default {
  name: 'CourseLearnItem',
  components: { CourseChapter, CourseTag },
  metaInfo() {
    return {
      title: this.detail.course_name || ''
    }
  },
  data() {
    return {
      tabActive: 0,
      loaded: false,
      detail: {}
    }
  },
  computed: {
    courseId() {
      return this.$route.params.id
    },
    isVip() {
      return this.$store.state.isVip
    }
  },
  methods: {
    // 课程学习
    getCourse() {
      this.loaded = false
      api.getCourse(this.courseId).then(response => {
        this.loaded = true
        response.chapters = response.chapters.filter(item => {
          item.children = item.children.filter(
            child => child.type === 2 && child.resource_id && child.resource_id !== '6684350363920760832'
          )
          return item.children.length
        })
        this.detail = response
      })
    }
  },
  beforeMount() {
    // 检测是否是付费用户
    this.$store.dispatch('checkIsVip').then(isVip => {
      if (isVip) {
        this.getCourse()
      } else {
        const routes = { 0: '/pay', 1: '/payPage' }
        const path = routes[random(1)] || '/pay'
        this.$router.replace(path)
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.course-title {
  font-size: 15px;
  font-weight: 600;
  color: #222;
  padding: 20px 0 10px;
}
.tab-content {
  margin-left: -0.4rem;
  margin-right: -0.4rem;
  min-height: 100vh;
  background: #eee;
  padding: 0.4rem;
}
</style>
