<template>
  <div class="container">
    <div class="content">
      <div class="profile-card">
        <!-- 头像 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <img :src="userInfo.avatar || defaultAvatar" alt="Avatar" class="avatar">
            <!-- 更多信息按钮 -->
            <button @click="editProfile" class="showFamilytree-btn" v-if="!userId">
              <img src="../../assets/pictures/space/more.png" alt="" style="width: 80px;">
            </button>
            <!-- 族谱树按钮 -->
            <button @click="showFamilyTree" class="showMoreInfo-btn">
              <img src="../../assets/pictures/space/tree.png" alt="" style="width: 80px;">
            </button>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="user-info">
          <h2 style="margin-bottom: 30px;">{{ userInfo.name || "用户" }}</h2>
          <div class="info-container">
            <p style="margin-right: 20px;">
              <img src="../../assets/pictures/space/map.png" style="width: 19px; margin-right: 5px;">
              {{ userInfo.location || "San Jose,California,USA" }}
            </p>
            <p>
              <img src="../../assets/pictures/space/calendar.png" style="width: 17px; margin-right: 5px">
              {{ userInfo.joinedDate || "1990/01/25" }}
            </p>
          </div>
        </div>

        <!-- 兴趣爱好 / 择偶期望 / 职业 -->
        <div class="interests">
          <p>
            <img src="../../assets/pictures/space/interest.png" alt="">
            <span class="in-text">
              <span class="title">兴趣爱好:</span>
              <span class="text-content" id="interest">{{ userInfo.interests || "gali建帅 马思唯最好" }}</span>
            </span>
          </p>
          <p>
            <img src="../../assets/pictures/space/double.png" alt="">
            <span class="in-text">
              <span class="title">择偶期望:</span>
              <span class="text-content" id="expectation">{{ userInfo.expectation || "长期关系" }}</span>
            </span>
          </p>
          <p>
            <img src="../../assets/pictures/space/career.png" alt="">
            <span class="in-text">
              <span class="title">职业:</span>
              <span class="text-content" id="career">{{ userInfo.career || "程序员" }}</span>
            </span>
          </p>
        </div>

        <!-- 操作按钮 -->
        <div class="actions">
          <button @click="logout" v-if="!userId">退出登录</button>
          <button @click="privateChat" v-if="userId">私聊</button>
        </div>
      </div>

        <div class="post-container">
          <div class="post" v-for="post in posts" :key="post.id">
            <div class="post-header">
              <img :src="post.avatarurl" alt="" />
              <div class="post-info">
                <h2>{{ post.name }}</h2>
                <h3>{{ post.date }}</h3>
                <p>{{ post.text }}</p>
              </div>
            </div>

            <div  v-if="post.postImageUrl" >
              <img :src="post.postImageUrl" alt="" class="post-img"/>
            </div>

            <div class="post-footer">
              <div class="reactions">
                <div class="Like">
                  <span @click="handleLike(post)" :class="{'liked': post.isLiked}">
                    <span v-if="post.isLiked">❤️</span>
                    <span v-else>🤍</span>
                  </span>
                  {{ post.likeCount }}
                </div>
                <div class="comment">
                  <span>💬</span>
                  {{ post.commentCount }}
                </div>
              </div>
              <div class="comments">
                <!-- 评论内容可以在这里渲染 -->
              </div>
            </div>

          </div>
        </div>
  </div>
  </div>
  </template>
  
  <script>
  import axios from '@/utils/axiosConfig'
  import {getUserId} from '@/token/auth'
  export default {
    props: ['userId'],
    name:'spaceIndex',
    data() {
      return {
        myId: 0,
        userlikelist:[],
        userInfo: {
          name: "", // 用户姓名
          avatar:"",
          location: "", // 用户位置
          joinedDate: "", // 加入时间
          interests: "", // 兴趣爱好
          expectation: "", // 择偶期望
          career: "", // 职业
        },
        posts:[
          {
            id: 0,
            avatarurl:require("../../assets/pictures/space/post1.png"),
            name:"掌声",
            date:"2024-01-01",
            text:"测试文本",
            postImageUrl:"../../assets/pictures/space/post1.png",
            likeCount: 0,
            commentCount: 0,
            isLiked:false,
          },
          {
            id: 1,
            avatarurl:require("../../assets/pictures/space/post1.png"),
            name:"掌声",
            date:"2024-12-01",
            text:"我好开心",
            postImageUrl:"",
            likeCount: 0,
            commentCount: 5,
            isLiked:false,
          },
          {
            id: 2,
            avatarurl:require("../../assets/pictures/space/post1.png"),
            name:"掌声",
            date:"2024-01-01",
            text:"测试文本",
            postImageUrl:"../../assets/pictures/space/post1.png",
            likeCount: 8,
            commentCount: 0,
            isLiked:false,
          },
        ],
        defaultAvatar: require("../../assets/pictures/space/avatar.png"), // 默认头像占位符
      };
  },
    methods: {
      async loaduserlikes() {//加载user点赞列表 并会传入每个帖子做是否已经点赞的判断
        const requestId = this.userId || this.myId;//获取用户id
        try {
          const response = await axios.get(`/likes/userid=${requestId}`);
          this.userlikelist = response; // Store the liked post IDs
          
          // Update isLiked status for all posts
          this.posts = this.posts.map(post => ({
            ...post,
            isLiked: this.userlikelist.some(like => like.postid === post.id)
          }));
          
        } catch (error) {
          console.error('Error:', error);
        }

        axios.get(`/likes/userid=${requestId}`)
          .then(response => {
            this.userlikelist.push(...response);
            return response;
          })
          .catch(error => {
            console.error('Error:', error);
          });
          if (this.userlikelist.some(follow => follow.postid === this.postid)) {
            this.isLiked = true;
          }
      },
      async handleLike(post) {//点赞按钮
        const requestId = this.userId || this.myId;
        if (!post.isLiked) {//假如没点赞
          try {
            const response = await axios.post(`/likes/userid=${requestId}/postid=${post.id}`);
            if (response === "点赞成功！") {
              post.isLiked = !post.isLiked;
              post.likeCount = post.likeCount + 1 ;
            }
            else {
              this.$message.error(response);
            }
          } catch (error) {
            this.$message.error("点赞失败");
            console.log(error);
          }
        }
        else {//假如已经点赞
          try {
            const response = await axios.delete(`/likes/userid=${requestId}/postid=${post.id}`);
            if (response === "取消点赞成功！") {
              post.isLiked = !post.isLiked;
              post.likeCount = post.likeCount - 1;
            }
            else {
              this.$message.error(response);
            }
          } catch (error) {
            this.$message.error("取消点赞失败");
            console.log("取消点赞失败:",error);
          }
        }
      },

      async fetchUserInfo() {
        await this.loaduserlikes();
        try {
          const requestId = this.userId || this.myId;
          // 调用后端接口获取用户信息
          const response = await axios.get("/getUserInfo", {
            params: {
              userId: requestId,
            },
          });

          // 更新数据
          this.userInfo.avatar = response.data.avatar;
          this.userInfo.name = response.data.name;
          this.userInfo.location = response.data.location;
          this.userInfo.joinedDate = response.data.joinedDate;
          this.userInfo.interests = response.data.interests;
          this.userInfo.expectation = response.data.expectation;
          this.userInfo.career = response.data.career;
        } catch (error) {
          console.error("获取用户信息失败:", error);
        }
      },
      async fetchPostInfo() {
        try {
          const requestId = this.userId || this.myId;
          const postResponse = await axios.get(`/posts/userid=${requestId}`);
          // 假设后端返回的数据中包含了用户是否对每个帖子点赞的信息
          this.posts = postResponse.map(post => ({
            id: post.postid, 
            avatarurl:post.avatarurl,
            name: post.username, 
            date: post.timestamp,
            text: post.content,
            postImageUrl: post.imageurl,
            likeCount: post.likecount,
            commentCount: post.commentcount,
            isLiked: this.userlikelist.some(like => like.postid === post.postid)
          }));
        } catch (error) {
          console.error("获取帖子信息失败:", error);
        }
    },
      showFamilyTree() {
        this.$router.push('/main/familyTree');

      },
      editProfile() {
        this.$router.push('/main/informationPage');  // 使用路由路径而不是文件路径
      },
      privateChat() {
        // Navigate to private chat page
      },
      logout() {
        this.$router.push('/')
      },
    },
    mounted() {
      // 获取当前登录用户的ID
      this.myId = getUserId();
      // 加载用户信息
      this.fetchUserInfo();
      this.fetchPostInfo();
    },
  };
  </script>
  
  <style scoped>
  .content {
    display: flex;
    justify-content: space-between;
    background-image: url("../../assets/pictures/space/Inbase2.png");
    padding: 20px;
    min-height: calc(100vh - 100px);
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
  }
  .profile-card {
    background-color: #FFFFFF;
    padding: 25px;
    border-radius: 30px;
    margin-top: 70px;
    margin-left: 80px;
    width: 430px;
    height: 580px;
    border-top: 10px solid #9EAFFD;
    position: relative; /* 为伪元素定位 */
  }

  .profile-card::before {
    content: '';
    position: absolute;
    top: -10px; /* 使蓝色区域位于框外 */
    left: 0;
    right: 0;
    height: 20px;  /* 蓝色区域的高度 */
    border-top-left-radius: 30px;  /* 圆角与卡片的左上角对齐 */
    border-top-right-radius: 30px;  /* 圆角与卡片的右上角对齐 */
    overflow: hidden;
  }
  .avatar-section {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
  }
  .avatar-container {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .avatar {
    margin-bottom: 20px;
    width: 138px;
    height: 138px;
    border-radius: 50%;
  }
  .showMoreInfo-btn,
  .showFamilytree-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 80px;
    height: 80px;
    border-radius: 50%; /* 圆形按钮 */
    border: none;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
  }

