<template>
  <div class="messages">
    <template v-for="item in messageList">
      <message-card :data="item" :key="item.id" @search="onSearchTag" @change="onChangeTag"></message-card>
    </template>
  </div>
</template>

<script>
import MessageCard from './messageCard.vue'
import * as api from '@/api/course.js'
export default {
  props: { courseId: { type: String, required: true } },
  components: { MessageCard },
  data() {
    return {
      messageList: [] // {id:'', type: 1, payload: {}}
    }
  },
  methods: {
    // 获取知识点列表
    getCourseTagList() {
      api.getCourseTagList(this.courseId).then(response => {
        this.messageList = response.chapters.map((item, index) => {
          return {
            id: this.genId(index),
            type: 1,
            from: 'system',
            payload: item
          }
        })
      })
    },
    // 点击标签
    onSearchTag(data) {
      this.messageList.push({
        id: this.genId(),
        type: 0,
        from: 'user',
        payload: { text: data.name }
      })
      this.searchTag(data.name)
    },
    searchTag(keywords) {
      api.getSearchTagList({ keywords }).then(response => {
        this.messageList.push({
          id: this.genId(),
          type: 2,
          from: 'system',
          payload: response
        })
      })
    },
    onChangeTag(data) {
      this.messageList.push({
        id: this.genId(),
        type: 0,
        from: 'user',
        payload: { text: data.title }
      })
      this.getCourseTag(data.id)
    },
    // 获取知识点详情
    getCourseTag(tagId) {
      api.getCourseTag(tagId).then(response => {
        this.messageList.push({
          id: this.genId(),
          type: 3,
          from: 'system',
          payload: response
        })
      })
    },
    // 生成消息ID
    genId(index) {
      index = index || this.messageList.length
      return `message_${index}`
    }
  },
  beforeMount() {
    this.getCourseTagList()
  }
}
</script>

<style lang="scss" scoped>
.messages {
  background: #eee;
  overflow: hidden;
}
</style>
