<template>
  <div class="main-container" v-if="loaded">
    <template v-if="detail.chapters && detail.chapters.length">
      <course-chapter :courseId="courseId" :data="detail.chapters" @on-click="handleClick"></course-chapter>
    </template>
    <van-empty description="暂无内容" v-else />
  </div>
</template>

<script>
import CourseChapter from '@/components/CourseChapter.vue'
import * as api from '@/api/course.js'

export default {
  name: 'CoursePlayerItem',
  components: { CourseChapter },
  metaInfo() {
    return {
      title: this.detail.course_name || ''
    }
  },
  data() {
    return {
      loaded: false,
      detail: {}
    }
  },
  computed: {
    courseId() {
      return this.$route.params.id
    },
    isWeapp() {
      return this.$store.state.isWeapp
    },
    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
      })
    },
    handleClick(data) {
      if (this.isWeapp) {
        let url = `/pages/course/player?course_id=${this.courseId}&chapter_id=${data.id}`
        // 未开通
        if (!data.free && !this.isVip) {
          url = `/pages/web/index?src=${window.location.origin}/pay`
        }
        wx.miniProgram.navigateTo({ url })
      } else {
        window.alert('请在微信小程序中打开')
      }
    }
  },
  beforeMount() {
    this.getCourse()
  }
}
</script>
