<template>
  <div>
    <div class="user-coin-card mb-4">
      <div class="row" style="width: 100%">
        <!-- 内容 -->
        <div class="container">
          <div class="content-wrap" style="float: none">
            <div class="content-layout">
              <div class="fixed-wrap bbs-home-tab">
                <div class="fixed-wrap-content">
                  <div class="tab-content bbs-main-tab-content">
                    <!-- 文章列表 -->
                    <div class="ajaxpager active" id="home-tab-2">
                      <div class="forum-posts detail alone ajax-item">
                        <div class="user-info flex ac mb10">
                          <!-- <a href="/"> -->
                          <div @click="showConfirm">
                            <span class="avatar-img"
                              ><img
                                src="https://onlinephoto.oss-cn-chengdu.aliyuncs.com/hangtian/touxiang.jpg"
                                data-src="//www.cmstui.com/wp-content/themes/zibll/img/avatar-default.png"
                                class="lazyload avatar avatar-id-1"
                              />
                            </span>
                          </div>
                          <!-- </a> -->
                          <div class="user-right flex flex1 ac jsb ml10">
                            <div class="flex1">
                              <div class="flex ac flex1">
                                <a
                                  class="display-name text-ellipsis"
                                  href="/"
                                  >{{ getUserName(forums.userId) }}</a
                                >
                              </div>
                            </div>
                          </div>
                        </div>
                        <!-- 将原来的文章内容显示部分替换为 -->
                        <div class="content mt6">
                          <div 
                            class="markdown-body"
                            v-html="forums.articleContent"
                          ></div>
                        </div>
                        <div class="flex ac jsb mt10">
                          <div class="action-meta flex0 flex jsb">
                            <div class="score-btns">
                              <a
                                href="javascript:;"
                                ajax-action="score_extra"
                                class="btn-score extra"
                                ><svg class="icon" aria-hidden="true">
                                  <use
                                    xlink:href="#icon-extra-points"
                                  ></use></svg></a
                              ><text>评分</text>
                              <a
                                href="javascript:;"
                                ajax-action="score_deduct"
                                class="btn-score deduct"
                                ><svg class="icon" aria-hidden="true">
                                  <use
                                    xlink:href="#icon-deduct-points"
                                  ></use></svg
                              ></a>
                            </div>
                            <a href="#" class="item"
                              ><svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-comment"></use></svg
                              ><text>回复</text></a
                            >
                            <a
                              mobile-bottom="true"
                              data-height="243"
                              class="btn-share item"
                              href="javascript:;"
                              data-toggle="RefreshModal"
                              ><svg class="icon" aria-hidden="true">
                                <use xlink:href="#icon-share"></use></svg
                              ><text>分享</text></a
                            >
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <section id="comments" class="box-show wow fadeInDown">
            <div id="comt-respond" class="commentpost">
              <h4>
                发表评论<span
                  ><a
                    rel="nofollow"
                    id="cancel-reply"
                    href="#comment"
                    class="page_speeder_1817808094"
                  ></a
                ></span>
              </h4>
              <form id="frmSumbit">
                <input type="hidden" id="inpId" value="413" />
                <input type="hidden" id="inpRevID" value="0" />

                <div id="comment-tools">
                  <div class="tools_text">
                    <textarea
                      placeholder="请输入您的评论"
                      name="txaArticle"
                      id="txaArticle"
                      class="text input-block-level comt-area"
                      cols="50"
                      rows="4"
                      tabindex="5"
                      v-model="text"
                    ></textarea>
                  </div>
                </div>
              </form>
              <div class="psumbit">
                <a-button type="primary" @click="PublishComments">
                  提交
                </a-button>
              </div>
            </div>
            <div id="commentlist" class="commentlist">
              <div class="comment-tab">
                <div class="come-comt">
                  评论列表 <span id="comment_div"></span>
                </div>
              </div>
            </div>
            <h2 class="comment-text-center" v-if="!this.msg">
              <i class="icon font-meiyou"></i> 还没有评论，来说两句吧...
            </h2>
            <label id="AjaxCommentBegin"></label>
            <div v-for="(item, index) in comments" :key="index">
              <div
                class="shadow-box msg noimg wow fadeInRight"
                data-wow-delay="0.25s"
                id="cmt225"
              >
                <!-- 只有当评论作者是当前用户时才显示删除按钮 -->
                <div
                  v-if="item.userId === userId"
                  class="delete-btn"
                  @click="DeleteComments(item)"
                >
                  删除
                </div>
                <div class="msgimg">
                  <img
                    class="avatar"
                    :src="getUserAvatar(item.userId)"
                    :alt="getUserName(item.userId)"
                    :title="getUserName(item.userId)"
                  />
                </div>

                <div class="msgtxt">
                  <div class="msgname">
                    <span class="autlv aut-6 vs">{{ getUserRole(item.userId) }}</span>
                    <span class="autlv autlvname aut-6">{{ getUserName(item.userId) }}</span>
                    <span class="dot">{{ index === 0 ? '沙发' : `${index + 1}楼` }}</span>
                  </div>
                  <div class="interact-bar">
                    <span class="interact-time" title="评论时间">{{
                      item.publishTime | formatTime
                    }}</span>
                  </div>
                  <div class="msgarticle">
                    {{ item.commentContent }}
                    <label id="AjaxComment225"></label>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </div>
        <!-- 评论列表 -->
      </div>
    </div>
  </div>