.showMoreInfo-btn {
  left: -130px; /* 在头像左侧 */
  top: 110px;
}
.showFamilytree-btn {
    right: -130px; /* 在头像右侧 */
    top: 110px;
  }
  .user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
  .user-info h2{
    font-size: 21px;
    margin-top: 8px;
    font-weight: normal;
    font-style: Italic;
    white-space: nowrap; /* 防止文本换行 */
  }
  .info-container {
    display: flex;
    justify-content: center;
    margin-top: -55px;
    gap: 5px;
  }
  .user-info p{
    margin-top: 40px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    font-size: 14px;
    white-space: nowrap;
  }
  .interests p{
    display: flex;
    flex-direction: row;
    align-content: center;
    margin-top: 4px;
  }
  .interests p img{
    width: 44px;
    height: 44px;
    margin-top: 6px;
    margin-left: 8px;
  }
  .interests p .in-text{
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
  .interests p .title{
    margin-left: 12px;
    margin-top: 10px;
    font-size: 18px;
    font-weight: bold;
    white-space: nowrap;
  }
  .interests p .text-content{
    font-size: 14px;
    margin-left: 10px;
  }
  .actions {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .actions button {
    color:white;
    font-size: 18px;
    background-color: #f077a8;
    padding: 12px 20px;
    margin-left: 55px;
    margin-right: 40px;
    margin-top: 30px;
    border: none;
    border-radius: 30px;
    width: 115px;
    cursor: pointer;
  }
  .post-container {
  font-family: Arial, sans-serif;
  display: flex;
  flex-direction: column;
  /* align-items: center; */
  background: rgba(255, 255, 255, 0.8);
  height: 680px;
  margin: 30px auto;
  border-radius: 30px;
  width: 750px;
  padding: 20px;
  overflow-y: auto;
}
.post {
  margin-left: 0;
  margin-top: 150px;
  height: 150px;
  width: 680px;
  position: relative; /* 使得子元素可以相对移动 */
  margin-bottom: 70px;
  padding: 0 20px;
  /* border-bottom: 2px solid #d1cccc; */
}

.post-header {
  display: flex;
  margin-top:-160px;
  margin-left: 30px;
  padding: 10px;
  position: relative;
}

.post-header::before {
  content: '';
  position: absolute;
  left: 30px; /* 根据需要调整左侧位置 */
  top: -10px; /* 调整横线的位置 */
  width: calc(100% - 60px); /* 横线宽度，减去左右边距 */
  height: 1px; /* 横线的高度 */
  /* background-color: #d1cccc; 横线颜色 */
}

.post-header img {
    margin-top: 10px;
    width: 56px; 
    height: 56px;
    border-radius: 50%; 
}
.post-info h2{
  font-weight: normal;
  font-size: 20px;
  padding-left: 10px;
  margin-top: 9px;
}

.post-info h3 {
  margin-top: -12px;
  padding-left: 12px;
  font-size: 14px;
  font-weight: normal;
  font-family: Italic;
  font-style: ABeeZee;
  white-space: nowrap;
}

.post-info p {
  margin: 0;
  font-size: 18px;
  white-space: nowrap;
  margin-left: 80px;
}

.post-img {
  
  
  max-width: 700px;
  max-height: 500px;
  width: auto;
  height: auto;
    
 
}

.post-footer {
  padding: 10px;
  left: 30px; /* 根据需要调整左侧位置 */
  top: -10px; /* 调整横线的位置 */
  width: calc(100% - 60px); /* 横线宽度，减去左右边距 */
  border-bottom: 1.5px solid #d1cccc;
}

/* 图标的样式 */
.reactions span {
  font-size: 24px;
  cursor: pointer;
  margin: 0 2px;
  display: inline-block;
  transition: transform 0.3s;
}

/* 点赞图标选中时的样式 */
.liked {
  color: red; /* 红色表示已点赞 */
  transform: scale(1.2); /* 点击时稍微放大 */
}

/* 图标悬停时的效果 */
.reactions span:hover {
  /* transform: scale(1.1); 悬停时稍微放大 */
}

/* 增加点赞和评论数值的可读性 */
.reactions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 20px;
  padding: 6px 10px;
}

.comment{
  display: flex;
  align-items: center;
  margin-right: 120px;
}

.Like{
  margin-left: 220px;
}
/* .reactions span img {
  padding-left: 230px;
  padding-top: 10px;
} */

.reactions .count {
  font-size: 21px;
  color: #666;
  padding-left: 8px;
}
  </style>