<template>
  <div class='top'>
    <div class="releaseRecord" @click="gotoRecord">
        <svg-icon class="releaseRecord-icon" name="pulishIcon" />
        <div class="releaseRecord-text">发布记录</div>
    </div>
    <div class="search" @click="goSearch">
      <svg-icon class="search-icon" name="search" />
      <span>搜索</span>
    </div>
    <div class="publish" @click="goPublish">发布</div>
  </div>

  <div class="content">
    <!-- 下拉刷新 + 上拉列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="finished"
        :loading="loading"
        :immediate-check="false"
        @load="onLoadMore"
      >
        <template #default>
          <div class="content-item" v-for="(item, i) in list" :key="item.dynamic_id">
            <div class="item-header">
              <van-image class="avatar" round :src="item.avatar"/>
              <div class="user-info">
                <div class="nickname">{{ item.name }}</div>
                <div class="desc">{{ item.content }}</div>

                <!-- 图片 -->
                <div v-if="item.images.length > 0" class="more-images">
                  <div v-for="(img, idx) in item.images" :key="idx">
                    <div v-if="item.images.length > 1" class="img-box">
                      <van-image round class="more-img-size" fit="cover" :src="img" @click="previewImage(i, idx)"/>
                    </div>
                    <div v-else class="main-img">
                      <van-image round class="main-img-size" fit="cover" :src="img" @click="previewImage(i, idx)"/>
                    </div>
                  </div>
                </div>

                <!-- 视频 -->
                <!-- <video v-if="item.video"
                  :src="item.video"
                  controls
                  width="200" height="300"
                  style="border-radius:8px; margin-top:8px;">
                </video> -->
                <!-- 视频封面 + 播放按钮 -->
                <div v-if="item.video" class="course-video" @click="handlePlay(item)">
                  <!-- 播放按钮蒙层 -->
                  <div class="relative-shadow">
                    <van-icon name="play-circle-o" class="play-icon"/>
                  </div>
                  <!-- 封面图 -->
                  <van-image
                    :src="item.video_thumb || defaultVideoThumb"
                    fit="cover"
                    width="200"
                    height="300"
                    class="video-thumb"
                  />
                </div>

                <!-- 底部点赞评论按钮 -->
                <div class="item-footer">
                  <div class="time">{{ item.created_at }}</div>
                  <div style="position: relative;">
                    <div @click="toggleActions(i,item)" style="cursor:pointer; display:inline-block;">
                      <svg-icon class="actions-icon" name="more1"/>
                    </div>
                    <transition name="slide-left-fade">
                      <div v-if="showActionsMap[i]" class="actions-popup" @click.stop>
                        <button class="action-btn" @click="onLike(i,item)">点赞</button>
                        <button class="action-btn" @click="handleComment(i, item)">评论</button>
                      </div>
                    </transition>
                  </div>
                </div>

                <!-- 点赞静态数据 -->
                <div class="like-row" v-if="item.dynamic_like.length > 0">
                  <!-- {{ item.dynamic_like.map(n => n.name).join(', ') }} -->
                  <van-image v-for="(n,likeindex) in item.dynamic_like" :key="i + '-' + likeindex" class="like-avatar" round :src="n.avatar"/>
                </div>

                <!-- 评论静态数据 -->
                <Remark 
                  ref="remarkRefs"
                  :comments="item.commnet_array"
                  :dynamic-id="item.dynamic_id"
                  :user-id="item.user_id"
                  @update:comments="setComments(i, $event)">
                </Remark>
              </div>
            </div>
          </div>
        </template>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { dynamicList, dynamicLike,dynamicDetail } from "@/api/path/im.api";
import { showToast, showImagePreview } from 'vant';
import Remark from '../../components/remarkList/index.vue';