</template>
<script>
import {
  ArticleById,
  CommentsById,
  PublishComments,
  DeleteComments,
  AllUser,
} from "@/api";
import MarkdownIt from 'markdown-it';

export default {
  name: "UserCenter",
  data() {
    return {
      userId: this.$store.state.user.userId,
      userName: this.$store.state.user.userName,
      likes: "",
      dianzan: "",
      forums: {},
      ArticleId: this.$route.query.id,
      text: "",
      msg: "",
      comments: [],
      users: [],
      userMap: {}, // 用于缓存用户信息
    };
  },

  mounted() {
    this.fetchData();
    this.getuser();
  },
  filters: {
    formatTime(time) {
      // 将 ISO 8601 格式的时间转换为 Date 对象
      const date = new Date(time);
      // 获取年月日时分秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      // 返回格式化后的时间字符串
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  methods: {
    showConfirm() {
      this.$confirm({
        title: "添加好友?",
        content: "是否现在与该用户进行聊天",
        onOk: () => {
          // 使用箭头函数定义回调函数
          let data = {
            friendId: this.forums.userId,
            friendName: this.getUserName(this.forums.userId),
          };
          console.log(data);
          this.$api.addFriend(data).then((res) => {
            console.log(res);
          });
        },
        onCancel() {},
      });
    },

    PublishComments() {
      // 发布评论
      let formdata = {
        articleId: this.ArticleId,
        commentContent: this.text,
        userId: this.userId,
      };
      // console.log(formdata);
      PublishComments(formdata)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("发布成功");

            // 发布成功后重新获取评论
            this.fetchData();
          }
        })
        .catch((error) => {
          console.log(error);
          this.$message.error(error.msg || "发布失败");
        });
    },

    // 添加 markdown 渲染方法
    renderMarkdown(content) {
      if (!content) return '';
      return this.md.render(content);
    },

    fetchData() {
      // 获取文章
      let datas = { id: this.ArticleId };
      ArticleById(datas)
        .then((res) => {
          if (res.code === 200) {
            // 初始化 markdown-it
            const md = new MarkdownIt({
              html: true,
              linkify: true,
              typographer: true,
              breaks: true
            });
            
            // 处理文章内容，将 Markdown 转换为 HTML
            this.forums = {
              ...res.data,
              articleContent: md.render(res.data.articleContent || '')
            };
            
            // 获取评论数据
            this.fetchComments();
          }
        })
        .catch((error) => {
          console.error("获取文章失败:", error);
          this.$message.error("获取文章失败");
        });
    },

    fetchComments() {
      // 获取评论
      let data = { id: this.ArticleId };  // 修改为使用 id 作为参数名
      CommentsById(data)
        .then((res) => {
          if (res.code === 200) {
            this.comments = res.data || [];  // 确保 comments 始终是数组
            this.msg = this.comments.length;
          } else {
            this.$message.error(res.msg || "获取评论失败");
            this.comments = [];  // 失败时重置为空数组
            this.msg = 0;
          }
        })
        .catch((error) => {
          console.error("获取评论失败:", error);
          this.$message.error("获取评论失败");
          this.comments = [];  // 错误时重置为空数组
          this.msg = 0;
        });
    },
    // 获取用户信息并缓存
    async getuser() {
      try {
        const response = await AllUser();
        this.users = response.data;
        // 创建用户信息映射
        this.userMap = this.users.reduce((map, user) => {
          map[user.userId] = user;
          return map;
        }, {});
      } catch (error) {
        console.error("Failed to load users:", error);
        this.$message.error("获取用户信息失败");
      }
    },

    // 获取用户名
    getUserName(userId) {
      return this.userMap[userId]?.userName || "未知用户";
    },

    // 获取用户头像
    getUserAvatar(userId) {
      return this.userMap[userId]?.avatar || "https://onlinephoto.oss-cn-chengdu.aliyuncs.com/hangtian/touxiang.jpg";
    },

    // 获取用户角色
    getUserRole(userId) {
      const user = this.userMap[userId];
      if (!user) return "V";
      
      switch(user.role) {
        case "admin":
          return "管理员";
        case "teacher":
          return "教师";
        case "student":
          return "学生";
        default:
          return "V";
      }
    },
  }
};
</script>
<style src="@/assets/pages.css"></style>
<style scoped>
button {
  color: #ffffff;
  background-color: #3690cf;
  height: 30px;
  width: 88px;
  border-top-width: 0;
  border-right-width: 0;
  border-bottom-width: 0;
  border-left-width: 0;
  border-radius: 4px;
  float: right;
  margin: 2px 10px 0 10px;
}

