<template>
  <component
    :is="currentCompoent"
    :chapter="chapter"
    :data="data"
    :homework="homework"
    @updateHomework="getHomework"
    v-bind="$attrs"
    v-on="$listeners"
    v-if="chapter"
    v-loading="loading"
  />
</template>

<script>
// componets
import ChapterWork from './chapterWork.vue'
import ChapterTest from './chapterTest.vue'
import * as api from '../../api'

export default {
  name: 'ViewerWork',
  components: { ChapterWork, ChapterTest },
  props: {
    // 当前选中的
    chapter: {
      type: Object,
      default() {
        return {}
      }
    },
    // 课程详情接口返回的数据
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      homework: {}
    }
  },
  computed: {
    currentCompoent() {
      const componentNames = {
        1: 'ChapterTest', // 课后测验
        2: 'ChapterWork' // 作业
      }
      const homework = this.homework
      return homework ? componentNames[homework.work_type] : ''
    },
    // 学期ID
    sid() {
      return this.$route.params.sid
    },
    // 课程ID
    cid() {
      return this.$route.params.cid
    },
    // 当前页面的ID
    pid() {
      return this.$route.params.id
    },
    // 资源ID
    resourceId() {
      return this.chapter.resource_id
    }
  },
  methods: {
    getHomework() {
      this.loading = true
      api
        .getChapterHomework(this.sid, this.cid, this.resourceId)
        .then(response => {
          const { answer, question } = response
          this.homework = { answer, ...question }
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  beforeMount() {
    this.getHomework()
  }
}
</script>