export default {
  components: { Remark },
  data() {
    return {
      list: [],
      page: 1,
      total: 0,
      loading: false,
      finished: false,
      refreshing: false,
      showActionsMap: {},
      remarkRefs: [],
    }
  },
  methods: {
    async loadList(isRefresh = false) {
      if (this.loading) return;
      this.loading = true;
      try {
        const res = await dynamicList({ page: this.page });
        if (res.code !== 1) {
          showToast(res.message || "加载失败");
          return;
        }
        const decoded = JSON.parse(atob(res.data));
        console.log(decoded)
        this.total = decoded.total || 0;

        const processedList = decoded.list.map(item => ({
          ...item,
          images: item.images
            ? (typeof item.images === "string" ? item.images.split(',').filter(Boolean) : item.images)
            : [],
          video: item.video || ''
        }));

        if (isRefresh) {
          this.list = processedList;
          this.page = 2;
          this.refreshing = false;
        } else {
          this.list = [...this.list, ...processedList];
          this.page++;
        }

        if (this.list.length >= this.total) this.finished = true;
      } catch (err) {
        showToast(err.message || "加载失败");
      } finally {
        this.loading = false;
        if (isRefresh) this.refreshing = false;
      }
    },
    onRefresh() {
      this.page = 1;
      this.list = [];
      this.finished = false;
      this.loadList(true);
    },
    onLoadMore() {
      this.loadList(false);
    },
    // 点赞/评论弹框
    toggleActions(index) {
      for (const key in this.showActionsMap) {
        if (Number(key) !== index) this.showActionsMap[key] = false;
      }
      this.showActionsMap[index] = !this.showActionsMap[index];
    },
    // 点赞
    async onLike(index, item) {
      try {
        const res = await dynamicLike({ dynamic_id: item.dynamic_id });
        if (res.code == 1) {
          showToast(res.message);
          // 刷新列表
          this.setLike(index,item.dynamic_id);
        } else {
          showToast(res.message || '点赞失败');
        }
      } catch (error) {
        showToast(error.message || '点赞失败');
      } finally {
        this.showActionsMap[index] = false;
      }
    },
    // 评论
    handleComment(i,item) {
      this.showActionsMap[i] = false;
      const comp = this.$refs.remarkRefs[i];
      if (comp && comp.openComment) {
        comp.openComment({ user_id: item.user_id, dynamic_id: item.dynamic_id });
      }
    },
    // 更新指定动态的点赞列表
    async setLike(index,dynamic_id){
      const res = await dynamicDetail({ dynamic_id });
      this.list[index] = {
        ...this.list[index],
        dynamic_like: res.data.like_array
      };
    },
    // 更新指定动态的评论列表
    setComments(index, newComments) {
      this.list[index].commnet_array = newComments;
    },
    previewImage(itemIndex, imgIndex) {
      const urls = this.list[itemIndex].images;
      showImagePreview({
        images: urls,
        startPosition: imgIndex,
      });
    },
    handlePlay(item) {
      console.log(item)
      this.$router.push({
        path: '/videoPlayer',
        query: {
          name: item.filename,
          src: encodeURIComponent(item.video)
        }
      })
    },
    gotoRecord() {
      this.$router.push('record');
    },
    goPublish() {
      this.$router.push('publish');
    },
    goSearch() {
      this.$router.push('chatSearch');
    }
  },
  mounted() {
    this.loadList(true);
  }
}
</script>

<style lang="less" scoped>
.top{
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  .releaseRecord{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 112px;
    height: 32px;
    background: #FFFFFF;
    border-radius: 23px;
    text-align: center;
    box-sizing: border-box;

    .releaseRecord-icon {
      width: 24px;
      height: 24px;
      margin-top: 8px;
      margin-right: 2px;
    }
    .releaseRecord-text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 15px;
      color: #000000;
    }
  }

  .search{
    flex: 1;
    height: 32px;
    background: #FFFFFF;
    border-radius: 23px;
    opacity: 0.5;
    padding: 6px;
    box-sizing: border-box;
    margin: 0 12px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 15px;
    color: #95A9ED;
    display: flex;
    align-items: center;
    .search-icon{
      height: 24px;
      width: 24px;
      margin-right: 2px;
    }
  }

  .publish{
    width: 62px;
    height: 32px;
    line-height: 32px;
    background: #4765DD;
    border-radius: 23px;
    text-align: center;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 15px;
    color: #FFFFFF;
    font-style: normal;
    text-transform: none;
    box-sizing: border-box;
  }
}

