<template>
  <view class="my-dynamics-page">
    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>
      <view class="nav-title">我的动态</view>
      <view class="nav-right"></view>
    </view>

    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
      <view class="user-details">
        <text class="nickname">{{ userInfo.nickname }}</text>
        <text class="dynamic-count">{{ userInfo.dynamicCount }} 动态</text>
      </view>
    </view>

    <!-- 标签页导航 -->
    <view class="tab-nav">
      <view
          class="tab-item"
          :class="{ active: activeTab === 'dynamic' }"
          @click="switchTab('dynamic')"
      >
        <text>动态</text>
      </view>
      <view
          class="tab-item"
          :class="{ active: activeTab === 'interaction' }"
          @click="switchTab('interaction')"
      >
        <text>互动</text>
      </view>
      <view
          class="tab-item"
          :class="{ active: activeTab === 'browse' }"
          @click="switchTab('browse')"
      >
        <text>浏览记录</text>
      </view>
    </view>

    <!-- 互动子标签 -->
    <view class="sub-tab-nav" v-if="activeTab === 'interaction'">
      <view
          class="sub-tab-item"
          :class="{ active: activeSubTab === 'like' }"
          @click="switchSubTab('like')"
      >
        <text>点赞</text>
      </view>
      <view
          class="sub-tab-item"
          :class="{ active: activeSubTab === 'collect' }"
          @click="switchSubTab('collect')"
      >
        <text>收藏</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 动态列表 -->
      <view v-if="activeTab === 'dynamic'" class="dynamic-list">
        <view class="empty-tip" v-if="dynamicList.length === 0">
          <text>暂无动态</text>
        </view>
        <view class="dynamic-item" v-for="item in dynamicList" :key="item.dynamicId" @click="goToDetail(item.dynamicId)">
          <!-- 动态内容 -->
          <view class="dynamic-content">
            <text class="dynamic-text">{{ item.content }}</text>
          </view>
          <!-- 动态图片 -->
          <view class="dynamic-images" v-if="item.mediaUrls">
            <image
                class="dynamic-image"
                v-for="(img, index) in getMediaUrls(item.mediaUrls)"
                :key="index"
                :src="img"
                mode="aspectFill"
                @click.stop="previewImage(getMediaUrls(item.mediaUrls), index)"
            ></image>
          </view>
          <!-- 动态信息 -->
          <view class="dynamic-info">
            <text class="dynamic-time">{{ formatTime(item.createdAt) }}</text>
            <view class="dynamic-stats">
              <text class="stat-item">{{ item.likeCount || 0 }} 赞</text>
              <text class="stat-item">{{ item.commentCount || 0 }} 评论</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 互动列表 -->
      <view v-else-if="activeTab === 'interaction'" class="interaction-list">
        <view class="empty-tip" v-if="interactionList.length === 0">
          <text>暂无互动</text>
        </view>
        <view class="interaction-item" v-for="item in interactionList" :key="item.dynamicId" @click="goToDetail(item.dynamicId)">
          <!-- 用户信息 -->
          <view class="user-info">
            <image class="avatar" :src="getAvatar(item)" mode="aspectFill"></image>
            <view class="user-details">
              <text class="nickname">{{ getNickname(item) }}</text>
            </view>
          </view>
          <!-- 互动内容 -->
          <view class="interaction-content">
            <text class="interaction-text">{{ item.content }}</text>
          </view>
          <!-- 互动图片 -->
          <view class="interaction-images" v-if="item.mediaUrls">
            <image
                class="interaction-image"
                v-for="(img, index) in getMediaUrls(item.mediaUrls)"
                :key="index"
                :src="img"
                mode="aspectFill"
                @click.stop="previewImage(getMediaUrls(item.mediaUrls), index)"
            ></image>
          </view>
          <!-- 互动信息 -->
          <view class="interaction-info">
            <text class="interaction-time">{{ formatTime(item.createdAt) }}</text>
            <view class="interaction-stats">
              <text class="stat-item">{{ item.likeCount || 0 }} 赞</text>
              <text class="stat-item">{{ item.commentCount || 0 }} 评论</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 浏览记录列表 -->
      <view v-else-if="activeTab === 'browse'" class="browse-list">
        <view class="empty-tip" v-if="browseList.length === 0">
          <text>暂无浏览记录</text>
        </view>
        <view class="browse-item" v-for="item in browseList" :key="item.dynamicId" @click="goToDetail(item.dynamicId)">
          <!-- 用户信息 -->
          <view class="user-info">
            <image class="avatar" :src="getAvatar(item)" mode="aspectFill"></image>
            <view class="user-details">
              <text class="nickname">{{ getNickname(item) }}</text>
            </view>
          </view>
          <!-- 浏览内容 -->
          <view class="browse-content">
            <text class="browse-text">{{ item.content }}</text>
          </view>
          <!-- 浏览图片 -->
          <view class="browse-images" v-if="item.mediaUrls">
            <image
                class="browse-image"
                v-for="(img, index) in getMediaUrls(item.mediaUrls)"
                :key="index"
                :src="img"
                mode="aspectFill"
                @click.stop="previewImage(getMediaUrls(item.mediaUrls), index)"
            ></image>
          </view>
          <!-- 浏览信息 -->
          <view class="browse-info">
            <text class="browse-time">{{ formatTime(item.createdAt) }}</text>
            <view class="browse-stats">
              <text class="stat-item">{{ item.likeCount || 0 }} 赞</text>
              <text class="stat-item">{{ item.commentCount || 0 }} 评论</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 发布动态按钮 -->
    <view class="publish-btn" @click="goPublish">
      <text class="publish-icon">+</text>
    </view>
  </view>
