<template>
  <div class=communitybase>

    <div class=leftinfo>
      <div class=focus style="position: absolute; font-weight: bold; font-size: 18px; left:8%;top:1%">
        你的关注
      </div>
      <div class=num style="position:absolute; font-size: 14px; right:20%; top:1.5%; color: #45D4CF;">
        {{ totalWeidu}}条新动态
      </div>
      <div style="top:6%;position: absolute;width: 100%;">
        <div class="alldongtai"
          style="display: flex; flex-direction: row;justify-content:center;  align-items: center;position: relative;"
          @click="alldongtai">
          <el-icon color="#45D4CF" size="30px">
            <Grid />
          </el-icon>
          <div style="margin-left: 40px; font-weight: bold; font-size: 16px;">全部动态</div>
        </div>
        <hr style="width: 100%; height: 0.001px; background-color: #D8D8D8;margin-top: 1%;">
      </div>

      <div class=followslist
        style="position:absolute;display: flex;flex-direction: column;top:10%;width:100%;height: 100%;gap:2%; ">

        <div v-for="(follow, index) in myfollows" :key="index" style="width: 100%;">
          <div class="follows"
            style="display: flex; flex-direction: row; justify-content: center; align-items: center; position: relative;height: 120%;gap:3%;width: 100%;"
            @mouseover="hoverIndex = index" @mouseleave="hoverIndex = -1" @click="fllowsClick(follow.myfollowid,index)"
            :class="{'selected': selectedIndex === index}">
            <img class="touxiang" src="../../assets/pictures/touxiang.png" style="left:20%;width: 15%; height: auto;" />
            <div style="margin-left: 40px; font-weight: bold; font-size: 16px;">{{ follow.myfollowid }}</div>
            <el-tag v-if="follow.newpostnum" effect="plain" round style="position: absolute; right:0%">
              {{follow.newpostnum}}条新动态
            </el-tag>
          </div>
          <hr style="width: 100%; height: 0.001px; background-color: #D8D8D8; margin-top: 1%;">
        </div>


      </div>
    </div>

    <div class="middle">
      <PostForm @post-submitted="submitPost" />
      <div class="post-list">
        <!-- 使用 transition-group 来包裹 v-for 渲染的元素 -->
        <ul v-infinite-scroll="load" class="infinite-list">
          <transition-group name="fade" tag="div">
            <div v-for="(post, index) in checkPosts" :key="post.postid" class="post-card"
              :infinite-scroll-target="'.middle'">

              <PostCard :avatarUrl="post.avatarurl" :username="post.username" :timestamp="post.timestamp"
                :content="post.content" :imageUrl="post.imageurl" :likeCount="post.likecount" :postid="post.postid"
                :commentCount="post.commentcount" :isCommentsVisible="post.isCommentsVisible" :comments="post.comments"
                :postuserid="post.userid" :userid="userid" :isfamilystory="post.isfamilystory"
                :userlikelist="this.userlikelist" @updateLikeCount="updateLikeCount(index, $event)"
                :myfollows="this.myfollows" @updateCommentCount="updateCommentCount(index, $event)"
                @toggleCommentsVisibility="toggleCommentsVisibility(index,post.postid)"
                @addComment="addComment(index, $event,post.postid)" />

            </div>
          </transition-group>
        </ul>
      </div>
    </div>


    <div class=rightheat style="display: flex;flex-direction:column;">

      <div style="position:relative; top:1%; display: flex;flex-direction:row;justify-content:center;gap:15px">
        <el-icon color="red" size="30px">
          <Odometer />
        </el-icon>
        <div style="font-weight:550; font-size: 18px;">热门动态</div>
      </div>
      <div class=heatlist style="margin-top:20px;display: flex;flex-direction:row;">
        <div
          style="position:relative; display: flex;flex-direction:column;  color: white; font-weight: bold;margin-left: 20px ;gap:51px">
          <div class=Hotsearchnum style="background-color:red;">1</div>
          <div class=Hotsearchnum style="background-color:#ff8e51;">2</div>
          <div class=Hotsearchnum style="background-color:#ffc74fd2;">3</div>
          <div class=Hotsearchnum style="background-color:gray;">4</div>
          <div class=Hotsearchnum style="background-color:gray;">5</div>

        </div>
        <div
          style="font-size: 14px; font-weight: 500; margin-left: 30px; display: flex; flex-direction: column; gap: 17px;width: 100%;">
          <div
            style="overflow: hidden; list-style-type: none; width: 90%; height: 20%; background-color: rgba(255, 225, 240, 0.7); border-radius: 10%; position: relative; cursor: pointer;"
            v-for="(Hotsearch, index) in HotsearchList" :key="index" @click="checkbypostid(Hotsearch.postid)">

            <div style=" font-weight: bold; margin-left: 10%; margin-top: 1%; ">{{ Hotsearch.username }}:</div>
            <div style="left:10%;width: 70%; font-size: 12px;position: relative;">{{ Hotsearch.content}}</div>

            <svg width="20" height="20" viewBox="0 0 15 15" xmlns="http://www.w3.org/2000/svg" id="fire-station"
              style="position: absolute;right:7% ;top:20%;fill:red ">
              <path
                d="M7.5 14C11.0899 14 14 11 14 7.50003C14 4.5 11.5 2 11.5 2L10.5 5.5L7.5 1L4.5 5.5L3.5 2C3.5 2 1 4.5 1 7.50003C1 11 3.91015 14 7.5 14ZM7.5 12.5C6.11929 12.5 5 11.3807 5 10C5 8.61929 7.5 5.5 7.5 5.5C7.5 5.5 10 8.61929 10 10C10 11.3807 8.88071 12.5 7.5 12.5Z" />
            </svg>
            <div style="position: absolute;right:7% ;top:60%;font-size: 12px;color: red;"> {{ (Hotsearch.commentcount *
              2 + Hotsearch.likecount) }}</div>
          </div>
        </div>

      </div>
      <div
        style="width: 100%; height: 1px; background: linear-gradient(to right, transparent, gray, transparent);margin-top: 20px">
      </div>
      <div style="position:relative; top:1%; display: flex;flex-direction:row;justify-content:center;gap:15px">
        <el-icon color="#FEB7D9" size="25px">
          <Notebook />
        </el-icon>
        <div style="font-weight:550; font-size: 18px;">热门家族故事</div>

        <button class="refresh-btn" @click="refresh">
          <svg class="refresh-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
            <path
              d="M12 4V1L8 7l4 4V6c4.97 0 9 4.03 9 9s-4.03 9-9 9-9-4.03-9-9h2c0 3.87 3.13 7 7 7s7-3.13 7-7-3.13-7-7-7z" />
          </svg>
          换一批
        </button>

      </div>
      <div class="familystorelist"
        style="margin-top: 20px; display: flex; justify-content: center; flex-direction: column; gap: 10px;">
        <div v-for="(story, index) in familystories" :key="index" class="familystore"
          style="width: 95%; height: 70px; background-color: rgba(255, 225, 240, 0.7); border-radius: 10%; position: relative;cursor: pointer;"
          @click="checkbypostid(story.postid)">
          <img class="touxiang" src="../../assets/pictures/touxiang.png" />
          <div class="familytitle">{{ story.username }}</div>
          <div class="familycontent">{{ story.content }}</div>
        </div>
      </div>


    </div>

  </div>

