<template>
  <div class="main-list" v-show="loaded">
    <ul v-if="list.length && hasLearned">
      <li v-for="item in list" :key="item.course_id" @click="onClick(item)">
        <div class="pic" v-if="item.picture">
          <img :src="item.picture" />
        </div>
        <div class="name">{{item.course_name}}</div>
        <div class="progress">{{item.video_progress | progressText}}</div>
      </li>
    </ul>
    <van-empty description="您还没有学习课程，快快开始学习吧！" v-else />
  </div>
</template>
<script>
import * as api from '../api'
export default {
  name: 'BuyCourseList',
  data() {
    return {
      loaded: false,
      list: []
    }
  },
  computed: {
    isWeapp() {
      return this.$store.state.isWeapp
    },
    // 是否学习过
    hasLearned() {
      return !!this.list.find(item => item.video_progress)
    }
  },
  filters: {
    progressText(value) {
      value = parseInt(value)
      if (value === 0) {
        return '未开始'
      }
      if (value === 100) {
        return '已学完'
      }
      return `已学${value}%`
    }
  },
  methods: {
    getList() {
      api
        .getFreeCourseList()
        .then(response => {
          this.list = response
        })
        .finally(() => {
          this.loaded = true
        })
    },
    onClick(data) {
      if (this.isWeapp) {
        wx.miniProgram.navigateTo({
          url: `/pages/course/free?id=${data.course_id}`
        })
      } else {
        window.alert('请在微信小程序中打开')
      }
    }
  },
  beforeMount() {
    this.getList()
  }
}
</script>

<style lang="scss" scoped>
.main-list li {
  display: flex;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid #f1f1f1;
  &:last-child {
    border-bottom: 0;
  }
  .pic {
    width: 100px;
    height: 64px;
    margin-right: 10px;
    border-radius: 6px;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
  .name {
    flex: 1;
    align-self: flex-start;
    font-size: 15px;
    color: #222;
  }
  .progress {
    margin-left: 20px;
    font-size: 12px;
    color: #999;
  }
}
</style>
