<template>
  <div class="answer-item">
    <div class="user">
      <img class="user-avatar" :src="avatar" />
      <div class="user-content">
        <div class="user-name">{{ data.replier.nickname }}</div>
        <div class="user-publishtime">{{ data.created_time }}</div>
      </div>
    </div>
    <div class="answer-content" v-html="contentHtml"></div>
    <div class="tools">
      <div class="right-txt" @click="toggleLike">
        <i class="el-icon-thumb"></i>
        {{ $t('DiscussModule.DiscussDetail.like') }}({{ data.tag_count }})
      </div>
      <div class="right-txt" @click="toggleComment">
        <i class="el-icon-chat-round"></i>
        {{ $t('DiscussModule.DiscussDetail.discuss') }}({{ data.comments.length }})
      </div>
      <div class="right-txt" @click="handleDelete(data.id)" v-if="data.mine">
        <i class="el-icon-delete"></i>
        {{ $t('DiscussModule.DiscussDetail.delete') }}
      </div>
    </div>
    <!-- 评论列表 -->
    <comment-list
      :detail="detail"
      :list="data.comments"
      :data="data"
      v-on="$listeners"
      v-if="commentVisible"
    ></comment-list>
  </div>
</template>

<script>
import * as api from '../api/index.js'
import commentList from './commentList.vue'
import defaultAvatar from '../assets/images/person-default.jpg'
export default {
  components: { commentList },
  props: {
    data: { type: Object, default: () => {} },
    detail: { type: Object, default: () => {} }
  },
  data() {
    return {
      commentVisible: false,
      publishText: ''
    }
  },
  computed: {
    avatar() {
      return this.data.replier.avatar || defaultAvatar
    },
    contentHtml() {
      return this.data.contents.replace(/\n/g, '<br />')
    }
  },
  methods: {
    // 点赞
    toggleLike() {
      const params = {
        answer_id: this.data.id,
        question_id: this.detail.id,
        semester_id: this.detail.semester_id
      }
      if (this.data.tag) {
        // 取消点赞
        api.unlike(this.data.tag.id).then(json => {
          this.$emit('update')
        })
      } else {
        // 点赞
        api.like(params).then(res => {
          this.$emit('update')
        })
      }
    },
    // 评论
    toggleComment() {
      this.commentVisible = !this.commentVisible
    },
    // 删除回答
    handleDelete(id) {
      api.deleteAnswer(id).then(json => {
        this.$message({ type: 'success', message: this.$t('DiscussModule.DiscussDetail.deleteSuccess') })
        this.$emit('update')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.answer-item + .answer-item {
  border-top: 1px solid #f6f6f6;
}
.answer-item {
  padding-bottom: 20px;
}
</style>