.content {
  flex: 1;
  overflow: auto;
  margin-top: 16px;
  .content-item {
    background: #FFFFFF;
    border-radius: 16px;
    margin: 0 16px 16px;
    padding: 12px;
    box-sizing: border-box;
    .item-header {
      display: flex;
      align-items: flex-start;

      .avatar {
        width: 42px;
        height: 42px;
        margin-right: 12px;
        flex-shrink: 0;
      }

      .user-info {
        display: flex;
        flex-direction: column;
        // align-items: flex-start;
        flex: 1;

        .nickname {
          font-family: PingFang SC, PingFang SC;
          font-weight: 500;
          font-size: 15px;
          color: #4765DD;
          margin-bottom: 4px;
        }

        .desc {
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 12px;
          color: #000000;
          margin-bottom: 3px;
          line-height: 1.5;
          word-break: break-all;
        }
        .more-images{
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
          margin-bottom: 10px;
          .img-box{
            width: 82px;
            height: 82px;
            .more-img-size{
              width: 100%;
              height: 100%;
              border-radius: 8px;
            }
          }
        }
        .main-img {
          width: 134px;
          height: 120px;
          // margin-bottom: 10px;
          .main-img-size{
            width: 100%;
            height: 100%;
            border-radius: 8px;
          }
        }
        .item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          margin-bottom: 10px;

          .time {
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 10px;
            color: #8D8D8D;
          }
          .actions-icon{
            width: 12px;
            height: 10px;
          }
        }

        .like-row {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          flex-wrap: wrap;
          font-size: 12px;
          color: #4765DD;
          font-weight: 500;
          .like-avatar {
            width: 18px;
            height: 18px;
            margin-right: 4px;
            margin-bottom: 4px;
          }
        }
      }
    }
  }
}
.content::-webkit-scrollbar{
  width: 0;
}
.actions-popup {
  position: absolute;
  top: -2px;
  right: calc(100% + 8px); /* 这里改成相对右边按钮左侧向左3px */
  background: #333;
  border-radius: 5px;
  padding: 5px 10px;
  display: flex;
  gap: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  color: white;
  user-select: none;
  white-space: nowrap;
  z-index: 1000;
}

/* 动画：从右往左淡入 */
.slide-left-fade-enter-active,
.slide-left-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-left-fade-enter-from,
.slide-left-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.slide-left-fade-enter-to,
.slide-left-fade-leave-from {
  opacity: 1;
  transform: translateX(0);
}

.action-btn {
  background: none;
  border: none;
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.action-btn:hover {
  background-color: rgba(255, 255, 255, 0.15);
}
.pop-content-password{
    padding: 27px 35px 25px 34px;
    .pop-title-password{
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 17px;
        color: #000000;
        text-align: center;
    }
    .pop-input{
        background: #F2F2F2;
        border-radius: 8px;
        // height: 40px;
        margin: 21px 0 31px;
    }
    .pop-btn-password{
        display: flex;
        justify-content: center;
        .btn-password{
            width: 83px;
            height: 29px;
            line-height: 29px;
            padding: 5px 0 !important;
            border-radius: 6px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            font-size: 15px;
            box-sizing:border-box;
        }
        .cancel{
            margin-right: 17px !important;
            border: 1px solid #D8D8D8;
            color: #000 !important;
        }
        .confirm{
            background: @theme-color1;
            color: #FFF;
            font-weight: 500;
            border: none !important;
        }
    }
}
:deep(.van-popup--center) {
    margin: 0 40px !important;
    width: auto !important;
}
.course-video {
  position: relative;
  display: inline-block;
  overflow: hidden;
  border-radius: 8px;
}

.relative-shadow {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 200px;
  height: 300px;
  z-index: 1;
  border-radius: 8px;
}

.play-icon {
  font-size: 40px;
  color: #fff;
}
</style>