<template>
  <div>
    <div class="tag-message" :class="classes">
      <div class="tag-message-bd">
        <div class="tag-message-content" ref="content" v-html="html"></div>
      </div>
      <div class="more" @click="viewMore" v-if="hasMore">
        <template v-if="!showMore">
          <span>更多</span>
          <van-icon name="arrow-down"></van-icon>
        </template>
        <template v-else>
          <span>收起</span>
          <van-icon name="arrow-up"></van-icon>
        </template>
      </div>
    </div>
    <div class="tools">
      <ul>
        <li @click="toExamPage">知识点考试</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TagMessage',
  props: {
    data: { type: Object }
  },
  data() {
    return {
      showMore: false,
      maxHeight: 90,
      contentHeight: 0
    }
  },
  computed: {
    hasMore() {
      return this.contentHeight > this.maxHeight
    },
    classes() {
      return {
        'has-more': this.hasMore && !this.showMore
      }
    },
    html() {
      if (this.data.contents) {
        return this.data.contents
          .replace(/\n/g, '<br/>')
          .replace(/---------- start ----------/gi, '')
          .replace(/---------- end ----------/gi, '')
      }
      return ''
    },
    isWeapp() {
      return this.$store.state.isWeapp
    }
  },
  methods: {
    toggleMore() {
      this.showMore = !this.showMore
    },
    viewMore() {
      if (this.isWeapp) {
        wx.miniProgram.navigateTo({
          url: `/pages/web/index?src=${window.location.origin}/course/tag/${this.data.id}`
        })
      } else {
        this.$router.push({
          name: 'courseTagItem',
          params: { id: this.data.id }
        })
      }
    },
    // 去知识点考试页面
    toExamPage() {
      const path = `/exam/answer?type=2&tag_id=${this.data.id}&papersUrl=zy/v2/examination/course-papers`
      if (this.isWeapp) {
        const src = encodeURIComponent(`${window.location.origin}${path}`)
        wx.miniProgram.navigateTo({ url: `/pages/web/index?src=${src}` })
      } else {
        this.$router.push({ path })
      }
    }
  },
  mounted() {
    this.contentHeight = this.$refs.content.offsetHeight
  }
}
</script>

<style lang="scss" scoped>
.tag-message {
  padding: 10px;
  background-color: #fff;
  border-radius: 6px;
}
.has-more .tag-message-bd {
  height: 90px;
  overflow: hidden;
}
.tag-message-content {
  font-size: 13px;
  line-height: 30px;
}
.more {
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-size: 13px;
  color: #222;
  text-align: center;
  cursor: pointer;
}
.tools {
  margin-top: 5px;
  li {
    display: inline-block;
    height: 24px;
    margin: 0 10px 10px 0;
    padding: 0 15px;
    font-size: 13px;
    color: #fff;
    line-height: 24px;
    background: #67a8ff;
    border-radius: 12px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    cursor: pointer;
  }
}
</style>
