<template>
  <div class="main-container" v-show="loaded" style="margin:0 0.15rem">
    <template v-if="list.length && hasLearned">
      <course-item
        v-for="item in list"
        :data="item"
        :key="item.id"
        :show-progress="true"
        @on-click="handleClick"
      />
    </template>
    <van-empty description="您还没有学习课程，快快开始学习吧！" v-else />
  </div>
</template>

<script>
import * as api from './api'
import CourseItem from '@/components/CourseItem.vue'

export default {
  name: 'Course',
  components: { CourseItem },
  metaInfo: {
    title: '已学课程'
  },
  data() {
    return {
      loaded: false,
      list: []
    }
  },
  computed: {
    isWeapp() {
      return this.$store.state.isWeapp
    },
    // 是否学习过
    hasLearned() {
      for (const item of this.list) {
        const found = item.child.find(item => item.course_progress)
        if (found) {
          return true
        }
      }
      return false
    }
  },
  methods: {
    getCourseList() {
      api
        .getCourseList()
        .then(response => {
          this.list = response
        })
        .finally(() => {
          this.loaded = true
        })
    },
    handleClick(data) {
      if (this.isWeapp) {
        const url = `/pages/web/index?src=${window.location.origin}/my/learn/${data.id}`
        wx.miniProgram.navigateTo({ url })
      } else {
        this.$router.push({
          name: 'myLearnItem',
          params: { id: data.id }
        })
      }
    }
  },
  beforeMount() {
    this.getCourseList()
  }
}
</script>

<style lang="scss">
.course-item:last-child {
  border-bottom: 0;
}
</style>
