<template>
  <div class="message-tab">
    <el-row>
      <el-col :span="20">
        <el-input v-model="commentContent" placeholder="发表一条友善的评论"/>
      </el-col>
      <el-col :span="4">
        <el-button style="width: 100%" type="primary" @click="createComment" plain>发表评论</el-button>
      </el-col>
    </el-row>
    <el-divider v-if="commentTree.length!==0"/>
    <div class="comment">
      <div v-for="(comments,index) in commentTree" :key="comments.id" class="comment-body">
        <div class="comment-main">
          <el-row>
            <div
              style="color: white;background: #619dc9;border-radius: 50%;padding: 10px;width: 20px;height: 20px;display: flex;justify-content: center;align-items: center; margin: 10px 10px 0 0">
              <span style="color: white; font-weight: bold;font-size: 24px;">
                {{ comments.mainMessage.sender.name.substring(0, 1) }}
              </span>
            </div>
            <div>
              <el-row style="font-weight: bold;">
                {{ comments.mainMessage.sender.name }}
              </el-row>
              <el-row style="font-size: small; color: #6d6d6d; margin-bottom: 6px">
                {{ comments.mainMessage.createdAt.substring(0, 16).replace("T", " ") }}
              </el-row>
              <el-row>
                {{ comments.mainMessage.content }}
                <span @click="handleReplyClick(comments.mainMessage, index)" class="reply-button">回复</span>
                <span v-if="isOwnComment(comments.mainMessage.sender.id)"
                      @click="deleteComment(comments.mainMessage.id)"
                      class="reply-button">删除</span>
              </el-row>
            </div>
          </el-row>
        </div>
        <div v-for="child in comments.children" :key="child.id" class="comment-child">
          <el-row>
            <div
              style="color: white;background: #619dc9;border-radius: 50%;padding: 10px;width: 20px;height: 20px;display: flex;justify-content: center;align-items: center; margin: 10px 10px 0 0">
                      <span style="color: white; font-weight: bold;font-size: 24px;">{{
                          child.sender.name.substring(0, 1)
                        }}</span>
            </div>
            <div>
              <el-row style="font-weight: bold; margin-bottom: 6px">
                {{ child.sender.name }}
              </el-row>
              <el-row style="font-size: small; color: #6d6d6d; margin-bottom: 6px">
                {{ child.createdAt.substring(0, 16).replace("T", " ") }}
              </el-row>
              <el-row>
                        <span style="color: black;">{{
                            child.targetId === null ?
                              "" :
                              "@" + (comments.children[child.targetId] ?
                                comments.children[child.targetId].sender.name :
                                "失效评论") + "："
                          }}</span>
                {{ child.content }}
                <span @click="handleReplyClick(child,index)" class="reply-button">回复</span>
                <span v-if="isOwnComment(child.sender.id)"
                      @click="deleteComment(child.id)"
                      class="reply-button">删除</span>
              </el-row>
            </div>
          </el-row>
        </div>
        <el-divider/>
      </div>
    </div>
  </div>
</template>

<script>
import {ElMessage, ElMessageBox} from "element-plus";
import portal from "@/utils/portal/portal";

export default {
  name: "MessageTab",
  props: {
    courseId: {
      required: true,
    },
    teacherId: {
      required: true,
    },
  },
  data() {
    return {
      commentContent: "",
      commentTree: [],
    };
  },
  computed: {
    isOwnComment() {
      const _this = this;
      return function (senderId) {
        return senderId === Number(_this.$store.state.user.id);
      };
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      this.commentTree = (await this.$apis.getCommentsByCourseId(this.courseId)).data.data;
    },

    timestampToTime: portal.functions.timestampToTime,

    createComment() {
      if (this.commentContent === "") {
        ElMessage.error("无法发表空评论");
      } else {
        this.$apis.createMessage({
          sender: {
            id: this.$store.state.user.id,
          },
          actionType: "COMMENT",
          targetType: "COURSE",
          targetId: this.courseId,
          mntId: this.courseId,
          content: this.commentContent,
          createdAt: new Date(),
        })
          .then(res => {
            const msg = res.data.data;
            msg.createdAt = this.timestampToTime(msg.createdAt);
            this.commentTree.push({mainMessage: msg, children: {}});
            this.commentContent = "";
            ElMessage.success("发送成功");
          });
      }
    },

    async deleteComment(commentId) {
      const res = (await this.$apis.deleteMessage(commentId)).data.data || null;
      if (res == null) {
        alert(res);
        return;
      }
      this.$message.success(res);
      this.commentTree = (await this.$apis.getCommentsByCourseId(this.$route.params.id)).data.data;
    },

    handleReplyClick(target, index) {
      ElMessageBox.prompt("请输入评论内容", "回复", {
        confirmButtonText: "发送",
        cancelButtonText: "取消",
      })
        .then(({value}) => {
          if (value === "") {
            ElMessage.error("无法发表空评论");
          } else {
            this.$apis.createMessage({
              sender: {
                id: this.$store.state.user.id,
              },
              actionType: "COMMENT",
              targetType: "COMMENT",
              targetId: target.id,
              mntId: target.targetType === "COURSE" ? target.id : target.mntId,
              content: value,
              createdAt: new Date(),
            })
              .then(res => {
                const msg = res.data.data;
                msg.createdAt = this.timestampToTime(msg.createdAt);
                if (msg.targetId === this.commentTree[index].mainMessage.id) {
                  msg.targetId = null;
                }
                this.commentTree[index].children[msg.id] = msg;
                this.commentContent = "";
                ElMessage.success("发送成功");
              });
          }
        }).catch(() => {
        ElMessage.info("取消输入");
      });
    },
  },
};
</script>

<style scoped>
@import "tabs.css";
</style>
