// 个人资料页面逻辑
const app = getApp();
const config = require('../../../config/config.js');
const apiClient = require('../../../utils/api-client.js');
const authManager = require('../../../utils/auth.js');
const imageCacheManager = require('../../../utils/image-cache-manager.js');
const nimUserManager = require('../../../utils/nim-user-manager.js');
const { calculateConstellationFromBirthday } = require('../../../utils/formatDate.js');
const cosManager = require('../../../utils/cos-manager.js');


Page({
  data: {
    userInfo: null,
    stats: {
      friendsCount: 0,
      postsCount: 0,
      visitorsCount: 0,
      likesCount: 0,
      groupsCount: 0
    },
    newMomentsCount: 0,
    fileSize: '0MB',
    cacheSize: '0MB',
    appVersion: '',
    showQRModal: false,

    // 系统适配信息
    systemInfo: {},
    statusBarHeight: 0,
    menuButtonHeight: 0,
    menuButtonTop: 0,
    navBarHeight: 0,
    windowHeight: 0,
    safeAreaBottom: 0,
    bottomSpaceHeight: 120,

    // 调试信息
    debugInfo: {
      hasGlobalUserInfo: false,
      hasToken: false,
      tokenLength: 0,
      hasLocalStorage: false
    },

    isLoggedIn: false,

    dynamicList: [],        // 动态列表
    totalDynamicCount: 0,   // 动态总数量
    currentPage: 1,         // 当前页码
    pageSize: 5,            // 每页加载数量
    isLoadingMore: false,   // 是否正在加载下一页
    hasMoreData: true,      // 是否还有更多数据
    emptyPageCount: 0,
    postContent: '',
    // 评论相关
    commentInputValue: '',     // 评论输入内容
    submittingComment: false,  // 是否正在提交评论，防止重复点击
    showCommentInput: {},      // 控制每个动态的评论输入框显示状态 {feedIndex: true/false}
    // 回复相关
    replyingCommentId: null,  // 当前正在回复的评论ID
    replyingCommentIndex: null, // 当前正在回复的评论索引
    replyingToCommentId: null, // 回复的目标评论ID（二级评论的父评论）
    replyInputValue: '',      // 回复输入内容
    showReplyInput: {},       // 控制每个评论的回复输入框显示状态
    submittingReply: false,  // 是否正在提交回复，防止重复点击

    // 自定义功能入口（6宫格，图片在上、文字在下）
    selfTools: [
      { 
        icon: '/images/self/bag.png', 
        label: '设置',
        url: '/subpackages/settings/settingss/settingss'
      },
      { 
        icon: '/images/self/store.png', 
        label: '收藏',
        url: '' // 待配置收藏页面路径
      },
      // { icon: '/images/self/picture.png', label: '相册', url: '' },
      // { icon: '/images/self/cycle.png', label: '圈子', url: '' },
      // { icon: '/images/self/game.png', label: '游戏', url: '' },
      // { icon: '/images/self/group-shop.png', label: '团购', url: '' }
    ],

    // VIP会员套餐（与后端商品列表保持一致）
    showVipModal: false,
    vipPackages: [
      {
        id: 1,
        name: '普通会员',
        duration: '30天',
        price: 29.9,
        originalPrice: 59.9,
        discount: '月度特惠',
        benefits: ['去广告', '专属标识', '优先匹配', '专属客服'],
        hot: false
      },
      {
        id: 2,
        name: '高级会员',
        duration: '90天',
        price: 49.9,
        originalPrice: 99.9,
        discount: '季度优惠',
        benefits: ['普通会员权益', '专属表情', '高级筛选', '聊天置顶'],
        hot: true
      },
      {
        id: 3,
        name: 'VIP会员',
        duration: '365天',
        price: 99.9,
        originalPrice: 199.9,
        discount: '年度最优惠',
        benefits: ['高级会员权益', '无限查看', '访客记录', '专属勋章'],
        hot: false
      },
      {
        id: 4,
        name: '终身会员',
        duration: '终身',
        price: 999,
        originalPrice: 1999,
        discount: '终身尊享',
        benefits: ['VIP会员权益', '终身免费', 'VIP专区', '尊贵标识'],
        hot: false
      },
      {
        id: 5,
        name: '测试支付',
        duration: '1天',
        price: 0.01,
        originalPrice: 0.01,
        discount: '测试专用',
        benefits: ['仅用于测试支付功能'],
        hot: false,
        isTest: true // 标记为测试套餐
      }
    ],
    selectedVipPackage: null,
  },

  onAvatarUpdated(payload = {}) {
    const displayUrl = payload.cachedUrl || payload.avatarUrl || payload.serverUrl || '';
    const baseInfo = this.data.userInfo || {};
    // payload.userInfo 可能是 { user: {...} } 结构，需要提取 user
    const latestInfo = payload.userInfo?.user ? Object.assign({}, payload.userInfo.user) : (payload.userInfo ? Object.assign({}, payload.userInfo) : {});
    const mergedInfo = Object.assign({}, baseInfo, latestInfo);

    // 确保保留 customId
    if (baseInfo.customId && !mergedInfo.customId) {
      mergedInfo.customId = baseInfo.customId;
    }

    if (displayUrl) {
      mergedInfo.avatar = displayUrl;
      mergedInfo.avatarUrl = displayUrl;
    }

    // 更新页面显示的头像
    if (Object.keys(mergedInfo).length > 0) {
      this.setData({ 
        userInfo: mergedInfo,
        selfAvatar: displayUrl || mergedInfo.avatar || mergedInfo.avatarUrl
      });
    } else if (displayUrl) {
      // 即使没有完整的用户信息，也要更新头像显示
      this.setData({ 
        selfAvatar: displayUrl
      });
    }
  },

  // 页面加载
  onLoad: async function () {

    this.initSystemInfo();
    this.loadUserData();
    this.getDynamicList();
    const appData = await apiClient.getUserInfo();
    console.log('appData -----',appData)
    if(appData.code === 0){
         const   nickname =    appData.data.nickname
         const avatar = appData.data.avatar
        //  wx.setStorageSync('userInfo', appData.data);
         app.globalData.userInfo.user = appData.data;
       
         this.setData({
          nickname:nickname,
          selfAvatar:avatar
         })
    }
  },


  // 核心方法：同步全局数据到当前页面
  syncGlobalUserInfo(avatarUrl) {
    this.setData({
      selfAvatar:avatarUrl
    });
  },


  // 下拉刷新
  onRefresh: function() {
    this.setData({
      refreshing: true,
      currentPage: 1,
      hasMoreData: true
    }, () => {
      this.getDynamicList();
    });
  },

  async preprocessDynamicImages(dynamics) {
    try {
      const processedDynamics = [];

      for (const dynamic of dynamics) {
        const processedDynamic = { ...dynamic };

        if (dynamic.media && Array.isArray(dynamic.media)) {
          processedDynamic.media = [];

          for (const mediaItem of dynamic.media) {
            const processedMediaItem = { ...mediaItem };

            const imageUrl = mediaItem.thumbnailUrl || mediaItem.url || (mediaItem.sizes && mediaItem.sizes.original) || '';

            if (imageUrl) {
              try {
                const cachedImageUrl = await imageCacheManager.cacheImage(imageUrl, 'feed_image');

                if (mediaItem.thumbnailUrl) {
                  processedMediaItem.thumbnailUrl = cachedImageUrl;
                }
                if (mediaItem.url) {
                  processedMediaItem.url = cachedImageUrl;
                }
                if (mediaItem.sizes && mediaItem.sizes.original) {
                  processedMediaItem.sizes.original = cachedImageUrl;
                }
              } catch (error) {
                console.error('处理动态图片失败:', imageUrl, error);
                try {
                  // 使用文件顶部已引入的 config
                  if (imageUrl && imageUrl.startsWith('/')) {
                    const fullUrl = `${config.api.baseUrl}${imageUrl}`;
                    if (mediaItem.thumbnailUrl) {
                      processedMediaItem.thumbnailUrl = fullUrl;
                    }
                    if (mediaItem.url) {
                      processedMediaItem.url = fullUrl;
                    }
                    if (mediaItem.sizes && mediaItem.sizes.original) {
                      processedMediaItem.sizes.original = fullUrl;
                    }
                  } else if (imageUrl && !imageUrl.startsWith('http://') && !imageUrl.startsWith('https://')) {
                    const fullUrl = `https://${imageUrl}`;
                    if (mediaItem.thumbnailUrl) {
                      processedMediaItem.thumbnailUrl = fullUrl;
                    }
                    if (mediaItem.url) {
                      processedMediaItem.url = fullUrl;
                    }
                    if (mediaItem.sizes && mediaItem.sizes.original) {
                      processedMediaItem.sizes.original = fullUrl;
                    }
                  }
                } catch (urlError) {
                  console.error('构建完整URL失败:', urlError);
                }
              }
            }

            processedDynamic.media.push(processedMediaItem);
          }
        }

        processedDynamics.push(processedDynamic);
      }

      return processedDynamics;
    } catch (error) {
      console.error('预处理动态图片失败:', error);
      return dynamics;
    }
  },

  // 获取动态列表
  getDynamicList() {
    const { currentPage, pageSize, userInfo } = this.data;
    this.setData({ isLoadingMore: true });

    if (!userInfo) {
      console.error('用户信息无效，无法获取个人动态');
      this.setData({ isLoadingMore: false });
      return;
    }

    wx.request({
      url: `${config.api.baseUrl}/api/v1/feeds/my`,
      method: 'GET',
      data: {
        page: currentPage,
        pageSize: pageSize
      },
      header: {
        'Authorization': `Bearer ${apiClient.getToken() || ''}`
      },
      success: async (res) => {

        // 🔥 统一处理401 - 使用apiClient的统一处理
        if (apiClient.is401Error(res)) {
          const app = getApp();
          const isLoggedIn = app?.globalData?.isLoggedIn || false;
          apiClient.handle401Error(isLoggedIn);
          return;
        }

        if (res.data.code === 200) {
          const response = res.data.data;
          const newDynamics = response.feeds || [];

          // 格式化时间
          let processedDynamics = newDynamics.map(dynamic => {
            let formattedTime = '未知时间';
            try {
              formattedTime = this.formatDynamicTime(dynamic.createdAt || dynamic.createTime || '');
            } catch (error) {
              console.error('时间格式化失败:', error);
            }

            const uniqueId = dynamic.id || dynamic.uuid || dynamic.dynamicId || dynamic.feedId || `dynamic_${Date.now()}_${Math.random()}`;

            // 处理互动数据（点赞数和评论数）
            const interactions = dynamic.interactions || {};
            const isLiked = dynamic.isLiked || false;
            
            // 处理评论数据，格式化评论时间，组织嵌套结构
            let processedComments = [];
            if (dynamic.comments && Array.isArray(dynamic.comments) && dynamic.comments.length > 0) {
              // 获取当前用户ID，用于判断是否是自己的评论
              const app = getApp();
              const currentUser = app.globalData.userInfo?.user || {};
              const currentUserId = currentUser.id || currentUser.userId || currentUser.customId || '';
              
              // 分离一级评论和回复
              const topLevelComments = [];
              const repliesList = [];
              
              dynamic.comments.forEach((item, idx) => {
                const itemUserId = item.userId || item.user?.id || item.user?.userId || '';
                const isOwn = currentUserId && itemUserId && currentUserId.toString() === itemUserId.toString();
                
                const user = item.user || {};
                if (!user.nickname && item.userName) {
                  user.nickname = item.userName;
                }
                if (!user.nickname) {
                  user.nickname = '未知用户';
                }
                
                if (!item.replyToId) {
                  topLevelComments.push({
                    ...item,
                    id: item.id || item.uuid || `comment_${feedIdx}_${idx}`,
                    formattedTime: item.formattedTime || this.formatCommentTime(item.createdAt || ''),
                    replies: [],
                    visibleReplyCount: 5,
                    isOwn: isOwn,
                    user: user
                  });
                } else {
                  repliesList.push({
                    ...item,
                    id: item.id || item.uuid || `reply_${feedIdx}_${idx}`,
                    formattedTime: item.formattedTime || this.formatCommentTime(item.createdAt || ''),
                    isOwn: isOwn,
                    user: user
                  });
                }
              });
              
              // 将回复组织到对应的一级评论下
              let remainingReplies = [...repliesList];
              let maxIterations = 10;
              let iteration = 0;
              
              while (remainingReplies.length > 0 && iteration < maxIterations) {
                iteration++;
                const newRemainingReplies = [];
                
                remainingReplies.forEach(reply => {
                  const parentComment = topLevelComments.find(c => c.id === reply.replyToId);
                  if (parentComment) {
                    if (!parentComment.replies) {
                      parentComment.replies = [];
                    }
                    if (parentComment.user) {
                      reply.replyToUser = parentComment.user;
                    }
                    parentComment.replies.push(reply);
                  } else {
                    let found = false;
                    for (let comment of topLevelComments) {
                      if (comment.replies && comment.replies.length > 0) {
                        const targetReply = comment.replies.find(r => r.id === reply.replyToId);
                        if (targetReply) {
                          if (targetReply.user) {
                            reply.replyToUser = targetReply.user;
                          }
                          const targetIndex = comment.replies.findIndex(r => r.id === reply.replyToId);
                          if (targetIndex >= 0) {
                            comment.replies.splice(targetIndex + 1, 0, reply);
                          } else {
                            comment.replies.push(reply);
                          }
                          found = true;
                          break;
                        }
                      }
                    }
                    if (!found) {
                      newRemainingReplies.push(reply);
                    }
                  }
                });
                
                remainingReplies = newRemainingReplies;
                if (remainingReplies.length === repliesList.length && iteration > 1) {
                  break;
                }
              }
              
              // 对一级评论和回复按时间倒序排序
              topLevelComments.sort((a, b) => {
                const timeA = new Date(a.createdAt || 0).getTime();
                const timeB = new Date(b.createdAt || 0).getTime();
                return timeB - timeA;
              });
              
              topLevelComments.forEach(comment => {
                if (comment.replies && comment.replies.length > 0) {
                  comment.replies.sort((a, b) => {
                    const timeA = new Date(a.createdAt || 0).getTime();
                    const timeB = new Date(b.createdAt || 0).getTime();
                    return timeB - timeA;
                  });
                }
              });
              
              processedComments = topLevelComments;
            }

            return {
              ...dynamic,
              id: uniqueId,
              formattedTime: formattedTime,
              interactions: {
                likeCount: interactions.likeCount || 0,
                commentCount: interactions.commentCount || 0
              },
              isLiked: isLiked,
              comments: processedComments || [],
              visibleCommentCount: dynamic.visibleCommentCount || 20
            };
          });

          try {

            processedDynamics = await this.preprocessDynamicImages(processedDynamics);

          } catch (error) {
            console.error('预处理动态图片时出现异常:', error);
          }

          // 去重处理
          if (currentPage !== 1 && this.data.dynamicList && this.data.dynamicList.length > 0) {
            const existingIds = new Set(this.data.dynamicList.map(item => item.id));
            processedDynamics = processedDynamics.filter(dynamic => !existingIds.has(dynamic.id));
          }

          const totalCount = response.total || 0;
          const formattedCount = this.formatDynamicCount(totalCount);

          let updatedEmptyPageCount = this.data.emptyPageCount;

          if (processedDynamics.length === 0 && currentPage > 1) {
            updatedEmptyPageCount += 1;
          } else if (processedDynamics.length > 0) {
            updatedEmptyPageCount = 0;
          }

          const hasMoreData = (
            (totalCount === 0 || (this.data.dynamicList.length + processedDynamics.length) < totalCount) ||
            (currentPage * pageSize < totalCount) ||
            response.hasMore
          ) && updatedEmptyPageCount < 3;


          this.setData({
            dynamicList: currentPage === 1 ? processedDynamics : [...this.data.dynamicList, ...processedDynamics],
            totalDynamicCount: totalCount,
            formattedDynamicCount: formattedCount,
            hasMoreData: hasMoreData,
            emptyPageCount: updatedEmptyPageCount,
            refreshing: false,
            isLoadingMore: false
          });
        } else {
          wx.showToast({ title: res.data.msg || '获取动态失败', icon: 'none' });
          this.setData({
            isLoadingMore: false,
            refreshing: false
          });
        }
      },
      fail: (err) => {
        console.error('获取动态失败：', err);
        wx.showToast({ title: '网络异常，获取动态失败', icon: 'none' });
        this.setData({
          isLoadingMore: false,
          refreshing: false
        });
      }
    });
  },

  // 滑动到底部加载下一页
  loadMoreDynamics() {
    const { currentPage, hasMoreData, isLoadingMore, totalDynamicCount, pageSize, emptyPageCount } = this.data;

    // 计算当前已加载数量
    const loadedCount = this.data.dynamicList.length;

    if (isLoadingMore) {

      return;
    }

    if (emptyPageCount >= 3) {
      this.setData({ hasMoreData: false });
      return;
    }

    const shouldLoadMore =
      hasMoreData ||
      (totalDynamicCount === 0 || loadedCount < totalDynamicCount) ||
      (currentPage * pageSize < totalDynamicCount);

    if (!shouldLoadMore) {

      return;
    }

    const nextPage = currentPage + 1;
    this.setData({
      currentPage: nextPage,
      isLoadingMore: true
    }, () => {
      this.getDynamicList();
    });
  },

  // 格式化动态数量
  formatDynamicCount(count) {
    const num = count || 0;
    return num >= 100 ? "100+" : num.toString();
  },

  // 格式化动态时间
  formatDynamicTime(createTime) {
    const now = new Date();
    const dynamicTime = new Date(createTime);
    const timeDiff = (now.getTime() - dynamicTime.getTime()) / 1000;

    // 小于5分钟：显示"刚刚"
    if (timeDiff < 5 * 60) {
      return { date: '刚刚', year: '' };
    }

    // 大于5分钟：处理日期格式
    const padZero = (num) => num.toString().padStart(2, "0");
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    
    const day = padZero(dynamicTime.getDate());
    const month = months[dynamicTime.getMonth()];
    const year = dynamicTime.getFullYear();

    // 返回日期和年份
    return { date: `${day} ${month}`, year: year };
  },

  // 预览动态图片
  previewDynamicImage(e) {
    try {
      const { index, feedIndex } = e.currentTarget.dataset;
      const dynamic = this.data.dynamicList[feedIndex];
      
      if (!dynamic || !dynamic.media || !dynamic.media.length) {
        console.error('没有找到动态数据');
        return;
      }

      // 优先使用原图URL，确保预览完整清晰的图片
      const imageUrls = dynamic.media
        .filter(item => item.type === 'image' || !item.type) // 过滤出图片
        .map(item => {
          // 优先使用 originalUrl，其次使用 url，最后使用 thumbnailUrl
          return item.originalUrl || item.url || item.thumbnailUrl || '';
        })
        .filter(url => url); // 过滤掉空URL

      if (!imageUrls.length) {
        console.error('没有有效的图片URL');
        wx.showToast({
          title: '图片加载失败',
          icon: 'none'
        });
        return;
      }

      // 确定当前显示的图片索引
      const currentIndex = index !== undefined ? parseInt(index) : 0;
      const currentUrl = imageUrls[currentIndex] || imageUrls[0];

      // 调用微信小程序的图片预览API
      wx.previewImage({
        current: currentUrl, // 当前显示图片的URL（使用原图）
        urls: imageUrls,     // 需要预览的图片URL列表（使用原图）
        fail: (err) => {
          console.error('图片预览失败:', err);
          wx.showToast({
            title: '预览图片失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error('预览动态图片过程中出错:', error);
      wx.showToast({
        title: '预览图片失败',
        icon: 'none'
      });
    }
  },


  // 页面显示
  onShow: function () {
    // 设置tabBar选中状态为"我的"（索引3）
    try {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({ selected: 3 });
      }
    } catch (error) {
      console.warn('设置tabBar选中状态失败:', error);
    }

    // 从头像编辑页面返回时，刷新头像显示
    const globalUserInfo = app.globalData.userInfo;
    if (globalUserInfo && globalUserInfo.user && globalUserInfo.user.avatar) {
      const avatarUrl = globalUserInfo.user.avatar;
      // 如果当前显示的头像与全局不一致，更新显示
      if (this.data.selfAvatar !== avatarUrl) {
        this.setData({
          selfAvatar: avatarUrl
        });
        // 同时更新用户信息中的头像
        if (this.data.userInfo) {
          this.setData({
            userInfo: {
              ...this.data.userInfo,
              avatar: avatarUrl,
              avatarUrl: avatarUrl
            }
          });
        }
      }
    }
  },


  // 刷新用户信息
  refreshUserInfo() {
    const userInfo = app.globalData.userInfo.user;
    if (userInfo) {
      // 将家乡数组转换为字符串
      let hometownText = '';
      if (userInfo.hometown) {
        if (Array.isArray(userInfo.hometown)) {
          hometownText = userInfo.hometown.filter(item => item).join(' ');
        } else if (typeof userInfo.hometown === 'string') {
          hometownText = userInfo.hometown;
        }
      }else if(userInfo.locationInfo){
        hometownText = userInfo.locationInfo.district + userInfo.locationInfo.city
      }
      this.setData({ 
        userInfo,
        hometownText
      });
    }
  },

  // 加载用户统计
  async loadUserStats() {
    try {
      const response = await this.mockLoadStats();

      if (response && response.code === 0) {
        this.setData({
          stats: response.data.stats,
          newMomentsCount: response.data.newMomentsCount || 0,
          fileSize: response.data.fileSize || '0MB',
          cacheSize: response.data.cacheSize || '0MB'
        });
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  },

  // 模拟加载统计API
  async mockLoadStats() {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 300));

    return {
      code: 0,
      message: '成功',
      data: {
        stats: {
          friendsCount: 42,
          postsCount: 18,
          visitorsCount: 156,
          likesCount: 89,
          groupsCount: 5
        },
        newMomentsCount: 2,
        fileSize: '125MB',
        cacheSize: '32MB'
      }
    };
  },

  // 更换头像
  changeAvatar() {
    let that = this;
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择'],
      success: (res) => {
        const sourceType = res.tapIndex === 0 ? ['camera'] : ['album'];

        wx.chooseImage({
          count: 1,
          sizeType: ['original'], // 使用原图，编辑后再压缩
          sourceType: sourceType,
          success: (res) => {
            // 跳转到头像编辑页面
            const imagePath = encodeURIComponent(res.tempFilePaths[0]);
            wx.navigateTo({
              url: `/subpackages/profile/avatar-edit/avatar-edit?imagePath=${imagePath}`,
              fail: (err) => {
                console.error('跳转编辑页面失败:', err);
                wx.showToast({
                  title: '打开编辑页面失败',
                  icon: 'none'
                });
              }
            });
          },
          fail: (error) => {
            console.error('选择头像失败:', error);
            wx.showToast({
              title: '选择头像失败',
              icon: 'none'
            });
          }
        });
      }
    });
  },


/**
 * 头像专用压缩：1M内→20K内，1M以上→50K内（强制达标）
 * @param {string} tempFilePath - 微信临时文件路径
 * @returns {Promise<string>} 压缩后的临时文件路径
 */

compressImage(tempFilePath) {
  return new Promise((resolve, reject) => {
    // 步骤1：获取文件大小
    wx.getFileInfo({
      filePath: tempFilePath,
      success: (fileInfo) => {
        const fileSize = fileInfo.size;
        const MAX_SIZE_LARGE = 2 * 1024 * 1024; // 2M临界值
        const TARGET_SMALL = 20 * 1024;    // 一般目标：20K
        const TARGET_LARGE = 50 * 1024;    // 2M以上目标：50K
        
        // 根据文件大小确定目标大小
        const targetSize = fileSize > MAX_SIZE_LARGE ? TARGET_LARGE : TARGET_SMALL;

        // 步骤2：获取图片信息并设置压缩参数
        wx.getImageInfo({
          src: tempFilePath,
          success: (imgInfo) => {
            let { width, height } = imgInfo;
            
            // 👉 优化1：头像专用尺寸调整（更激进）
            // 头像通常显示较小，最大边长设为150px足够清晰[1,3](@ref)
            const MAX_DIMENSION = 150;
            if (width > MAX_DIMENSION || height > MAX_DIMENSION) {
              if (width > height) {
                height = Math.floor(height * MAX_DIMENSION / width);
                width = MAX_DIMENSION;
              } else {
                width = Math.floor(width * MAX_DIMENSION / height);
                height = MAX_DIMENSION;
              }
            }

            // 👉 优化2：更精细的质量参数设置
            let quality = this.calculateQuality(fileSize, targetSize);
            
            // 步骤3：执行压缩
            this.executeCompression(tempFilePath, width, height, quality, targetSize, resolve, reject);
          },
          fail: (err) => reject(err)
        });
      },
      fail: (err) => reject(err)
    });
  });
},

// 辅助函数：计算合适的质量参数
calculateQuality(fileSize, targetSize) {
  // 基础质量设置[2,5](@ref)
  let quality;
  
  if (targetSize <= 20 * 1024) {
    // 目标20K以下的配置
    if (fileSize > 1024 * 1024) { // 原图>1M
      quality = 30;
    } else if (fileSize > 500 * 1024) { // 原图>500K
      quality = 40;
    } else if (fileSize > 100 * 1024) { // 原图>100K
      quality = 50;
    } else {
      quality = 60; // 原图已较小，轻度压缩
    }
  } else {
    // 目标50K以下的配置（针对大原图）
    if (fileSize > 3 * 1024 * 1024) { // 原图>3M
      quality = 40;
    } else if (fileSize > 2 * 1024 * 1024) { // 原图>2M
      quality = 50;
    } else {
      quality = 60;
    }
  }
  
  return quality;
},

// 辅助函数：执行压缩（支持多次压缩）
executeCompression(srcPath, width, height, initialQuality, targetSize, resolve, reject) {
  const compressRecursively = (currentPath, currentQuality, attempt = 0) => {
    if (attempt >= 3) { // 最多尝试3次
      resolve(currentPath);
      return;
    }
    
    wx.compressImage({
      src: currentPath,
      quality: currentQuality,
      success: (compressRes) => {
        // 检查压缩后大小
        wx.getFileInfo({
          filePath: compressRes.tempFilePath,
          success: (fileInfo) => {
            if (fileInfo.size <= targetSize || currentQuality <= 20) {
              // 已达到目标或质量已很低，停止压缩
              resolve(compressRes.tempFilePath);
            } else {
              // 未达到目标，继续压缩（更激进地降低质量）
              const newQuality = Math.max(20, currentQuality - 15);
              compressRecursively(compressRes.tempFilePath, newQuality, attempt + 1);
            }
          },
          fail: (err) => reject(err)
        });
      },
      fail: (err) => reject(err)
    });
  };
  
  // 开始第一次压缩
  compressRecursively(srcPath, initialQuality);
},

// Add this temporary debug method
async debugServerAvatar() {
    try {

      console.log('🔍 Current global avatar:', getApp().getCurrentAvatarUrl());

      // Fetch fresh from server
      const response = await apiClient.getUserInfo();

      wx.showModal({
        title: 'Avatar Debug',
        content: `Client: ${this.data.userInfo?.avatar}\n\nServer DB: ${response.data?.avatar}`,
        showCancel: false
      });
    } catch (error) {
      console.error('Debug failed:', error);
    }
  },


  // 上传头像
  async uploadAvatar(tempFilePath) {
    wx.showLoading({ title: '上传中...' });
    try {
      // const uploadResult = await apiClient.uploadAvatar(tempFilePath);
      // if (!uploadResult?.success) {
      //   throw new Error(uploadResult?.message || '上传失败');
      // }

      const uploadResult = await cosManager.upload(tempFilePath, {
        fileType: 'avatar',
        enableDedup: true, // 启用去重，节省存储空间
        onProgress: (percent) => {
          console.log('上传进度:', percent + '%');
        },
        enableCompress: false,
        compressOptions: {
          maxWidth: 400,
          maxHeight: 400,
          targetSize: 30 * 1024
        }
      });

         // 检查上传结果
         if (!uploadResult || !uploadResult.success) {
          throw new Error(uploadResult?.error || '上传失败');
        }

      // 获取上传后的文件URL
      const avatarUrl = uploadResult.fileUrl;

      if (!avatarUrl) {
        console.error('上传返回数据:', uploadResult);
        throw new Error('上传失败：未获取到文件URL');
      }
      app.globalData.userInfo.user.avatar = avatarUrl;
       // 立即同步头像到 NIM
       try {
        await nimUserManager.updateSelfUserInfo({
          avatar: avatarUrl
        });
        console.log('✅ 头像已同步到 NIM');
      } catch (nimError) {
        console.error('⚠️ 同步头像到 NIM 失败:', nimError);
        // 不影响主流程，静默失败
      }

      // 立即同步头像到业务后端
      try {
        await apiClient.updateUserProfile({ avatar: avatarUrl });
        console.log('✅ 头像已同步到后端');
      } catch (apiError) {
        console.error('⚠️ 同步头像到后端失败:', apiError);
        // 不影响主流程，静默失败
      }

      // uploadResult.userInfo 可能是 { user: {...} } 结构，需要提取 user
      // const latestInfo = uploadResult.userInfo?.user || uploadResult.userInfo || getApp().globalData.userInfo?.user;
      // 优先使用 cachedUrl，其次使用 fileUrl，最后尝试从 uploadData 中获取
      // const displayAvatar = uploadResult.cachedUrl || uploadResult.fileUrl || uploadResult.uploadData?.file_url || uploadResult.uploadData?.fileUrl;

      console.log('头像上传结果:', {
        uploadResult,
        avatarUrl
      });


      if (avatarUrl) {
        this.setData({
          selfAvatar: avatarUrl
        });
      } else {
        console.error('未找到头像URL，上传结果:', uploadResult);
        throw new Error('上传成功但未获取到头像URL');
      }

      wx.showToast({ title: '头像更新成功', icon: 'success' });
    } catch (error) {
      console.error('上传头像失败:', error);
      wx.showToast({ title: error.message || '上传失败', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  // 打开设置页面
  openSettingsPage() {
    wx.navigateTo({
      url: '/subpackages/settings/settingss/settingss'
    });
  },

  // 跳转到二维码页面
  navigateToQRCode() {
    wx.navigateTo({
      url: '/subpackages/qr/qr-code/qr-code'
    });
  },

  // 打开设置
  openSettings() {
    console.log('点击设置按钮，准备跳转到设置页面');
    wx.navigateTo({
      url: '/subpackages/settings/settingss/settingss',
      success: (res) => {
        console.log('跳转设置页面成功', res);
      },
      fail: (err) => {
        console.error('跳转设置页面失败', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 自定义功能模块点击事件
  onSelfToolClick(e) {
    const { url, label } = e.currentTarget.dataset;
    console.log('点击功能模块:', label, '跳转路径:', url);
    
    if (!url) {
      console.warn('该功能模块未配置跳转路径:', label);
      wx.showToast({
        title: '功能暂未开放',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    // 判断是否为 tabBar 页面
    const app = getApp();
    const tabBarPages = app.globalData?.tabBarPages || [];
    const isTabBarPage = tabBarPages.some(page => url.includes(page));

    if (isTabBarPage) {
      // 如果是 tabBar 页面，使用 switchTab
      wx.switchTab({
        url: url,
        success: (res) => {
          console.log('跳转 tabBar 页面成功:', url, res);
        },
        fail: (err) => {
          console.error('跳转 tabBar 页面失败:', url, err);
          wx.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    } else {
      // 普通页面使用 navigateTo
      wx.navigateTo({
        url: url,
        success: (res) => {
          console.log('跳转页面成功:', url, res);
        },
        fail: (err) => {
          console.error('跳转页面失败:', url, err);
          // 如果是页面不存在，尝试使用 redirectTo
          if (err.errMsg && err.errMsg.includes('not found')) {
            wx.redirectTo({
              url: url,
              fail: (redirectErr) => {
                console.error('重定向也失败:', url, redirectErr);
                wx.showToast({
                  title: '页面不存在',
                  icon: 'none'
                });
              }
            });
          } else {
            wx.showToast({
              title: '跳转失败',
              icon: 'none'
            });
          }
        }
      });
    }
  },

  // 复制ID
  copyId() {
    const userInfo = this.data.userInfo;
    const id = userInfo?.customId || (userInfo?.id ? 'findme_' + userInfo.id : '未设置');
    if (!id || id === '未设置') {
      wx.showToast({
        title: 'ID不存在',
        icon: 'none'
      });
      return;
    }
    wx.setClipboardData({
      data: id,
      success: () => {
        wx.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 去认证
  goVerify() {
    try {
      wx.navigateTo({
        url: '/subpackages/realname/realname'
      });
    } catch (e) {
      wx.showToast({ title: '跳转失败', icon: 'none' });
    }
  },

  // 清理缓存
  clearCache() {
    wx.showModal({
      title: '清理缓存',
      content: '确定要清理缓存吗？清理后可能需要重新加载一些数据。',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '清理中...'
          });

          // 🔥 清除图片缓存
          imageCacheManager.clearAllCache();

          setTimeout(() => {
            wx.hideLoading();
            this.setData({ cacheSize: '0MB' });
            wx.showToast({
              title: '缓存清理完成',
              icon: 'success'
            });
          }, 1000);
        }
      }
    });
  },

  // 🔥 显示缓存统计信息
  showCacheStats() {
    const stats = imageCacheManager.getCacheStats();
    wx.showModal({
      title: '缓存统计',
      content: `总缓存: ${stats.total}个\n头像缓存: ${stats.avatar}个\n图片缓存: ${stats.image}个\n过期缓存: ${stats.expired}个\n最大缓存: ${stats.maxSize}个`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      success: (res) => {
        if (res.confirm) {
          this.performLogout();
        }
      }
    });
  },

  // 执行退出登录
  async performLogout() {
    try {
      wx.showLoading({
        title: '退出中...'
      });

      // 🔥 设置退出登录标志，防止登录页误判为已登录
      wx.setStorageSync('isLoggingOut', true);

      // 清除本地存储
      await app.logout();

      // 🔥 确保完全清除登录状态
      app.globalData.isLoggedIn = false;
      app.globalData.userInfo = null;
      app.globalData.nim = null;

      // 🔥 清除可能残留的登录信息
      wx.removeStorageSync('userInfo');
      wx.removeStorageSync('token');
      wx.removeStorageSync('testWechatLogin-loginData');

      wx.hideLoading();
      wx.showToast({
        title: '已退出登录',
        icon: 'success'
      });

      // 跳转到登录页（带退出标志，防止自动跳转）
      setTimeout(() => {
        // 🔥 保留退出标志，登录页会根据此标志判断
        wx.reLaunch({
          url: '/pages/login/login?from=logout',
          success: () => {
            // 延迟清除退出标志，给登录页足够时间检查
            setTimeout(() => {
              wx.removeStorageSync('isLoggingOut');
            }, 500);
          }
        });
      }, 1000);

    } catch (error) {
      wx.hideLoading();
      console.error('退出登录失败:', error);
      
      // 🔥 即使失败也要清除状态和标志
      wx.removeStorageSync('isLoggingOut');
      app.globalData.isLoggedIn = false;
      app.globalData.userInfo = null;
      
      wx.showToast({
        title: '退出失败',
        icon: 'none'
      });
    }
  },

  // 初始化系统信息（使用新API替换已废弃的wx.getSystemInfoSync）
  initSystemInfo() {
    try {
      // 使用新的API获取系统信息
      const windowInfo = wx.getWindowInfo();
      const deviceInfo = wx.getDeviceInfo();
      const appBaseInfo = wx.getAppBaseInfo();
      const menuButtonInfo = wx.getMenuButtonBoundingClientRect();

      // 合并系统信息（保持向后兼容）
      const systemInfo = {
        ...windowInfo,
        ...deviceInfo,
        ...appBaseInfo
      };

      // 状态栏高度
      const statusBarHeight = windowInfo.statusBarHeight;

      // 胶囊按钮信息
      const menuButtonHeight = menuButtonInfo.height;
      const menuButtonTop = menuButtonInfo.top;
      const menuButtonBottom = menuButtonInfo.bottom;

      // 导航栏高度 = 胶囊按钮底部 + 胶囊按钮顶部到状态栏的距离
      const navBarHeight = menuButtonBottom + menuButtonTop - statusBarHeight;

      // 窗口高度
      const windowHeight = windowInfo.windowHeight;

      // 安全区域（screenHeight在deviceInfo中）
      const screenHeight = deviceInfo.screenHeight;
      const safeAreaBottom = windowInfo.safeArea ? screenHeight - windowInfo.safeArea.bottom : 0;

      this.setData({
        systemInfo,
        statusBarHeight,
        menuButtonHeight,
        menuButtonTop,
        navBarHeight,
        windowHeight,
        safeAreaBottom,
        bottomSpaceHeight: (safeAreaBottom || 0) * 2 + 120
      });
    } catch (error) {
      console.error('获取系统信息失败，使用兜底方案:', error);
      // 兜底方案：使用旧API（如果新API不可用）
      try {
        const systemInfo = wx.getSystemInfoSync();
        const menuButtonInfo = wx.getMenuButtonBoundingClientRect();

        const statusBarHeight = systemInfo.statusBarHeight;
        const menuButtonHeight = menuButtonInfo.height;
        const menuButtonTop = menuButtonInfo.top;
        const menuButtonBottom = menuButtonInfo.bottom;
        const navBarHeight = menuButtonBottom + menuButtonTop - statusBarHeight;
        const windowHeight = systemInfo.windowHeight;
        const safeAreaBottom = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0;

        this.setData({
          systemInfo,
          statusBarHeight,
          menuButtonHeight,
          menuButtonTop,
          navBarHeight,
          windowHeight,
          safeAreaBottom,
          bottomSpaceHeight: (safeAreaBottom || 0) * 2 + 120
        });
      } catch (fallbackError) {
        console.error('兜底方案也失败:', fallbackError);
      }
    }
  },

  // 加载用户数据
  loadUserData() {
    return new Promise((resolve) => {
      const globalUserInfo = app.globalData.userInfo;
      const isLoggedIn = app.globalData.isLoggedIn;
      const currentToken = apiClient.getToken();

      // userInfo.user 才是真正的用户信息
      let userInfo = globalUserInfo?.user ? Object.assign({}, globalUserInfo.user) : null;
      
      // 处理用户信息
      if (userInfo) {
        // 如果没有customId或customId为空字符串，使用id生成一个
        if ((!userInfo.customId || userInfo.customId.trim() === '') && userInfo.id) {
          userInfo.customId = 'findme_' + userInfo.id;
          console.log('自动生成 customId:', userInfo.customId);
        }
        // 如果既没有customId也没有id，设置默认值
        if (!userInfo.customId || userInfo.customId.trim() === '') {
          userInfo.customId = '未设置';
          console.log('customId 未设置，使用默认值');
        }
        
        // 确保 avatarUrl 存在（用于兼容）
        if (!userInfo.avatarUrl && userInfo.avatar) {
          userInfo.avatarUrl = userInfo.avatar;
        }
        
      } else {
        // 如果没有用户信息，初始化一个空对象
        userInfo = { customId: '未设置' };
        console.log('用户信息为空，初始化默认 customId');
      }
      
      // 调试：输出 customId 的值
      console.log('loadUserData - customId 处理结果:', {
        '原始 customId': globalUserInfo?.user?.customId,
        '原始 id': globalUserInfo?.user?.id,
        '处理后的 customId': userInfo?.customId,
        'userInfo 对象': userInfo
      });

      // 调试信息
      const debugInfo = {
        hasGlobalUserInfo: !!globalUserInfo,
        hasUser: !!globalUserInfo?.user,
        hasToken: !!currentToken,
        tokenLength: currentToken ? currentToken.length : 0,
        tokenPrefix: currentToken ? currentToken.substring(0, 20) + '...' : 'null',
        hasLocalStorage: false
      };

      // 检查本地存储
      try {
        const storedUserInfo = wx.getStorageSync('userInfo');
        debugInfo.hasLocalStorage = !!(storedUserInfo && storedUserInfo.token);
      } catch (error) {
        console.error('检查本地存储失败:', error);
      }

      // 从 userInfo 中提取 nickname 和 avatar
      const nickname = userInfo?.nickname || '';
      const avatar = userInfo?.avatar || userInfo?.avatarUrl || '';
      
      // 计算年龄（根据生日）
      const birthday = userInfo?.birthday;
      const calculatedAge = this.calculateAge(birthday);
      
      // 如果生日存在但星座不存在，则计算星座
      if (birthday && !userInfo?.zodiacSign) {
        const calculatedZodiacSign = calculateConstellationFromBirthday(birthday);
        if (calculatedZodiacSign) {
          userInfo.zodiacSign = calculatedZodiacSign;
          // 同步更新到全局 userInfo
          if (app.globalData.userInfo?.user) {
            app.globalData.userInfo.user.zodiacSign = calculatedZodiacSign;
          }
          console.log('自动计算星座 - 生日:', birthday, '星座:', calculatedZodiacSign);
        }
      }
      
      // 将家乡数组转换为字符串
      let hometownText = '';
      if (userInfo?.hometown) {
        if (Array.isArray(userInfo.hometown)) {
          // 过滤空值并连接
          hometownText = userInfo.hometown.filter(item => item).join(' ');
        } else if (typeof userInfo.hometown === 'string') {
          hometownText = userInfo.hometown;
        }
      }
      
      console.log('年龄计算 - 生日:', birthday, '计算结果:', calculatedAge, 'userInfo结构:', {
        'userInfo.birthday': userInfo?.birthday,
        'userInfo.zodiacSign': userInfo?.zodiacSign,
        'userInfo.customId': userInfo?.customId,
        'userInfo': userInfo,
        'hometownText': hometownText
      });

      this.setData({
        userInfo: userInfo,  // 直接设置 userInfo 为用户信息对象
        nickname: nickname,
        selfAvatar: avatar,
        calculatedAge: calculatedAge,  // 计算后的年龄
        hometownText: hometownText,  // 家乡文本（字符串格式）
        isLoggedIn: isLoggedIn,
        debugInfo: debugInfo
      }, () => {
        // 确保数据设置完成后再解析Promise
        resolve();
      });
    });
  },

  // 根据生日计算年龄
  calculateAge(birthday) {
    if (!birthday) {
      console.log('计算年龄：生日为空');
      return null;
    }
    
    try {
      // 处理 YYYY-MM-DD 格式的日期
      let birthDate;
      if (typeof birthday === 'string' && birthday.includes('-')) {
        // 确保日期格式正确
        const dateParts = birthday.split('-');
        if (dateParts.length === 3) {
          birthDate = new Date(parseInt(dateParts[0]), parseInt(dateParts[1]) - 1, parseInt(dateParts[2]));
        } else {
          birthDate = new Date(birthday);
        }
      } else {
        birthDate = new Date(birthday);
      }
      
      if (isNaN(birthDate.getTime())) {
        console.log('计算年龄：日期格式无效', birthday);
        return null;
      }
      
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      
      // 如果还没过生日，年龄减1
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      
      // 年龄应该大于等于0（0岁表示刚出生）
      const result = age >= 0 ? age : null;
      console.log('计算年龄：', birthday, '->', result, '岁');
      return result;
    } catch (error) {
      console.error('计算年龄失败:', error, birthday);
      return null;
    }
  },

  // 刷新页面
  onRefresh() {
    this.setData({ refreshing: true });
    this.loadUserData();
    setTimeout(() => {
      this.setData({ refreshing: false });
    }, 1000);
  },

  // 调试功能
  toggleDebug() {
    this.setData({
      showDebugDetails: !this.data.showDebugDetails
    });
  },

  // 测试API
  testAPI() {
    wx.showToast({
      title: 'API测试中...',
      icon: 'loading'
    });

    setTimeout(() => {
      wx.hideToast();
      wx.showModal({
        title: 'API测试结果',
        content: '测试成功！API连接正常。',
        showCancel: false
      });
    }, 1500);
  },

  // 导出日志
  exportLogs() {
    wx.showToast({
      title: '日志导出中...',
      icon: 'loading'
    });

    setTimeout(() => {
      wx.hideToast();
      wx.showModal({
        title: '日志导出',
        content: '日志已导出到本地缓存。',
        showCancel: false
      });
    }, 1500);
  },

  // 隐藏状态编辑弹窗
  hideStatusModal() {
    this.setData({ showStatusModal: false });
  },

  // 选择状态
  selectStatus(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ selectedStatus: status });
  },

  // 状态输入
  onStatusInput(e) {
    this.setData({ customStatus: e.detail.value });
  },

  // 保存状态
  saveStatus() {
    wx.showToast({
      title: '状态已保存',
      icon: 'success'
    });
    this.hideStatusModal();
  },

  // 隐藏成就提示
  hideAchievement() {
    this.setData({ showAchievement: false });
  },

  // 编辑个人资料
  editProfile() {
    wx.navigateTo({
      url: '/subpackages/profile/personal-details/personal-details'
    });
  },

  handlePostImage() {

    // 跳转到发布页面
    wx.navigateTo({
      url: '/subpackages/media/edits/edits',
      fail: (err) => {
        console.error('跳转失败:', err);
        wx.showToast({
          title: '跳转发布页面失败',
          icon: 'none'
        });
      }
    });
  },

  // 跳转到VIP页面（显示VIP套餐选择弹窗）
  async navigateToVIP() {
    wx.showLoading({ title: '加载套餐...' });
    
    try {
      // 调用接口获取套餐列表
      const plansData = await this.getUserPlans();
      
      // 将后端数据映射到前端格式
      const vipPackages = plansData.map(plan => {
        // 解析benefits字符串为数组
        const benefits = plan.benefits ? plan.benefits.split(',') : [];
        
        // 根据duration判断显示文本
        let durationText = '';
        if (plan.duration === 36500) {
          durationText = '终身';
        } else if (plan.duration >= 365) {
          durationText = `${Math.floor(plan.duration / 365)}年`;
        } else if (plan.duration >= 30) {
          durationText = `${Math.floor(plan.duration / 30)}个月`;
        } else {
          durationText = `${plan.duration}天`;
        }
        
        return {
          id: plan.id,
          name: plan.name,
          duration: durationText,
          price: plan.price,
          originalPrice: plan.price * 2, // 原价设为2倍(可根据实际需求调整)
          discount: plan.description || '',
          benefits: benefits,
          hot: plan.level === 2, // 季度会员标记为热门
          isTest: plan.name.includes('测试'),
          status: plan.status
        };
      });
      
      // 只显示状态为1的套餐
      const activePackages = vipPackages.filter(pkg => pkg.status === 1);
      
      this.setData({ 
        vipPackages: activePackages,
        showVipModal: true 
      });
      
      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      console.error('加载套餐失败:', error);
      wx.showToast({
        title: '加载套餐失败',
        icon: 'none'
      });
    }
  },

  // 关闭VIP弹窗
  closeVipModal() {
    this.setData({ 
      showVipModal: false,
      selectedVipPackage: null 
    });
  },

  // 选择VIP套餐
  selectVipPackage(e) {
    const packageId = e.currentTarget.dataset.id;
    const selectedPackage = this.data.vipPackages.find(pkg => pkg.id === packageId);
    this.setData({ selectedVipPackage: selectedPackage });
  },

  // 发起支付
  async purchaseVip() {
    const selectedPackage = this.data.selectedVipPackage;
    
    if (!selectedPackage) {
      wx.showToast({
        title: '请选择会员套餐',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({ title: '正在创建订单...' });

    try {
        // 🔥 调用后端会员订阅接口创建订单
      const orderResult = await this.createVipOrder(selectedPackage);
      
      if (!orderResult || !orderResult.success) {
        throw new Error(orderResult?.message || '创建订单失败');
      }

      wx.hideLoading();

        // 🔥 调用微信支付
      await this.callWeChatPay(orderResult.paymentParams);

        // 🔥 支付成功后查询订单状态确认
      await this.verifyPaymentStatus(orderResult.orderNo);

        // 🔥 支付成功处理
      this.handlePaymentSuccess(selectedPackage, orderResult.orderNo);

    } catch (error) {
      wx.hideLoading();
      console.error('购买VIP失败:', error);
      
      // 用户取消支付不弹错误提示
      if (error.message && error.message.indexOf('cancel') !== -1) {
        wx.showToast({
          title: '已取消支付',
          icon: 'none'
        });
        return;
      }

      wx.showModal({
        title: '支付失败',
        content: error.message || '支付过程中出现错误，请重试',
        showCancel: true,
        confirmText: '重试',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.purchaseVip();
          }
        }
      });
    }
  },

  // 🔥 获取套餐列表
  async getUserPlans() {
    try {
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${config.api.baseUrl}/api/v1/user/membership/plans`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${apiClient.getToken()}`,
            'Content-Type': 'application/json'
          },
          success: (res) => {
            if (res.data.code === 0 && res.data.data) {
              resolve(res.data.data);
            } else {
              reject(new Error(res.data.message || '获取套餐列表失败'));
            }
          },
          fail: reject
        });
      });

      console.log('✅ 成功获取套餐列表:', response);
      return response;

    } catch (error) {
      console.error('❌ 获取套餐列表失败:', error);
      throw error;
    }
  },

  // 🔥 创建VIP订单（使用推荐的会员订阅接口）
  async createVipOrder(vipPackage) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.api.baseUrl}/api/v1/user/membership/subscribe`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${apiClient.getToken()}`,
          'Content-Type': 'application/json'
        },
        data: {
          planID: vipPackage.id,           // 套餐ID（后端根据此ID查询价格）
          paymentType: 'wechat',            // 支付方式固定为微信支付
          paymentScene: 'miniprogram',      // 小程序支付场景
          // openID: openID                    // 用户openID（小程序支付必需）
        },
        success: (res) => {
          console.log('创建订单响应:', res.data);
          
          if (res.data.code === 0 && res.data.data) {
            const data = res.data.data;
            resolve({
              success: true,
              orderNo: data.orderNo,           // 商户订单号
              amount: data.amount,              // 实际支付金额
              paymentParams: data.extra,        // 调起支付所需参数
              expireTime: data.expireTime,      // 订单过期时间
              message: res.data.message
            });
          } else {
            reject(new Error(res.data.message || '创建订单失败'));
          }
        },
        fail: (err) => {
          console.error('请求创建订单失败:', err);
          reject(new Error('网络错误，请检查网络连接'));
        }
      });
    });
  },

  // 🔥 调用微信支付（使用后端返回的extra对象中的所有参数）
  async callWeChatPay(paymentParams) {
    return new Promise((resolve, reject) => {
      // 验证必需参数
      if (!paymentParams || !paymentParams.appId || !paymentParams.package) {
        reject(new Error('支付参数不完整'));
        return;
      }

      console.log('📱 调起微信支付，参数:', {
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType
      });

      wx.requestPayment({
        timeStamp: paymentParams.timeStamp,
        nonceStr: paymentParams.nonceStr,
        package: paymentParams.package,
        signType: paymentParams.signType || 'RSA',
        paySign: paymentParams.paySign,
        success: (res) => {
          console.log('✅ 微信支付成功回调:', res);
          resolve(res);
        },
        fail: (err) => {
          console.error('❌ 微信支付失败回调:', err);
          
          // 用户取消支付
          if (err.errMsg && err.errMsg.indexOf('cancel') !== -1) {
            reject(new Error('用户取消支付'));
          } else {
            reject(new Error(err.errMsg || '支付失败'));
          }
        }
      });
    });
  },

  // 🔥 验证支付状态（支付成功后主动查询确认）
  async verifyPaymentStatus(orderNo) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${config.api.baseUrl}/api/v1/payment/status/${orderNo}`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${apiClient.getToken()}`
        },
        success: (res) => {
          console.log('查询支付状态响应:', res.data);
          
          if (res.data.code === 0 && res.data.data) {
            const status = res.data.data.status;
            // status: 0-未支付, 1-已支付, 2-已取消, 3-已退款
            if (status === 1) {
              console.log('✅ 订单支付状态确认成功');
              resolve(res.data.data);
            } else {
              console.warn('⚠️ 订单状态异常:', status);
              reject(new Error(`订单状态异常: ${status}`));
            }
          } else {
            reject(new Error(res.data.message || '查询订单状态失败'));
          }
        },
        fail: (err) => {
          console.error('查询订单状态失败:', err);
          // 查询失败不影响主流程，静默处理
          resolve({ status: -1, message: '查询失败' });
        }
      });
    });
  },

  // 🔥 支付成功处理
  handlePaymentSuccess(vipPackage, orderNo) {
    // 关闭VIP弹窗
    this.closeVipModal();

    // 显示成功提示
    wx.showModal({
      title: '🎉 恭喜开通成功',
      content: `您已成功开通${vipPackage.name}！\n有效期：${vipPackage.duration}\n订单号：${orderNo}\n尊享专属权益已生效`,
      showCancel: false,
      confirmText: '开始体验',
      success: (res) => {
        if (res.confirm) {
          // 刷新用户信息
          this.loadUserData();
          
          // 更新VIP状态
          const userInfo = this.data.userInfo;
          if (userInfo) {
            userInfo.isMember = true;
            userInfo.memberLevel = vipPackage.id;
            // 更新全局用户信息
            if (app.globalData.userInfo) {
              app.globalData.userInfo.user = Object.assign({}, app.globalData.userInfo.user || {}, userInfo);
            }
            this.setData({ userInfo });
          }

          wx.showToast({
            title: 'VIP权益已生效',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },

  // 🔥 计算VIP过期时间
  calculateVipExpireTime(duration) {
    const now = new Date();
    if (duration === '终身') {
      return '9999-12-31';
    }
    
    // 提取天数
    const days = parseInt(duration);
    if (isNaN(days)) {
      return null;
    }

    now.setDate(now.getDate() + days);
    return now.toISOString();
  },

  // 查看VIP权益详情
  viewVipBenefits(e) {
    const packageId = e.currentTarget.dataset.id;
    const vipPackage = this.data.vipPackages.find(pkg => pkg.id === packageId);
    
    if (vipPackage) {
      const benefitsText = vipPackage.benefits.join('\n✓ ');
      
      wx.showModal({
        title: `${vipPackage.name} 专属权益`,
        content: `✓ ${benefitsText}\n\n有效期：${vipPackage.duration}\n价格：¥${vipPackage.price}`,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  },

  // 阻止弹窗背景滚动穿透
  preventTouchMove() {
    return false;
  },

  // 阻止点击事件冒泡
  stopPropagation() {
    return false;
  },

  // 处理点赞
  async handleLike(e) {
    const feedUuid = e.currentTarget.dataset.feedUuid;
    const isLiked = e.currentTarget.dataset.isliked;
    const feedIndex = e.currentTarget.dataset.feedIndex;
    
    if (!feedUuid) {
      wx.showToast({
        title: '动态ID不存在',
        icon: 'none'
      });
      return;
    }

    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    if (!isLiked) {
      const response = await apiClient.addLikeDynamic(feedUuid);
      if (response) {
        if (response.code == 200) {
          wx.showToast({
            title: response.data.message,
            icon: 'success',
            duration: 1000
          });
        } else {
          wx.showToast({
            title: response.message,
            icon: 'none',
            duration: 1000
          });
        }
      }
      // 更新点赞状态和数量
      this.updateLikeStatus(feedIndex, true);
    } else {
      const responseDelete = await apiClient.deleteLikeDynamic(feedUuid);
      if (responseDelete) {
        if (responseDelete.code == 200) {
          wx.showToast({
            title: responseDelete.data.message,
            icon: 'success',
            duration: 1000
          });
        } else {
          wx.showToast({
            title: responseDelete.message,
            icon: 'none',
            duration: 1000
          });
        }
      }
      // 更新点赞状态和数量
      this.updateLikeStatus(feedIndex, false);
    }
  },

  // 更新点赞状态
  updateLikeStatus(feedIndex, isLiked) {
    const dynamicList = [...this.data.dynamicList];
    
    if (dynamicList[feedIndex]) {
      // 初始化interactions对象（防止undefined错误）
      if (!dynamicList[feedIndex].interactions) {
        dynamicList[feedIndex].interactions = {
          likeCount: 0,
          commentCount: 0
        };
      }
      
      // 更新点赞状态
      dynamicList[feedIndex].isLiked = isLiked;
      
      // 更新点赞数量（点赞+1，取消点赞-1）
      dynamicList[feedIndex].interactions.likeCount = 
        (dynamicList[feedIndex].interactions.likeCount || 0) + (isLiked ? 1 : -1);
      
      // 确保数量不会小于0
      if (dynamicList[feedIndex].interactions.likeCount < 0) {
        dynamicList[feedIndex].interactions.likeCount = 0;
      }
      
      // 更新数据
      this.setData({
        dynamicList: dynamicList
      });
    }
  },

  // 处理评论 - 显示/隐藏评论输入框
  handleComment(e) {
    const feedUuid = e.currentTarget.dataset.feedUuid;
    const feedIndex = e.currentTarget.dataset.feedIndex;
    
    if (!feedUuid) {
      wx.showToast({
        title: '动态ID不存在',
        icon: 'none'
      });
      return;
    }

    // 检查登录状态
    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    // 切换评论输入框显示状态
    const showCommentInput = { ...this.data.showCommentInput };
    const commentKey = `feed_${feedIndex}`;
    
    // 如果当前输入框已显示，则关闭；否则打开
    if (showCommentInput[commentKey]) {
      showCommentInput[commentKey] = false;
      this.setData({
        showCommentInput: showCommentInput,
        commentInputValue: ''
      });
    } else {
      // 关闭其他所有输入框
      Object.keys(showCommentInput).forEach(key => {
        showCommentInput[key] = false;
      });
      
      // 打开当前输入框
      showCommentInput[commentKey] = true;
      
      this.setData({
        showCommentInput: showCommentInput,
        commentInputValue: '',
        currentFeedUuid: feedUuid,
        currentFeedIndex: feedIndex
      });
    }
  },


  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentInputValue: e.detail.value
    });
  },

  // 格式化评论时间
  formatCommentTime(timeStr) {
    if (!timeStr) return '';

    const commentTime = new Date(timeStr);
    if (isNaN(commentTime.getTime())) return '';

    const now = new Date();
    const diffMinutes = Math.floor((now - commentTime) / (1000 * 60));

    // 5分钟内：显示"刚刚"
    if (diffMinutes < 5) return '刚刚';

    // 格式化日期时间
    const year = commentTime.getFullYear();
    const month = commentTime.getMonth() + 1;
    const day = commentTime.getDate();
    const hour = String(commentTime.getHours()).padStart(2, '0');
    const minute = String(commentTime.getMinutes()).padStart(2, '0');

    // 当前年份：显示不带年份的日期和时间
    // 非当前年份：显示带年份的日期和时间
    const currentYear = now.getFullYear();
    return year === currentYear
      ? `${month}月${day}日 ${hour}:${minute}`
      : `${year}年 ${month}月${day}日 ${hour}:${minute}`;
  },

  // 提交评论
  async submitComment(e) {
    const feedIndex = e.currentTarget.dataset.feedIndex;
    const { commentInputValue, currentFeedUuid } = this.data;
    
    if (!commentInputValue || !commentInputValue.trim()) {
      wx.showToast({
        title: '请输入评论内容',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    // 防重复点击
    if (this.data.submittingComment) {
      return;
    }
    this.setData({ submittingComment: true });

    // 获取当前用户信息
    const app = getApp();
    const currentUser = app.globalData.userInfo?.user || {};
    const userName = currentUser.nickname || currentUser.customId || '未知用户';

    try {
      const response = await apiClient.addCommentDynamic(currentFeedUuid, commentInputValue.trim(), null, userName);
      
      if (response && response.code === 200) {
        wx.showToast({
          title: '评论成功',
          icon: 'success',
          duration: 1000
        });

        // 创建新评论对象（新发布的评论默认是自己的）
        const newComment = {
          id: response.data?.id || `comment_${Date.now()}`,
          content: commentInputValue.trim(),
          createdAt: response.data?.createdAt || new Date().toISOString(),
          user: {
            nickname: currentUser.nickname || currentUser.customId || '未知用户',
            avatar: currentUser.avatar || '/images/findme-logo.png',
            customId: currentUser.customId || ''
          },
          formattedTime: this.formatCommentTime(response.data?.createdAt || new Date().toISOString()),
          replies: [],
          visibleReplyCount: 5,
          isOwn: true
        };

        // 更新动态的评论列表和数量
        const dynamic = this.data.dynamicList[feedIndex];
        if (dynamic) {
          const currentComments = dynamic.comments || [];
          const updatedComments = [newComment, ...currentComments];
          const currentCommentCount = dynamic.interactions?.commentCount || 0;
          
          const updatePath = {};
          updatePath[`dynamicList[${feedIndex}].comments`] = updatedComments;
          updatePath[`dynamicList[${feedIndex}].interactions.commentCount`] = currentCommentCount + 1;
          if (!dynamic.visibleCommentCount || dynamic.visibleCommentCount < 20) {
            updatePath[`dynamicList[${feedIndex}].visibleCommentCount`] = 20;
          }
          
          // 关闭输入框并清空内容
          const showCommentInput = { ...this.data.showCommentInput };
          showCommentInput[`feed_${feedIndex}`] = false;
          updatePath.showCommentInput = showCommentInput;
          updatePath.commentInputValue = '';
          updatePath.submittingComment = false;
          
          this.setData(updatePath);
        } else {
          this.setData({ submittingComment: false });
        }
      } else {
        this.setData({ submittingComment: false });
        wx.showToast({
          title: response?.message || '评论失败',
          icon: 'none',
          duration: 1500
        });
      }
    } catch (error) {
      console.error('提交评论失败:', error);
      wx.showToast({
        title: '评论失败，请重试',
        icon: 'none',
        duration: 1500
      });
    } finally {
      this.setData({ submittingComment: false });
    }
  },

  // 展开更多评论（每次增加20条）
  expandComments(e) {
    const feedIndex = e.currentTarget.dataset.feedIndex;
    this.loadMoreComments(feedIndex);
  },

  // 加载更多评论（懒加载，每次加载20条）
  loadMoreComments(feedIndex) {
    const dynamic = this.data.dynamicList[feedIndex];
    if (dynamic && dynamic.comments) {
      const currentCount = dynamic.visibleCommentCount || 20;
      const totalCount = dynamic.comments.length;
      if (currentCount >= totalCount) {
        return;
      }
      const newCount = Math.min(currentCount + 20, totalCount);
      if (newCount > currentCount) {
        this.setData({
          [`dynamicList[${feedIndex}].visibleCommentCount`]: newCount
        });
      }
    }
  },

  // 评论区域滚动到底部时触发（懒加载评论和回复）
  onCommentScrollToLower(e) {
    const feedIndex = e.currentTarget.dataset.feedIndex;
    if (feedIndex !== undefined && feedIndex !== null) {
      const dynamic = this.data.dynamicList[feedIndex];
      
      // 先尝试加载更多回复（优先处理回复）
      if (dynamic && dynamic.comments) {
        let hasMoreReplies = false;
        dynamic.comments.forEach((comment, commentIndex) => {
          if (comment.replies && comment.replies.length > 0) {
            const currentCount = comment.visibleReplyCount || 5;
            const totalCount = comment.replies.length;
            
            if (currentCount < totalCount) {
              const newCount = Math.min(currentCount + 20, totalCount);
              if (newCount > currentCount) {
                this.setData({
                  [`dynamicList[${feedIndex}].comments[${commentIndex}].visibleReplyCount`]: newCount
                });
                hasMoreReplies = true;
              }
            }
          }
        });
        
        if (hasMoreReplies) {
          return;
        }
      }
      
      // 如果没有更多回复需要加载，则加载更多评论
      this.loadMoreComments(feedIndex);
    }
  },

  // 展开更多回复（每次增加20条）
  expandReplies(e) {
    const feedIndex = e.currentTarget.dataset.feedIndex;
    const commentIndex = e.currentTarget.dataset.commentIndex;
    const dynamic = this.data.dynamicList[feedIndex];
    
    if (dynamic && dynamic.comments && dynamic.comments[commentIndex]) {
      const comment = dynamic.comments[commentIndex];
      const currentCount = comment.visibleReplyCount || 5;
      const totalCount = comment.replies ? comment.replies.length : 0;
      const newCount = Math.min(currentCount + 20, totalCount);
      
      if (newCount > currentCount) {
        this.setData({
          [`dynamicList[${feedIndex}].comments[${commentIndex}].visibleReplyCount`]: newCount
        });
      }
    }
  },

  // 点击回复按钮
  handleReplyClick(e) {
    const feedIndex = e.currentTarget.dataset.feedIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const commentIndex = e.currentTarget.dataset.commentIndex;
    const replyId = e.currentTarget.dataset.replyId;
    const replyToUserName = e.currentTarget.dataset.replyToUser || '';
    
    const dynamic = this.data.dynamicList[feedIndex];
    const feedUuid = dynamic ? (dynamic.uuid || dynamic.id || dynamic.dynamicId) : '';
    
    // 生成唯一key
    const replyKey = replyId 
      ? `feed_${feedIndex}_comment_${commentId}_reply_${replyId}`
      : `feed_${feedIndex}_comment_${commentId}`;
    
    // 切换回复输入框显示状态
    const showReplyInput = { ...this.data.showReplyInput };
    
    if (showReplyInput[replyKey]) {
      showReplyInput[replyKey] = false;
      this.setData({
        showReplyInput: showReplyInput,
        replyInputValue: '',
        replyingCommentId: null,
        replyingCommentIndex: null,
        replyingToCommentId: null
      });
    } else {
      Object.keys(showReplyInput).forEach(key => {
        showReplyInput[key] = false;
      });
      showReplyInput[replyKey] = true;
      
      this.setData({
        showReplyInput: showReplyInput,
        replyInputValue: replyToUserName ? `@${replyToUserName} ` : '',
        replyingCommentId: commentId,
        replyingCommentIndex: commentIndex,
        replyingToCommentId: replyId || null,
        currentFeedIndex: feedIndex,
        currentFeedUuid: feedUuid
      });
    }
  },

  // 回复输入
  onReplyInput(e) {
    this.setData({
      replyInputValue: e.detail.value
    });
  },

  // 提交回复
  async submitReply(e) {
    if (this.data.submittingReply) {
      return;
    }

    const feedIndex = e.currentTarget.dataset.feedIndex;
    const commentId = e.currentTarget.dataset.commentId;
    const commentIndex = e.currentTarget.dataset.commentIndex;
    const replyId = e.currentTarget.dataset.replyId;
    const { replyInputValue, replyingToCommentId } = this.data;
    
    const contentWithoutMention = replyInputValue ? replyInputValue.trim().replace(/^@[\S]+\s+/, '') : '';
    if (!replyInputValue || !replyInputValue.trim() || !contentWithoutMention) {
      wx.showToast({
        title: '请输入回复内容',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    this.setData({ submittingReply: true });

    const dynamic = this.data.dynamicList[feedIndex];
    if (!dynamic) {
      wx.showToast({ title: '动态不存在', icon: 'none' });
      this.setData({ submittingReply: false });
      return;
    }

    const feedUuid = dynamic.uuid || dynamic.id || dynamic.dynamicId;
    if (!feedUuid) {
      wx.showToast({ title: '动态ID不存在', icon: 'none' });
      this.setData({ submittingReply: false });
      return;
    }

    const app = getApp();
    if (!app.globalData.isLoggedIn) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => { wx.navigateTo({ url: '/pages/login/login' }); }, 1500);
      this.setData({ submittingReply: false });
      return;
    }

    const currentUser = app.globalData.userInfo?.user || {};
    const userName = currentUser.nickname || currentUser.customId || '未知用户';

    try {
      const replyToId = replyingToCommentId || commentId;
      const response = await apiClient.addCommentDynamic(feedUuid, replyInputValue.trim(), replyToId, userName);
      
      if (response && response.code === 200) {
        wx.showToast({
          title: '回复成功',
          icon: 'success',
          duration: 1000
        });

        // 创建新回复对象
        const newReply = {
          id: response.data?.id || `reply_${Date.now()}`,
          content: replyInputValue.trim().replace(/^@[\S]+\s+/, ''),
          createdAt: response.data?.createdAt || new Date().toISOString(),
          user: {
            nickname: currentUser.nickname || currentUser.customId || '未知用户',
            avatar: currentUser.avatar || '/images/findme-logo.png',
            customId: currentUser.customId || ''
          },
          formattedTime: this.formatCommentTime(response.data?.createdAt || new Date().toISOString()),
          replyToId: replyToId,
          replyToUser: replyingToCommentId ? this.findReplyUser(dynamic, commentId, replyingToCommentId) : null,
          isOwn: true
        };

        // 更新动态的评论列表
        const updateDynamic = this.data.dynamicList[feedIndex];
        if (updateDynamic && updateDynamic.comments && updateDynamic.comments[commentIndex]) {
          const comment = updateDynamic.comments[commentIndex];
          const currentReplies = comment.replies || [];
          const updatedReplies = [newReply, ...currentReplies];
          const currentCommentCount = updateDynamic.interactions?.commentCount || 0;
          
          const updatePath = {};
          updatePath[`dynamicList[${feedIndex}].comments[${commentIndex}].replies`] = updatedReplies;
          updatePath[`dynamicList[${feedIndex}].interactions.commentCount`] = currentCommentCount + 1;
          
          const currentVisibleReplyCount = comment.visibleReplyCount || 5;
          if (currentVisibleReplyCount < 5) {
            updatePath[`dynamicList[${feedIndex}].comments[${commentIndex}].visibleReplyCount`] = 5;
          }
          
          const replyKey = replyingToCommentId ? `feed_${feedIndex}_comment_${commentId}_reply_${replyingToCommentId}` : `feed_${feedIndex}_comment_${commentId}`;
          const showReplyInput = { ...this.data.showReplyInput };
          showReplyInput[replyKey] = false;
          
          updatePath.showReplyInput = showReplyInput;
          updatePath.replyInputValue = '';
          updatePath.replyingCommentId = null;
          updatePath.replyingCommentIndex = null;
          updatePath.replyingToCommentId = null;
          updatePath.submittingReply = false;
          
          this.setData(updatePath);
        } else {
          this.setData({ submittingReply: false });
        }
      } else {
        this.setData({
          submittingReply: false
        });
        wx.showToast({
          title: response?.message || '回复失败',
          icon: 'none',
          duration: 1500
        });
      }
    } catch (error) {
      console.error('提交回复失败:', error);
      this.setData({
        submittingReply: false
      });
      wx.showToast({
        title: '回复失败，请重试',
        icon: 'none',
        duration: 1500
      });
    }
  },

  // 查找被回复的用户信息
  findReplyUser(dynamic, commentId, replyId) {
    if (!dynamic || !dynamic.comments) return null;
    
    const comment = dynamic.comments.find(c => c.id === commentId);
    if (!comment || !comment.replies) return null;
    
    const reply = comment.replies.find(r => r.id === replyId);
    return reply ? reply.user : null;
  },

  // 删除评论
  async deleteComment(e) {
    const { feedIndex, commentId, commentIndex } = e.currentTarget.dataset;
    
    if (feedIndex === undefined || feedIndex === null || !commentId || commentIndex === undefined || commentIndex === null) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '删除评论',
      content: '确定要删除这条评论吗？',
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: async (res) => {
        if (!res.confirm) return;

        const dynamic = this.data.dynamicList[feedIndex];
        if (!dynamic) {
          wx.showToast({ title: '动态不存在', icon: 'none' });
          return;
        }

        const feedUuid = dynamic.uuid || dynamic.id || dynamic.dynamicId;
        if (!feedUuid) {
          wx.showToast({ title: '动态ID不存在', icon: 'none' });
          return;
        }

        try {
          wx.showLoading({ title: '删除中...', mask: true });
          const response = await apiClient.deleteCommentDynamic(feedUuid, commentId);

          if (response && response.code === 200) {
            wx.hideLoading();
            wx.showToast({ title: '删除成功', icon: 'success', duration: 1000 });

            const currentComments = this.data.dynamicList[feedIndex].comments || [];
            const updatedComments = currentComments.filter((c) => c.id !== commentId);
            const currentCommentCount = (this.data.dynamicList[feedIndex].interactions.commentCount || 0) - 1;
            
            const updatePath = {};
            updatePath[`dynamicList[${feedIndex}].comments`] = updatedComments;
            updatePath[`dynamicList[${feedIndex}].interactions.commentCount`] = Math.max(0, currentCommentCount);
            this.setData(updatePath);
          } else {
            wx.hideLoading();
            wx.showToast({ title: response?.message || '删除失败', icon: 'none', duration: 1500 });
          }
        } catch (error) {
          console.error('删除评论失败:', error);
          wx.hideLoading();
          wx.showToast({ title: '删除失败，请重试', icon: 'none', duration: 1500 });
        }
      }
    });
  },

  // 删除回复
  async deleteReply(e) {
    const { feedIndex, commentId, commentIndex, replyId, replyIndex } = e.currentTarget.dataset;
    
    if (feedIndex === undefined || feedIndex === null || !commentId || commentIndex === undefined || commentIndex === null || !replyId || replyIndex === undefined || replyIndex === null) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '删除回复',
      content: '确定要删除这条回复吗？',
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: async (res) => {
        if (!res.confirm) return;

        const dynamic = this.data.dynamicList[feedIndex];
        if (!dynamic) {
          wx.showToast({ title: '动态不存在', icon: 'none' });
          return;
        }

        const feedUuid = dynamic.uuid || dynamic.id || dynamic.dynamicId;
        if (!feedUuid) {
          wx.showToast({ title: '动态ID不存在', icon: 'none' });
          return;
        }

        try {
          wx.showLoading({ title: '删除中...', mask: true });
          const response = await apiClient.deleteCommentDynamic(feedUuid, replyId);

          if (response && response.code === 200) {
            wx.hideLoading();
            wx.showToast({ title: '删除成功', icon: 'success', duration: 1000 });

            const currentComments = this.data.dynamicList[feedIndex].comments || [];
            const targetCommentIndex = currentComments.findIndex(c => c.id === commentId);
            if (targetCommentIndex >= 0) {
              const targetComment = currentComments[targetCommentIndex];
              if (targetComment && targetComment.replies) {
                const updatedReplies = targetComment.replies.filter((r) => r.id !== replyId);
                const currentCommentCount = (this.data.dynamicList[feedIndex].interactions.commentCount || 0) - 1;
                
                const updatePath = {};
                updatePath[`dynamicList[${feedIndex}].comments[${targetCommentIndex}].replies`] = updatedReplies;
                updatePath[`dynamicList[${feedIndex}].interactions.commentCount`] = Math.max(0, currentCommentCount);
                this.setData(updatePath);
              }
            }
          } else {
            wx.hideLoading();
            wx.showToast({ title: response?.message || '删除失败', icon: 'none', duration: 1500 });
          }
        } catch (error) {
          console.error('删除回复失败:', error);
          wx.hideLoading();
          wx.showToast({ title: '删除失败，请重试', icon: 'none', duration: 1500 });
        }
      }
    });
  }
});

