<template>
  <div class="comment-section">
    <h2>评论区</h2>
    <!-- 评论列表 -->
    <div v-for="(comment, index) in commentList" :key="index" class="comment">
      <p class="comment-content">{{ comment.content }}</p>
      <div class="comment-meta">
        <span class="comment-username">{{ comment.username }}</span>
        <span class="comment-updated-at">{{ comment.updated_at }}</span>
      </div>
    </div>
    <!-- 添加评论表单 -->
    <form @submit.prevent="addComment">
      <textarea v-model="newComment" placeholder="添加评论..." required></textarea>
      <button type="submit">提交</button>
    </form>
  </div>
</template>
  
<script lang="ts" setup>
  import { ref,reactive,onMounted } from 'vue';
  import axios from 'axios';
  import { useLoginStore } from '@/stores/Login'; 
  import { useToast } from 'vue-toastification' 

  const toast = useToast();
  const loginStore = useLoginStore();

  const props = defineProps(['post_id'])

  interface comment{
  post_id: number;
  username: string;
  content: string;
  token: string;
  updated_at: string;
  }

  let commentList = ref<comment[]>([]);
  
  function getComments(){
    axios.get('http://localhost:8080/comment',{
      params:{
        post_id: props.post_id
      }
    })
    .then(res=>{
      commentList.value = res.data.data;
      console.log(commentList.value);
    })
    .catch(err=>{
      console.log(err);
    })
  }

  const newComment = ref('');
  const addComment = async () => {
    if(loginStore.userInfo.token===''||loginStore.userInfo.token===null){
      toast.error("请先登录");
    }
    else{
      axios.post('http://localhost:8080/comment',{
        post_id: props.post_id,
        content: newComment.value,
        token: loginStore.userInfo.token
      })
      .then(res=>{
        toast.success("评论成功");
        getComments();
        newComment.value = '';
      })
      .catch(err=>{
        console.log(err);
      })
    }
  };

  onMounted(()=>{
    getComments();
  })
</script>
  

<style scoped>
.comment-section {
  position: fixed;
  top: 100px;
  right: 50%; /* 调整右侧位置 */
  transform: translateX(250%); /* 调整位置以居中 */
  width: 300px;
  background-color: #fff;
  border: none;
  border-radius: 5px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
  height: 75vh;
  overflow-y: auto;
  overflow-x: hidden; 
}

.comment {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #ddd; /* 添加边框 */
  border-radius: 5px; /* 圆角边框 */
  background-color: #f9f9f9; /* 浅背景色 */
}

.comment-content {
  font-size: 16px;
  margin-bottom: 5px;
}

.comment-meta {
  font-size: 12px;
  color: #888;
}

.comment-username {
  margin-right: 10px;
}

textarea {
  width: 100%;
  height: 50px;
  margin-bottom: 10px;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 3px;
}

button {
  padding: 5px 10px;
  border: none;
  background-color: #007bff;
  color: #fff;
  border-radius: 3px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}
</style>