</template>

<script>
import api from '../../utils/api.js'

export default {
  data() {
        return {
            // 用户信息
            userInfo: {
                avatar: 'https://via.placeholder.com/100',
                nickname: '用户',
                dynamicCount: 0
            },
            // 活跃标签页
            activeTab: 'dynamic',
            // 活跃子标签（互动下的点赞/收藏）
            activeSubTab: 'like',
            // 动态列表数据
            dynamicList: [],
            // 互动列表数据
            interactionList: [],
            // 浏览记录列表数据
            browseList: [],
            // 默认头像
            defaultAvatar: 'https://via.placeholder.com/100x100.png?text=头像'
        }
    },
  onLoad() {
    // 页面加载时获取用户信息和动态数据
    this.loadUserInfo();
    this.loadDynamicData();
  },
  methods: {
        // 返回上一页
        goBack() {
            uni.navigateBack();
        },
        // 获取头像
        getAvatar(item) {
            if (item && item.user && item.user.avatarUrl) {
                return item.user.avatarUrl;
            }
            return this.defaultAvatar;
        },
        // 获取昵称
        getNickname(item) {
            if (item && item.user && item.user.nickname) {
                return item.user.nickname;
            }
            return '匿名用户';
        },
    // 切换标签页
    switchTab(tab) {
      this.activeTab = tab;
      // 根据标签页加载对应数据
      if (tab === 'dynamic') {
        this.loadDynamicData();
      } else if (tab === 'interaction') {
        this.loadInteractionData();
      } else if (tab === 'browse') {
        this.loadBrowseData();
      }
    },
    // 切换互动子标签
    switchSubTab(subTab) {
      this.activeSubTab = subTab;
      // 根据子标签加载对应数据
      this.loadInteractionData();
    },
    // 加载用户信息
    loadUserInfo() {
      // 从本地存储获取用户信息
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.userInfo = {
          avatar: userInfo.avatarUrl || userInfo.avatar || 'https://via.placeholder.com/100',
          nickname: userInfo.nickname || '用户',
          dynamicCount: 0 // 后续从接口获取
        };
        // 加载用户动态数量
        this.loadUserDynamicCount();
      }
    },
    // 加载用户动态数量
    loadUserDynamicCount() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.userId) {
        // 获取用户动态数量
        api.dynamic.getUserDynamics(userInfo.userId, { pageNum: 1, pageSize: 1 }).then(res => {
          if (res && res.total) {
            this.userInfo.dynamicCount = res.total;
          }
        }).catch(err => {
          console.error('获取用户动态数量失败:', err);
        });
      }
    },
    // 加载动态数据
    loadDynamicData() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.userId) {
        // 获取用户发布的动态列表
        api.dynamic.getUserDynamics(userInfo.userId, {
          pageNum: 1,
          pageSize: 10
        }).then(res => {
          if (res && res.records) {
            this.dynamicList = res.records;
          }
        }).catch(err => {
          console.error('获取用户动态列表失败:', err);
        });
      }
    },
    // 加载互动数据
    loadInteractionData() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.userId) {
        if (this.activeSubTab === 'like') {
          // 获取用户点赞的动态列表
          api.dynamic.getLikedList(userInfo.userId, 1, 10).then(res => {
            if (res && res.records) {
              this.interactionList = res.records;
            }
          }).catch(err => {
            console.error('获取用户点赞列表失败:', err);
          });
        } else if (this.activeSubTab === 'collect') {
          // 获取用户收藏的动态列表
          api.dynamic.getFavoritesList(userInfo.userId, 1, 10).then(res => {
            if (res && res.records) {
              this.interactionList = res.records;
            }
          }).catch(err => {
            console.error('获取用户收藏列表失败:', err);
          });
        }
      }
    },
    // 加载浏览记录数据
    loadBrowseData() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo && userInfo.userId) {
        // 获取用户浏览记录列表
        api.dynamic.getBrowseHistoryList(userInfo.userId, 1, 10).then(res => {
          if (res && res.records) {
            this.browseList = res.records;
          }
        }).catch(err => {
          console.error('获取用户浏览记录失败:', err);
        });
      }
    },
    // 跳转到发布动态页面
    goPublish() {
      uni.navigateTo({
        url: '/pages/plaza/publish'
      });
    },
    // 跳转到动态详情页
    goToDetail(dynamicId) {
      uni.navigateTo({
        url: `/pages/plaza/detail?id=${dynamicId}`
      });
    },
    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;
      const minute = 60 * 1000;
      const hour = minute * 60;
      const day = hour * 24;
      const month = day * 30;
      const year = day * 365;
      
      if (diff < minute) {
        return '刚刚';
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前';
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前';
      } else if (diff < month) {
        return Math.floor(diff / day) + '天前';
      } else if (diff < year) {
        return Math.floor(diff / month) + '个月前';
      } else {
        return Math.floor(diff / year) + '年前';
      }
    },
    // 处理媒体URL，支持数组、JSON字符串、逗号分隔等多种格式
    getMediaUrls(mediaUrls) {
      if (!mediaUrls) return [];
      
      const isLikelyImage = (u) => {
        if (typeof u !== 'string' || !u.trim()) return false;
        const url = u.trim();
        const hasExt = /(\.png|\.jpg|\.jpeg|\.gif|\.webp|\.bmp)(\?|$)/i.test(url);
        const isHttp = /^https?:\/\//i.test(url);
        return hasExt || isHttp;
      };
      
      try {
        if (Array.isArray(mediaUrls)) {
          return mediaUrls.filter(isLikelyImage);
        }
        if (typeof mediaUrls === 'string') {
          const s = mediaUrls.trim();
          // JSON数组字符串: ["url1", "url2"]
          if (s.startsWith('[')) {
            const arr = JSON.parse(s);
            return Array.isArray(arr) ? arr.filter(isLikelyImage) : [];
          }
          // 逗号分隔或带引号
          return s.split(',')
                  .map(x => x.trim().replace(/^\[|\]$/g, '').replace(/^['"]|['"]$/g, ''))
                  .filter(isLikelyImage);
        }
      } catch (e) {
        // ignore parse error
        console.error('解析媒体URL失败:', e);
      }
      return [];
    },
    // 预览图片
    previewImage(urls, current) {
      uni.previewImage({
        urls: urls,
        current: current,
        longPressActions: {
          itemList: ['保存图片'],
          success: function(data) {
            console.log('长按图片操作结果:', data);
          },
          fail: function(err) {
            console.error('长按图片操作失败:', err);
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.my-dynamics-page {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 100rpx;
}

/* 顶部导航栏 */
.top-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 40rpx 30rpx 20rpx;
  background: #FFFFFF;
  position: relative;
  z-index: 10;

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .back-icon {
      font-size: 48rpx;
      color: #333333;
      font-weight: bold;
    }
  }

  .nav-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }

  .nav-right {
    width: 60rpx;
  }
}

/* 用户信息区域 */
.user-info-section {
  display: flex;
  align-items: center;
  padding: 30rpx;
  background: #FFFFFF;
  margin-bottom: 20rpx;

  .avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-right: 20rpx;
    background-color: #E0E0E0;
  }

  .user-details {
    display: flex;
    flex-direction: column;
    justify-content: center;

    .nickname {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 8rpx;
    }

    .dynamic-count {
      font-size: 24rpx;
      color: #999999;
    }
  }
}

/* 标签页导航 */
.tab-nav {
  display: flex;
  background: #FFFFFF;
  border-bottom: 2rpx solid #F0F0F0;
  margin-bottom: 20rpx;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: 30rpx 0;
    position: relative;

    text {
      font-size: 30rpx;
      color: #666666;
    }

    &.active {
      text {
        color: #E91E63;
        font-weight: bold;
      }

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background: #E91E63;
        border-radius: 3rpx;
      }
    }
  }
}

/* 互动子标签导航 */
.sub-tab-nav {
  display: flex;
  background: #FFFFFF;
  padding: 0 30rpx;
  margin-bottom: 20rpx;

  .sub-tab-item {
    padding: 20rpx 30rpx;
    margin-right: 40rpx;

    text {
      font-size: 26rpx;
      color: #999999;
    }

    &.active {
      text {
        color: #E91E63;
        font-weight: bold;
      }
    }
  }
}

/* 内容区域 */
.content-area {
  padding: 0 30rpx;
}

/* 列表通用样式 */
.dynamic-list,
.interaction-list,
.browse-list {
  background: #FFFFFF;
  border-radius: 12rpx;
  overflow: hidden;
}

.dynamic-item,
.interaction-item,
.browse-item {
  padding: 30rpx;
  border-bottom: 2rpx solid #F5F5F5;

  &:last-child {
    border-bottom: none;
  }
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;

  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 40rpx;
    margin-right: 20rpx;
    background-color: #E0E0E0;
  }

  .user-details {
    display: flex;
    flex-direction: column;

    .nickname {
      font-size: 28rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 4rpx;
    }
  }
}

/* 内容文本 */
.dynamic-content,
.interaction-content,
.browse-content {
  margin-bottom: 20rpx;

  .dynamic-text,
  .interaction-text,
  .browse-text {
    font-size: 28rpx;
    color: #333333;
    line-height: 44rpx;
  }
}

/* 图片列表 */
.dynamic-images,
.interaction-images,
.browse-images {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
  margin-bottom: 20rpx;

  .dynamic-image,
  .interaction-image,
  .browse-image {
    width: calc((100% - 30rpx) / 3);
    height: 200rpx;
    border-radius: 8rpx;
    background-color: #E0E0E0;
  }
}

/* 信息栏 */
.dynamic-info,
.interaction-info,
.browse-info {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .dynamic-time,
  .interaction-time,
  .browse-time {
    font-size: 22rpx;
    color: #999999;
  }

  .dynamic-stats,
  .interaction-stats,
  .browse-stats {
    display: flex;
    align-items: center;

    .stat-item {
      font-size: 22rpx;
      color: #999999;
      margin-left: 30rpx;
    }
  }
}

/* 空状态提示 */
.empty-tip {
  padding: 100rpx 0;
  text-align: center;

  text {
    font-size: 28rpx;
    color: #999999;
  }
}

/* 发布动态按钮 */
.publish-btn {
  position: fixed;
  bottom: 80rpx;
  right: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: #E91E63;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 20rpx rgba(233, 30, 99, 0.3);
  z-index: 999;

  .publish-icon {
    font-size: 60rpx;
    color: #FFFFFF;
    font-weight: bold;
    line-height: 1;
  }
}

/* 页面背景色 */
.my-dynamics-page {
  background-color: #F5F5F5;
}
</style>