</template>
<script>
  import PostCard from './PostCard.vue';
  import PostForm from './Postform.vue';
  import axios from '@/utils/axiosConfig';
  import {getUserId} from '@/token/auth'
  export default {
    name: 'CommunityIndex', // 添加组件名称
    components: { PostCard, PostForm },
    // 其他组件选项
    data() {
      return {
        HotsearchList: [],
        familystories: [],
        myfollows: [],
        userlikelist: [],
        hoverIndex: -1,
        selectedIndex: -1,
        isloading: false,
        loaddone: 0,
        checkPostsindex: 0,
        checkPosts: [],
        page: 1,
        userid: 1,
        totalPages: 1,
        posts: [
          {

          },
        ]
      };
    },
    computed: {
      totalWeidu() {
        // 使用reduce方法来遍历数组并计算总和
        return this.myfollows.reduce((sum, item) => sum + item.newpostnum, 0);
      }

    },

    created() {
      // 在组件实例创建时调用

      this.loadData();
    },




    methods: {


      async loadData() {
        try {
          this.userid= getUserId();
         
          // 确保异步操作按顺序执行
          await this.fllowlist();
          await this.loadhotpost();
          await this.loadhotfamilystory();
          await this.loaduserlikes();
        } catch (error) {
          console.error("加载数据时发生错误:", error);
        } finally {
          // 所有操作完成后再设置 isloading 为 true
          this.isloading = true;
          this.load();//等待这四个信息加载完再加载帖子 不然有BUG 会重复加载一页帖子
        }
      },
      async fllowlist() {

        const userid = this.userid;//获取用户id
        axios.get(`http://localhost:8082/loveforest/Myfollows/userid=${userid}`)
          .then(response => {


            this.myfollows.splice(0, this.myfollows.length);
            this.myfollows.push(...response.data);

            return response.data;
          })
          .catch(error => {
            console.error('Error:', error);
          });

      },

      submitPost(newpost) {//发布帖子后，本地显示帖子
        this.checkPosts = [newpost, ...this.checkPosts];

      },
      async load() {//加载帖子函数
        if (this.isloading) {
          try {
            const response = await axios.get(`http://localhost:8082/loveforest/posts`, {
              params: {
                page: this.page,
                size: 5,
              },
            });

            const filteredPostsList = response.data.records;


            this.$message("动态加载中page" + this.page);

            this.checkPosts.push(...filteredPostsList);
            this.page = this.page + 1;
          } catch (error) {
            console.error("动态加载失败", error);
          }
        }

      },
      async checkbypostid(postid) {//根据postid显示单个帖子 用于热门动态以及热门家族故事


        try {
          const response = await axios.get(`http://localhost:8082/loveforest/posts/postid=${postid}`);
          this.isloading = false;
          this.checkPosts.splice(0, this.checkPosts.length);
          this.checkPosts.push(response.data);


        } catch (error) {
          console.error('动态获取失败', error);
        }


      },

      async loaduserlikes() {//加载user点赞列表 并会传入每个帖子做是否已经点赞的判断
        const userid = this.userid;//获取用户id
        axios.get(`http://localhost:8082/loveforest/likes/userid=${userid}`)
          .then(response => {

            this.userlikelist.splice(0, this.myfollows.length);
            this.userlikelist.push(...response.data);

            return response.data;
          })
          .catch(error => {
            console.error('Error:', error);
          });


      },

      alldongtai() {//显示所有动态
        this.isloading = true;
        this.checkPosts.splice(0, this.checkPosts.length);
        this.page = 1;
        this.load();
        this.selectedIndex = -1;

      },
      async loadhotpost() {//加载热门动态
        try {
          const response = await axios.get(`http://localhost:8082/loveforest/posts/topposts`);
          this.HotsearchList.push(...response.data);
          console.log(response.data);

        } catch (error) {
          this.$message.error("热门动态获取失败");
          console.error('热门动态获取失败', error);
        }

      },

      async loadhotfamilystory() {//加载热门家族故事
        try {
          const response = await axios.get(`http://localhost:8082/loveforest/posts/topfamilystory`);
          this.familystories.push(...response.data);


        } catch (error) {
          this.$message.error("热门家族故事获取失败");
          console.error('热门家族故事获取失败', error);
        }

      },

      async fllowsClick(userid, index) {//左侧关注列表点击后单独显示关注用户的动态

        this.myfollows[index].newpostnum = 0;
        this.selectedIndex = index;  // 点击后设置选中的项

        try {
          const response = await axios.get(`http://localhost:8082/loveforest/posts/userid=${userid}`);
          this.isloading = false;
          this.checkPosts.splice(0, this.checkPosts.length);

          this.checkPosts.push(...response.data);
          if (response.data.length === 0) {
            this.$message("对方还没有发过动态哦");
          }


        } catch (error) {
          console.error('动态获取失败', error);
          this.$message.error("动态获取失败");
        }

      },


      updateLikeCount(index, newLikeCount) {//用于本地显示的点赞数量变化
        this.checkPosts[index].likecount = newLikeCount;
      },
      updateCommentCount(index, newCommentCount) {//用于本地显示的点赞数量变化
        this.checkPosts[index].commentcount = newCommentCount;
      },
      async toggleCommentsVisibility(index, postid) {//展开评论以及获取评论列表
        this.$message("评论区展开" + index);
        try {
          const response = await axios.get(`/comments/postid=${postid}`);
          this.checkPosts[index].comments = response;
          
          this.checkPosts[index].isCommentsVisible = !this.checkPosts[index].isCommentsVisible;

        } catch (error) {
          console.error('评论获取失败', error);
          this.$message.error("评论获取失败");
        }


      },
      async addComment(index, commentText, postid) {//发送评论

        try {
          const response = await axios.post('http://localhost:8082/loveforest/comments/addcomments', {
            userid: this.userid,
            postid: postid,
            content: commentText
          }, {
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
          });
          if (response.startsWith ("评论成功！")) {
            this.$message.success("评论成功！");
            const id = response.replace("评论成功！", '').trim();
            this.checkPosts[index].comments.push({
              username: '用户名',//等待user接口
              postid: postid,
              content: commentText,
              commentid:id,
              userid:this.userid
            });
            this.checkPosts[index].commentCount += 1;
          }
          else {
            this.$message.error(response.data);
          }

        } catch (error) {
          console.error('评论失败:', error);
          this.$message.error('评论失败');
        }



      },
      refresh() {//热门家族故事刷新换一批按钮
        // 点击后触发的刷新动作
        console.log('Refreshing...');
        this.triggerAnimation();
      },



      triggerAnimation() {
        const button = document.querySelector('.refresh-btn');
        button.classList.add('clicked');

        // 动画结束后移除动画类
        setTimeout(() => {
          button.classList.remove('clicked');
        }, 600); // 动画持续时间，确保动画完成后移除类
      },
    }
  }
</script>

<style scoped>
  @import url('../../assets/css/community/community.css');
</style>