.router-link-exact-active {
  color: none;
}

.delete-btn {
  display: flex;
  justify-content: flex-end;
  padding: 5px 10px;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.delete-btn:hover {
  color: #ff7875;
}

.msgname {
  display: flex;
  align-items: center;
  gap: 8px;
}

.autlv {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
}

.aut-6.vs {
  background-color: #3690cf;
  color: white;
}

.dot {
  color: #999;
  font-size: 12px;
}

.interact-time {
  color: #999;
  font-size: 12px;
}

.msgarticle {
  margin-top: 8px;
  line-height: 1.6;
}

/* 添加 Markdown 样式 */
:deep(.markdown-body) {
  color: #24292e;
  font-size: 16px;
  line-height: 1.5;
}

:deep(.markdown-body h1),
:deep(.markdown-body h2),
:deep(.markdown-body h3),
:deep(.markdown-body h4),
:deep(.markdown-body h5),
:deep(.markdown-body h6) {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

:deep(.markdown-body code) {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27,31,35,0.05);
  border-radius: 3px;
}

:deep(.markdown-body pre) {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

:deep(.markdown-body img) {
  max-width: 100%;
  box-sizing: content-box;
}

:deep(.markdown-body p) {
  margin-bottom: 16px;
}

:deep(.markdown-body blockquote) {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

:deep(.markdown-body table) {
  display: block;
  width: 100%;
  overflow: auto;
  border-spacing: 0;
  border-collapse: collapse;
}

:deep(.markdown-body table th),
:deep(.markdown-body table td) {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

:deep(.markdown-body table tr:nth-child(2n)) {
  background-color: #f6f8fa;
}
</style>
