<template>
  <view class="message-page">
    <!-- 顶部标题栏 -->
    <view class="header">
      <text class="header-title">💬 消息</text>
      <view class="header-actions">
        <text class="action-icon" @click="showSearchPanel = true">🔍</text>
      </view>
    </view>

    <!-- 搜索面板 -->
    <view v-if="showSearchPanel" class="search-panel">
      <view class="search-bar">
        <input 
          class="search-input" 
          v-model="searchKeyword" 
          placeholder="搜索好友或消息内容"
          @input="onSearch" />
        <text class="search-cancel" @click="cancelSearch">取消</text>
      </view>
    </view>

    <!-- 会话列表 -->
    <scroll-view 
      class="conversation-list" 
      scroll-y 
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMore">
      
      <!-- 骨架屏加载状态 -->
      <view v-if="loading && conversations.length === 0" class="skeleton-container">
        <view v-for="i in 6" :key="i" class="skeleton-item">
          <view class="skeleton-avatar"></view>
          <view class="skeleton-content">
            <view class="skeleton-line skeleton-line-title"></view>
            <view class="skeleton-line skeleton-line-text"></view>
          </view>
        </view>
      </view>

      <!-- 空状态（初次/无搜索） -->
      <view v-if="conversations.length === 0 && !loading && !searchKeyword" class="empty-container">
        <view class="empty-icon-wrapper">
          <text class="empty-icon">💬</text>
        </view>
        <text class="empty-text">暂无消息</text>
        <text class="empty-hint">开始和心仪的TA聊天吧~</text>
        <view class="empty-action">
          <button class="empty-btn" @click="switchTab('recommend')">去推荐页面</button>
        </view>
      </view>

      <!-- 系统消息作为第一条会话项展示（整合到同列表，突出样式） -->
      <view v-else-if="!searchKeyword" class="conversation-item-wrapper system-highlight" @click="openSystemMessages">
        <view class="conversation-item">
          <view class="avatar-wrapper">
            <text class="system-icon">📢</text>
            <view v-if="systemUnread > 0" class="unread-badge">{{ systemUnread > 99 ? '99+' : systemUnread }}</view>
          </view>
          <view class="conversation-content">
            <view class="content-top">
              <text class="user-name system-title">系统通知</text>
              <text class="last-time">{{ systemLatestTime ? formatTime(systemLatestTime) : '' }}</text>
            </view>
            <view class="content-bottom">
              <text class="last-message system-preview">{{ systemLatestPreview || '平台公告及处理通知' }}</text>
              <text class="system-tag"></text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 搜索无结果 -->
      <view v-else-if="searchKeyword && filteredConversations.length === 0" class="empty-container">
        <view class="empty-icon-wrapper">
          <text class="empty-icon">🔍</text>
        </view>
        <text class="empty-text">没有找到相关内容</text>
        <text class="empty-hint">试试搜索其他关键词</text>
      </view>

      <!-- 会话列表项（带滑动） -->
      <view 
        v-for="conv in filteredConversations" 
        :key="conv.id"
        class="conversation-item-wrapper">
        
        <movable-area class="movable-area">
          <movable-view 
            class="movable-view" 
            direction="horizontal" 
            :x="conv.id === swipingConvId ? -150 : 0"
            @change="handleSwipe($event, conv)"
            @touchend="handleSwipeEnd(conv)">
            
            <view class="conversation-item" @click="openChat(conv)" @longpress="showActionMenu(conv)">
              <!-- 置顶标记 -->
              <view v-if="conv.isPinned" class="pinned-badge">📌</view>
              
              <!-- 头像 -->
              <view class="avatar-wrapper">
                <image 
                  class="avatar" 
                  :src="conv.targetUserAvatar || '/static/default-avatar.svg'" 
                  mode="aspectFill" 
                  lazy-load />
                <view v-if="conv.isOnline" class="online-badge"></view>
                <view v-if="conv.unreadCount > 0" class="unread-badge">
                  {{ conv.unreadCount > 99 ? '99+' : conv.unreadCount }}
                </view>
              </view>

              <!-- 会话内容 -->
              <view class="conversation-content">
                <view class="content-top">
                  <text class="user-name">{{ conv.targetUserName }}</text>
                  <text class="last-time">{{formatTime(conv.lastMessageTime) }}</text>
                </view>
                <view class="content-bottom">
                  <text class="last-message" :class="{ unread: conv.unreadCount > 0 }">
                    {{ formatLastMessage(conv) }}
                  </text>
                  <text v-if="conv.lastMessageType === 1" class="message-type-icon">📝</text>
                  <text v-else-if="conv.lastMessageType === 2" class="message-type-icon">🖼️</text>
                  <text v-else-if="conv.lastMessageType === 3" class="message-type-icon">🎤</text>
                  <text v-else-if="conv.lastMessageType === 4" class="message-type-icon">📹</text>
                </view>
              </view>
            </view>
          </movable-view>
          
          <!-- 右滑操作按钮 -->
          <view class="conversation-actions">
            <view class="action-btn pin-btn" @click.stop="togglePin(conv)">
              {{ conv.isPinned ? '取消' : '置顶' }}
            </view>
            <view class="action-btn delete-btn" @click.stop="confirmDeleteConversation(conv)">
              删除
            </view>
          </view>
        </movable-area>
      </view>

      <!-- 加载更多 -->
      <view v-if="hasMore && conversations.length > 0" class="load-more">
        <text class="load-more-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>
      <view v-else-if="!hasMore && conversations.length > 0" class="load-more">
        <text class="load-more-text">没有更多了</text>
      </view>
    </scroll-view>

    <!-- 底部导航栏 -->
    <view class="tabbar">
      <view class="tabbar-item" @click="switchTab('index')">
        <text class="tabbar-icon">🏠</text>
        <text class="tabbar-text">首页</text>
      </view>
      <view class="tabbar-item" @click="switchTab('plaza')">
        <text class="tabbar-icon">💕</text>
        <text class="tabbar-text">广场</text>
      </view>
      <view class="tabbar-item" @click="switchTab('recommend')">
        <text class="tabbar-icon">👍</text>
        <text class="tabbar-text">推荐</text>
      </view>
      <view class="tabbar-item active">
        <text class="tabbar-icon">💬</text>
        <text class="tabbar-text">消息</text>
        <view v-if="totalUnread > 0" class="tab-badge">
          {{ totalUnread > 99 ? '99+' : totalUnread }}
        </view>
      </view>
      <view class="tabbar-item" @click="switchTab('mine')">
        <text class="tabbar-icon">👤</text>
        <text class="tabbar-text">我的</text>
      </view>
    </view>

    <!-- 操作菜单 -->
    <uni-popup ref="actionMenu" type="bottom">
      <view class="action-menu">
        <view class="menu-item" @click="markAsRead">标为已读</view>
        <view class="menu-item" @click="deleteCurrentConversation">删除会话</view>
        <view class="menu-item cancel" @click="closeActionMenu">取消</view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import { getConversations, getUnreadCount, deleteConversation, checkOnlineStatus } from '@/utils/chat-api.js';
import wsManager from '@/utils/websocket.js';
import timManager from '@/utils/tim-manager.js';
import TIM from 'tim-wx-sdk';

export default {
  data() {
    return {
	  blacklistUsers: [], // 拉黑用户ID列表
	  blacklistLoaded: false, // 拉黑列表是否加载完成
      userId: null,
      conversations: [],
      loading: false,
      refreshing: false,
      hasMore: false,  // TIM 一次性返回所有会话，不分页
      currentPage: 1,
      pageSize: 20,
      
      totalUnread: 0,
      showSearchPanel: false,
      searchKeyword: '',
      
      selectedConversation: null,
      onlineCheckTimer: null,
      timInitialized: false,
      
      // 滑动相关
      swipingConvId: null,
      
      // 置顶会话列表（本地存储）
      pinnedConversations: []
      , systemUnread: 0
      , systemLatestTime: null
      , systemLatestPreview: ''
    };
  },
  
  computed: {
    // 过滤和排序会话列表
    filteredConversations() {
      let list = [...this.conversations];
      
      // 搜索过滤
      if (this.searchKeyword) {
        list = list.filter(conv => {
          return conv.targetUserName.includes(this.searchKeyword) ||
                 conv.lastMessage.includes(this.searchKeyword);
        });
      }
      
      // 按置顶和时间排序
      list.sort((a, b) => {
        // 置顶优先
        if (a.isPinned && !b.isPinned) return -1;
        if (!a.isPinned && b.isPinned) return 1;
        
        // 时间倒序
        return new Date(b.lastMessageTime) - new Date(a.lastMessageTime);
      });
      
      return list;
    }
  },
  
  onLoad() {
    // 获取登录凭证
    const token = uni.getStorageSync('token');
    const userInfo = uni.getStorageSync('userInfo');
    const storedUserId = uni.getStorageSync('userId');
    
    console.log('=== 消息页面登录状态检查 ===');
    console.log('token:', token ? '存在' : '不存在');
    console.log('userInfo:', userInfo);
    console.log('storedUserId:', storedUserId);
    
    // 严格验证登录状态
    if (!token || !userInfo) {
      console.error('❌ 未登录或登录信息不完整');
      uni.showModal({
        title: '需要登录',
        content: '请先登录后再查看消息',
        showCancel: false,
        success: () => {
          uni.reLaunch({
            url: '/pages/page3/page3'
          });
        }
      });
      return;
    }
    
    // 优先使用 storage 中的 userId，确保一致性
    this.userId = storedUserId || userInfo.userId || userInfo.id || userInfo.user_id;
    
    // 转换为数字类型（如果是字符串）
    if (typeof this.userId === 'string') {
      this.userId = parseInt(this.userId);
    }
    
    // 最终验证 userId
    if (!this.userId || isNaN(this.userId)) {
      console.error('❌ 无法获取有效的用户ID');
      console.error('userInfo:', JSON.stringify(userInfo));
      console.error('storedUserId:', storedUserId);
      uni.showModal({
        title: '用户信息错误',
        content: '无法获取用户ID，请重新登录',
        showCancel: false,
        success: () => {
          // 清除错误的登录信息
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          uni.removeStorageSync('userId');
          uni.reLaunch({
            url: '/pages/page3/page3'
          });
        }
      });
      return;
    }
    
    console.log('✅ 当前登录用户ID:', this.userId, '(类型:', typeof this.userId, ')');
    
    // 确保 userId 同步到 storage（以防不一致）
    if (storedUserId !== this.userId) {
      console.log('⚠️ 同步 userId 到 storage');
      uni.setStorageSync('userId', this.userId);
    }
    
    // 加载置顶会话列表（基于当前用户ID）
    this.loadPinnedConversations();
    
    // 初始化腾讯云IM（确保使用正确的用户ID登录）
    this.initTIM();
    // 拉取系统消息未读
    this.loadSystemUnread();
    
    // 监听刷新事件（从聊天页面返回时触发）
    uni.$on('refreshConversations', this.refreshConversations);
	uni.$on('blacklistUpdated', this.handleBlacklistUpdate);
  },
  
  onShow() {
    console.log('=== 消息页面显示 ===');
    
    // 重新验证登录状态
    const token = uni.getStorageSync('token');
    const storedUserId = uni.getStorageSync('userId');
    
    console.log('onShow - 检查登录状态:');
    console.log('  - token:', token ? '存在' : '不存在');
    console.log('  - storedUserId:', storedUserId);
    console.log('  - this.userId:', this.userId);
    
    // 如果未登录，跳转登录页
    if (!token || !storedUserId) {
      console.warn('⚠️ 未登录，跳转登录页');
      uni.reLaunch({
        url: '/pages/page3/page3'
      });
      return;
    }
    
    // 如果用户ID改变，更新页面userId并重新初始化TIM
    if (storedUserId !== this.userId) {
      console.warn('⚠️ 用户ID改变，从', this.userId, '到', storedUserId);
      console.log('🔄 更新页面userId并重新初始化TIM...');
      
      this.userId = storedUserId;
      this.timInitialized = false;
      
      // 重新初始化TIM
      this.initTIM().catch(error => {
        console.error('❌ 重新初始化TIM失败:', error);
        uni.showToast({
          title: '初始化失败',
          icon: 'none'
        });
      });
      return;
    }
    
    console.log('✅ 登录状态正常，用户ID:', this.userId);
    
    // 页面显示时刷新会话列表
    this.refreshConversations();
    this.loadSystemUnread();
  },
  
  onUnload() {
    // 清除定时器
    if (this.onlineCheckTimer) {
      clearInterval(this.onlineCheckTimer);
    }
    
    // 移除事件监听
    uni.$off('refreshConversations', this.refreshConversations);
	// 移除拉黑状态变更监听
	  uni.$off('blacklistUpdated', this.handleBlacklistUpdate);
  },
  
  methods: {
	  
	  /**
	     * 处理拉黑列表更新事件
	     */
	    async handleBlacklistUpdate() {
	      console.log('🔄 检测到拉黑列表更新，开始刷新会话列表');
	      
	      // 重置拉黑列表加载状态
	      this.blacklistLoaded = false;
	      
	      // 重新加载拉黑列表
	      await this.loadBlacklist();
	      
	      // 重新加载系统消息未读
	      await this.loadSystemUnread();
	      
	      // 重新加载会话列表（会自动过滤拉黑用户）
	      this.loadConversations();
	      
	      // 显示提示
	      uni.showToast({
	        title: '已更新会话列表',
	        icon: 'success',
	        duration: 1500
	      });
	    },
    /**
     * 初始化腾讯云IM
     */
    async initTIM() {
      try {
        console.log('📱 初始化腾讯云IM...');
        console.log('📱 当前用户ID:', this.userId);
        
        // 如果未初始化，先初始化
        if (!timManager.tim) {
          timManager.init(1600109674);  // SDKAppID
          console.log('✅ TIM SDK 实例已创建');
        }
        
        // 检查是否已登录，以及登录的用户是否匹配
        if (timManager.isLogin && timManager.userId) {
          // 如果已登录但用户ID不匹配，先登出
          if (String(timManager.userId) !== String(this.userId)) {
            console.warn('⚠️ 检测到用户切换，从', timManager.userId, '到', this.userId);
            console.log('⚠️ 执行登出操作...');
            await timManager.logout();
          } else {
            console.log('✅ TIM 已登录，用户ID匹配:', this.userId);
            this.timInitialized = true;
            // 直接加载会话列表
            this.loadConversations();
            return;
          }
        }
        
        // 执行登录流程
        console.log('🔐 开始登录流程，用户ID:', this.userId);
        
        // 先导入用户到腾讯云IM
        await this.importUser();
        
        // 获取 UserSig 并登录
        const userSig = await this.getUserSig();
        console.log('🔑 获取到 UserSig');
        
        // 登录到 TIM
        await timManager.login(this.userId, userSig);
        console.log('✅ TIM 登录成功，用户ID:', this.userId);
        
        // 监听会话列表更新
        timManager.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
          console.log('📋 会话列表更新事件触发');
          console.log('📋 当前登录用户:', this.userId);
          this.loadConversations();
        });
        
        this.timInitialized = true;
        console.log('✅ TIM 初始化完成');
        
        // 加载会话列表
        this.loadConversations();
        
      } catch (error) {
        console.error('❌ TIM 初始化失败:', error);
        console.error('❌ 错误详情:', error.message || error);
        uni.showToast({
          title: '初始化失败: ' + (error.message || '请重试'),
          icon: 'none',
          duration: 3000
        });
      }
    },
    
    /**
     * 导入用户到腾讯云IM
     */
    async importUser() {
      try {
        await uni.request({
          url: 'http://localhost:1004/api/im/importUser',
          method: 'POST',
          data: {
            userId: String(this.userId)
          }
        });
        console.log('✅ 用户导入成功');
      } catch (error) {
        console.log('⚠️ 用户导入失败（可能已存在）:', error);
        // 导入失败不影响登录
      }
    },
    
    /**
     * 获取 UserSig
     */
    async getUserSig() {
      try {
        const res = await uni.request({
          url: `http://localhost:1004/api/im/getUserSig?userId=${this.userId}`,
          method: 'GET'
        });
        
        if (res[1].data.code === 200) {
          return res[1].data.data.userSig;
        } else {
          throw new Error(res[1].data.message);
        }
      } catch (error) {
        console.error('❌ 获取 UserSig 失败:', error);
        throw error;
      }
    },
    /**
     * 加载会话列表（从腾讯云IM）
     */
    async loadConversations() {
      if (this.loading || !this.timInitialized) {
        console.log('⏸️ 跳过加载会话列表:', this.loading ? '正在加载中' : 'TIM未初始化');
        return;
      }
      
      // 确保先加载拉黑列表
      if (!this.blacklistLoaded) {
        await this.loadBlacklist();
      }
      
      // 验证登录状态
      if (!timManager.isLogin || !timManager.userId) {
        console.error('❌ TIM 未登录或用户ID为空');
        return;
      }
      
      // 验证用户ID是否匹配
      if (String(timManager.userId) !== String(this.userId)) {
        console.error('❌ 用户ID不匹配！TIM:', timManager.userId, '页面:', this.userId);
        console.log('🔄 自动切换用户，重新登录TIM...');
        
        // 自动重新初始化TIM（会自动登出旧用户并登录新用户）
        this.timInitialized = false;
        try {
          await this.initTIM();
          // 初始化完成后会自动调用loadConversations
        } catch (error) {
          console.error('❌ 重新初始化TIM失败:', error);
          uni.showModal({
            title: '切换用户失败',
            content: '请重新登录',
            showCancel: false,
            success: () => {
              uni.reLaunch({
                url: '/pages/page3/page3'
              });
            }
          });
        }
        return;
      }
      
      this.loading = true;
      console.log('🔄 开始加载会话列表，用户ID:', this.userId);
      
      try {
        // 从腾讯云IM获取会话列表（仅当前登录用户的会话）
        const conversationList = await timManager.getConversationList();
        console.log('📋 从TIM获取到会话数:', conversationList.length);
        
        // 转换为UI需要的格式
        let formattedConversations = conversationList.map(conv => {
          const formatted = this.formatConversation(conv);
          // 验证会话是否属于当前用户
          if (formatted.userId !== this.userId) {
            console.warn('⚠️ 发现不属于当前用户的会话:', formatted);
          }
          return formatted;
        });
        
        // 过滤掉不属于当前用户的会话（双重保险）
        formattedConversations = formattedConversations.filter(conv => conv.userId === this.userId);
        
        // 先计算所有会话的未读数（包括拉黑用户）
        const allUnreadCount = formattedConversations.reduce((total, conv) => total + conv.unreadCount, 0);
        
        // 过滤掉拉黑用户的会话 🌟
        formattedConversations = formattedConversations.filter(conv => {
          return !this.blacklistUsers.includes(conv.targetUserId.toString());
        });
        
        this.conversations = formattedConversations;
        
        // 批量获取用户头像信息
        await this.loadUserAvatars();
        
        // 计算总未读数（包括所有会话的未读 + 系统消息未读）
        this.totalUnread = allUnreadCount + this.systemUnread;
        
        // 同步到Vuex
        this.$store.dispatch('updateTotalUnread', this.totalUnread);
        
        console.log('✅ 会话列表加载成功');
        console.log('   - 当前用户ID:', this.userId);
        console.log('   - 会话数量:', this.conversations.length);
        console.log('   - 拉黑用户数:', this.blacklistUsers.length);
        console.log('   - 会话未读数:', allUnreadCount);
        console.log('   - 系统消息未读数:', this.systemUnread);
        console.log('   - 总未读数:', this.totalUnread);
        
        // 输出前3个会话的详细信息（调试用）
        if (this.conversations.length > 0) {
          console.log('📋 会话预览（前3个）:');
          this.conversations.slice(0, 3).forEach((conv, idx) => {
            console.log(`   ${idx + 1}. ${conv.targetUserName} (ID:${conv.targetUserId}) 头像: ${conv.targetUserAvatar}, 未读: ${conv.unreadCount}`);
          });
        }
        
        if (this.blacklistUsers.length > 0) {
          console.log('🚫 已过滤拉黑用户:', this.blacklistUsers);
        }
        
      } catch (e) {
        console.error('❌ 加载会话列表失败:', e);
        console.error('❌ 错误详情:', e.message || e);
        uni.showToast({
          title: '加载失败: ' + (e.message || '请重试'),
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.loading = false;
        this.refreshing = false;
      }
    },
    
    /**
     * 获取拉黑用户列表
     */
    async loadBlacklist() {
      try {
        console.log('🔄 加载拉黑用户列表，用户ID:', this.userId);
        
        const res = await uni.request({
          url: 'http://localhost:8083/api/chatfriend/getBlacklist', // 替换为你的后端接口
          method: 'GET',
          data: {
            userId: this.userId
          }
        });
        
        if (res[1].statusCode === 200 && res[1].data.code === 200) {
          // 假设返回格式: {data: [{targetUserId: 'xxx'}, ...]}
          const blacklistData = res[1].data.data || [];
          this.blacklistUsers = blacklistData.map(item => {
            // 确保用户ID为字符串格式，避免类型不一致问题
            return String(item.targetUserId || item.userId || item.id);
          });
          
          console.log('✅ 拉黑列表加载成功，共', this.blacklistUsers.length, '个拉黑用户:', this.blacklistUsers);
        } else {
          console.warn('⚠️ 拉黑列表接口返回异常:', res[1].data);
        }
      } catch (error) {
        console.error('❌ 加载拉黑列表失败:', error);
        // 加载失败不影响会话列表显示，只记录错误
      } finally {
        this.blacklistLoaded = true; // 标记为已加载，避免重复请求
      }
    },
    
    /**
     * 批量获取用户头像信息
     */
    async loadUserAvatars() {
      try {
        if (this.conversations.length === 0) {
          return;
        }
        
        // 收集所有需要获取头像的用户ID
        const userIds = this.conversations
          .map(conv => conv.targetUserId)
          .filter(id => id)  // 过滤掉空值
          .join(',');
        
        if (!userIds) {
          console.log('⚠️ 没有需要获取头像的用户');
          return;
        }
        
        console.log('🔄 开始批量获取用户头像，用户ID列表:', userIds);
        
        // 调用批量获取用户信息接口
        const res = await uni.request({
          url: 'http://localhost:8083/api/user/batch',
          method: 'GET',
          data: {
            userIds: userIds
          }
        });
        
        if (res[1].statusCode === 200 && res[1].data.code === 200) {
          const userList = res[1].data.data || [];
          console.log('✅ 批量获取用户信息成功，数量:', userList.length);
          
          // 创建用户ID到用户信息的映射
          const userMap = {};
          userList.forEach(user => {
            userMap[user.userId] = user;
          });
          
          // 更新会话列表中的头像和昵称
          this.conversations.forEach(conv => {
            const userInfo = userMap[conv.targetUserId];
            if (userInfo) {
              // 更新头像（如果数据库中有头像）
              if (userInfo.avatarUrl) {
                conv.targetUserAvatar = userInfo.avatarUrl;
              }
              // 更新昵称（如果数据库中的昵称更准确）
              if (userInfo.nickname && userInfo.nickname !== `用户${conv.targetUserId}`) {
                conv.targetUserName = userInfo.nickname;
              }
              
              console.log(`🖼️ 更新用户 ${conv.targetUserId} 的信息:`, {
                昵称: conv.targetUserName,
                头像: conv.targetUserAvatar
              });
            }
          });
        } else {
          console.error('❌ 批量获取用户信息失败:', res[1].data);
        }
      } catch (error) {
        console.error('❌ 批量获取用户头像失败:', error);
        // 头像获取失败不影响会话列表显示，只记录错误
      }
    },
    
    /**
     * 格式化会话数据
     * 将TIM的会话格式转换为UI需要的格式
     */
    formatConversation(timConv) {
      // conversationID 格式: C2C{userId}
      const targetUserId = timConv.conversationID.replace('C2C', '');
      
      // 检查是否在本地置顶列表中
      const isPinned = this.pinnedConversations.includes(timConv.conversationID) ? 1 : 0;
      
      return {
        id: timConv.conversationID,
        userId: this.userId,
        targetUserId: targetUserId,
        targetUserName: timConv.userProfile?.nick || `用户${targetUserId}`,
        targetUserAvatar: timConv.userProfile?.avatar || '',
        lastMessage: this.getLastMessageText(timConv.lastMessage),
        lastMessageType: this.getMessageType(timConv.lastMessage),
        lastMessageTime: timConv.lastMessage?.lastTime ? timConv.lastMessage.lastTime * 1000 : Date.now(),
        unreadCount: timConv.unreadCount || 0,
        isOnline: false,
        isPinned: isPinned
      };
    },
    
    /**
     * 获取最后一条消息的文本
     */
    getLastMessageText(message) {
      if (!message) return '暂无消息';
      
      switch (message.type) {
        case 'TIMTextElem':
          return message.payload?.text || '';
        case 'TIMImageElem':
          return '[图片]';
        case 'TIMSoundElem':
          return '[语音]';
        case 'TIMVideoFileElem':
          return '[视频]';
        case 'TIMFileElem':
          return '[文件]';
        case 'TIMCustomElem':
          return '[自定义消息]';
        default:
          return '[未知消息]';
      }
    },
    
    /**
     * 获取消息类型
     */
    getMessageType(message) {
      if (!message) return 1;
      
      const typeMap = {
        'TIMTextElem': 1,      // 文本
        'TIMImageElem': 2,     // 图片
        'TIMSoundElem': 3,     // 语音
        'TIMVideoFileElem': 4  // 视频
      };
      
      return typeMap[message.type] || 1;
    },
    
    /**
     * 下拉刷新
     */
    onRefresh() {
      this.refreshing = true;
      this.loadConversations();
    },
    
    /**
     * 加载更多（TIM一次性返回所有会话，不需要分页）
     */
    loadMore() {
      // TIM SDK 一次性返回所有会话，不需要分页加载
    },

    /**
     * 加载系统消息未读
     */
    async loadSystemUnread() {
      try {
        const userId = this.userId;
        const res = await this.$api?.message?.getSystemUnreadCount ? this.$api.message.getSystemUnreadCount(userId) : null;
        if (res && (res.code === 200 || res.code === 0)) {
          this.systemUnread = res.data || 0;
        } else {
          // 直接调用工具方法
          const api = require('@/utils/api.js').default;
          const r = await api.message.getSystemUnreadCount(userId);
          this.systemUnread = r.data || 0;
        }
        
        // 预览最新一条
        const api2 = require('@/utils/api.js').default;
        const listRes = await api2.message.getSystemList(userId, 1, 1);
        const list = listRes.data?.list || listRes.data || [];
        if (list.length > 0) {
          this.systemLatestTime = list[0].createdAt || list[0].created_at;
          this.systemLatestPreview = list[0].title || '系统通知';
        }
        
        // 更新总未读数
        const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
        this.totalUnread = allUnreadCount + this.systemUnread;
        
        // 同步到Vuex
        this.$store.dispatch('updateTotalUnread', this.totalUnread);
        
      } catch (e) { 
        console.log('加载系统未读失败', e); 
      }
    },

    openSystemMessages() {
      uni.navigateTo({ url: '/pages/message/system' });
    },
    
    /**
     * 刷新会话列表
     */
    refreshConversations() {
      if (this.timInitialized) {
        // 先刷新系统消息未读
        this.loadSystemUnread();
        // 再刷新会话列表
        this.loadConversations();
      }
    },
    
    /**
     * 打开聊天页面
     */
    openChat(conversation) {
      uni.navigateTo({
        url: `/pages/message/chat?targetUserId=${conversation.targetUserId}&targetUserName=${conversation.targetUserName}&targetUserAvatar=${conversation.targetUserAvatar || ''}`
      });
    },
    
    /**
     * 显示操作菜单
     */
    showActionMenu(conversation) {
      this.selectedConversation = conversation;
      this.$refs.actionMenu.open();
    },
    
    /**
     * 关闭操作菜单
     */
    closeActionMenu() {
      this.$refs.actionMenu.close();
      this.selectedConversation = null;
    },
    
    /**
     * 标记为已读
     */
    async markAsRead() {
      if (!this.selectedConversation) {
        return;
      }
      
      try {
        // 调用 TIM SDK 标记已读
        await timManager.setMessageRead(this.selectedConversation.id);
        
        // 更新本地显示
        this.selectedConversation.unreadCount = 0;
        
        // 重新计算总未读数（包含所有会话+系统消息）
        const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
        this.totalUnread = allUnreadCount + this.systemUnread;
        
        // 同步到Vuex
        this.$store.dispatch('updateTotalUnread', this.totalUnread);
        
        uni.showToast({
          title: '已标记为已读',
          icon: 'success'
        });
      } catch (e) {
        console.error('标记已读失败', e);
      }
      
      this.closeActionMenu();
    },
    
    /**
     * 删除会话
     */
    async deleteCurrentConversation() {
      if (!this.selectedConversation) {
        return;
      }
      
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该会话吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              // 调用 TIM SDK 删除会话
              await timManager.tim.deleteConversation(this.selectedConversation.id);
              
              // 从列表中移除
              const index = this.conversations.findIndex(c => c.id === this.selectedConversation.id);
              if (index > -1) {
                this.conversations.splice(index, 1);
              }
              
              // 重新计算总未读数（包含所有会话+系统消息）
              const allUnreadCount = this.conversations.reduce((total, conv) => total + conv.unreadCount, 0);
              this.totalUnread = allUnreadCount + this.systemUnread;
              
              // 同步到Vuex
              this.$store.dispatch('updateTotalUnread', this.totalUnread);
              
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            } catch (e) {
              console.error('删除会话失败', e);
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          }
        }
      });
      
      this.closeActionMenu();
    },
    
    /**
     * 搜索（实时过滤在computed中实现）
     */
    onSearch() {
      console.log('搜索:', this.searchKeyword);
      // filteredConversations computed属性会自动过滤
    },
    
    /**
     * 取消搜索
     */
    cancelSearch() {
      this.showSearchPanel = false;
      this.searchKeyword = '';
    },
    
    /**
     * 处理滑动
     */
    handleSwipe(e, conv) {
      if (e.detail.x < -50) {
        this.swipingConvId = conv.id;
      } else if (e.detail.x > -10) {
        this.swipingConvId = null;
      }
    },
    
    /**
     * 滑动结束
     */
    handleSwipeEnd(conv) {
      // 如果滑动距离不够，自动回弹
      setTimeout(() => {
        if (this.swipingConvId === conv.id) {
          // 保持显示操作按钮
        }
      }, 100);
    },
    
    /**
     * 切换置顶状态
     */
    togglePin(conv) {
      conv.isPinned = conv.isPinned ? 0 : 1;
      
      // 保存到本地存储
      this.savePinnedConversations();
      
      // 重置滑动状态
      this.swipingConvId = null;
      
      uni.showToast({
        title: conv.isPinned ? '已置顶' : '已取消置顶',
        icon: 'success'
      });
    },
    
    /**
     * 加载置顶会话列表
     */
    loadPinnedConversations() {
      try {
        const pinned = uni.getStorageSync('pinnedConversations_' + this.userId);
        if (pinned) {
          this.pinnedConversations = JSON.parse(pinned);
        }
      } catch (e) {
        console.error('加载置顶列表失败:', e);
      }
    },
    
    /**
     * 保存置顶会话列表
     */
    savePinnedConversations() {
      try {
        const pinnedIds = this.conversations
          .filter(conv => conv.isPinned)
          .map(conv => conv.id);
        uni.setStorageSync('pinnedConversations_' + this.userId, JSON.stringify(pinnedIds));
      } catch (e) {
        console.error('保存置顶列表失败:', e);
      }
    },
    
    /**
     * 确认删除会话
     */
    confirmDeleteConversation(conv) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除该会话吗？',
        success: (res) => {
          if (res.confirm) {
            this.deleteConversationItem(conv);
          }
        }
      });
      
      // 重置滑动状态
      this.swipingConvId = null;
    },
    
    /**
     * 删除会话
     */
    async deleteConversationItem(conv) {
      try {
        // 调用 TIM SDK 删除会话
        await timManager.tim.deleteConversation(conv.id);
        
        // 从列表中移除
        const index = this.conversations.findIndex(c => c.id === conv.id);
        if (index > -1) {
          this.conversations.splice(index, 1);
        }
        
        // 重新计算总未读数（包含所有会话+系统消息）
        const allUnreadCount = this.conversations.reduce((total, c) => total + c.unreadCount, 0);
        this.totalUnread = allUnreadCount + this.systemUnread;
        
        // 同步到Vuex
        this.$store.dispatch('updateTotalUnread', this.totalUnread);
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
      } catch (e) {
        console.error('删除会话失败', e);
        uni.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    },
    
    /**
     * 格式化最后一条消息
     */
    formatLastMessage(conv) {
      if (!conv.lastMessage) {
        return '暂无消息';
      }
      
      // 限制长度
      const maxLen = 30;
      if (conv.lastMessage.length > maxLen) {
        return conv.lastMessage.substring(0, maxLen) + '...';
      }
      
      return conv.lastMessage;
    },
    
    /**
     * 格式化时间
     */
    formatTime(time) {
      if (!time) return '';
      
      const date = new Date(time);
      const now = new Date();
      const diff = now - date;
      
      // 今天
      if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit'
        });
      }
      
      // 昨天
      const yesterday = new Date(now);
      yesterday.setDate(yesterday.getDate() - 1);
      if (date.toDateString() === yesterday.toDateString()) {
        return '昨天';
      }
      
      // 本周
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return days[date.getDay()];
      }
      
      // 更早
      return date.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit'
      });
    },
    
    /**
     * 切换标签页
     */
    switchTab(tab) {
      if (tab === 'message') return;
      
      const tabPages = {
        index: '/pages/index/index',
        plaza: '/pages/plaza/index',
        recommend: '/pages/recommend/index',
        mine: '/pages/mine/index'
      };
      
      if (tabPages[tab]) {
        uni.redirectTo({
          url: tabPages[tab]
        });
      }
    }
  }
};
</script>

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

/* 顶部标题栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #F0F0F0;
  
  .header-title {
    font-size: 40rpx;
    font-weight: bold;
    color: #E91E63;
  }
  
  .header-actions {
    display: flex;
    gap: 30rpx;
    
    .action-icon {
      font-size: 40rpx;
      cursor: pointer;
    }
  }
}

/* 搜索面板 */
.search-panel {
  background-color: #FFFFFF;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #F0F0F0;
  
  .search-bar {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .search-input {
      flex: 1;
      height: 70rpx;
      padding: 0 20rpx;
      background-color: #F5F5F5;
      border-radius: 35rpx;
      font-size: 28rpx;
    }
    
    .search-cancel {
      font-size: 28rpx;
      color: #E91E63;
    }
  }
}

/* 会话列表 */
.conversation-list {
  height: calc(100vh - 200rpx);
  background-color: #FFFFFF;
}

/* 骨架屏 */
.skeleton-container {
  padding: 20rpx 0;
}

.skeleton-item {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #F5F5F5;
  
  .skeleton-avatar {
    width: 100rpx;
    height: 100rpx;
    border-radius: 12rpx;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-loading 1.5s ease-in-out infinite;
    margin-right: 25rpx;
  }
  
  .skeleton-content {
    flex: 1;
    
    .skeleton-line {
      height: 30rpx;
      border-radius: 6rpx;
      background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s ease-in-out infinite;
      
      &.skeleton-line-title {
        width: 40%;
        margin-bottom: 20rpx;
      }
      
      &.skeleton-line-text {
        width: 60%;
      }
    }
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

/* 空状态 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 150rpx 60rpx;
  
  .empty-icon-wrapper {
    width: 200rpx;
    height: 200rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40rpx;
    box-shadow: 0 20rpx 60rpx rgba(102, 126, 234, 0.3);
    animation: float 3s ease-in-out infinite;
  }
  
  .empty-icon {
    font-size: 100rpx;
    filter: brightness(1.2);
  }
  
  .empty-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 15rpx;
  }
  
  .empty-hint {
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 40rpx;
  }
  
  .empty-action {
    margin-top: 20rpx;
    
    .empty-btn {
      padding: 20rpx 60rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #FFFFFF;
      border-radius: 50rpx;
      font-size: 28rpx;
      border: none;
      box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);
      
      &::after {
        border: none;
      }
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-20rpx);
  }
}

/* 会话列表项包装器 */
.conversation-item-wrapper {
  position: relative;
  background-color: #FFFFFF;
  border-bottom: 1rpx solid #F5F5F5;
  overflow: hidden;
}

/* 系统消息高亮样式 */
.system-highlight { background: #fff7f7; }
.system-icon { font-size: 44rpx; color: #E91E63; }
.system-title { color: #E91E63; font-weight: 600; }
.system-preview { color: #d25d6b; }
.system-tag { font-size: 22rpx; color: #fff; background-color: #E91E63; padding: 4rpx 10rpx; border-radius: 8rpx; }

/* 滑动区域 */
.movable-area {
  width: 100%;
  height: 160rpx;
  position: relative;
}

.movable-view {
  width: 100%;
  height: 100%;
  background-color: #FFFFFF;
}

/* 会话列表项 */
.conversation-item {
  display: flex;
  align-items: center;
  padding: 25rpx 30rpx;
  background-color: #FFFFFF;
  position: relative;
  width: 94%;
  height: 100%;
  
  &:active {
    background-color: #F8F8F8;
  }
  
  /* 置顶标记 */
  .pinned-badge {
    position: absolute;
    top: 10rpx;
    left: 10rpx;
    font-size: 28rpx;
    opacity: 0.7;
  }
  
  .avatar-wrapper {
    position: relative;
    margin-right: 25rpx;
    
    .avatar {
      width: 100rpx;
      height: 100rpx;
      border-radius: 12rpx;
    }
    
    .online-badge {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 24rpx;
      height: 24rpx;
      background-color: #07C160;
      border: 3rpx solid #FFFFFF;
      border-radius: 50%;
    }
    
    .unread-badge {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
      min-width: 36rpx;
      height: 36rpx;
      line-height: 36rpx;
      padding: 0 8rpx;
      background-color: #FA5151;
      border-radius: 18rpx;
      font-size: 20rpx;
      color: #FFFFFF;
      text-align: center;
    }
  }
  
  .conversation-content {
    flex: 1;
    
    .content-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12rpx;
      
      .user-name {
        font-size: 32rpx;
        font-weight: 500;
        color: #333333;
      }
      
      .last-time {
        font-size: 24rpx;
        color: #999999;
      }
    }
    
    .content-bottom {
      display: flex;
      align-items: center;
      gap: 10rpx;
      
      .last-message {
        flex: 1;
        font-size: 28rpx;
        color: #999999;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        
        &.unread {
          color: #666666;
          font-weight: 500;
        }
      }
      
      .message-type-icon {
        font-size: 28rpx;
      }
    }
  }
  
  /* 右滑操作按钮 */
  .conversation-actions {
    position: absolute;
    right: 0;
    top: 0;
    height: 100%;
    display: flex;
    z-index: 1;
    
    .action-btn {
      width: 150rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #FFFFFF;
      font-size: 28rpx;
    }
    
    .pin-btn {
      background-color: #576B95;
    }
    
    .delete-btn {
      background-color: #FA5151;
    }
  }
}

.load-more {
  padding: 30rpx;
  text-align: center;
  
  .load-more-text {
    font-size: 26rpx;
    color: #999999;
  }
}

/* 底部导航栏 */
.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #FFFFFF;
  border-top: 1rpx solid #F0F0F0;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  z-index: 999;
  
  .tabbar-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 15rpx 0;
    position: relative;
    
    .tabbar-icon {
      font-size: 44rpx;
      margin-bottom: 5rpx;
    }
    
    .tabbar-text {
      font-size: 22rpx;
      color: #666666;
    }
    
    .tab-badge {
      position: absolute;
      top: 8rpx;
      right: 50%;
      margin-right: -40rpx;
      min-width: 32rpx;
      height: 32rpx;
      line-height: 32rpx;
      padding: 0 6rpx;
      background-color: #FA5151;
      border-radius: 16rpx;
      font-size: 20rpx;
      color: #FFFFFF;
      text-align: center;
    }
    
    &.active {
      .tabbar-text {
        color: #E91E63;
        font-weight: bold;
      }
    }
  }
}

/* 操作菜单 */
.action-menu {
  background-color: #FFFFFF;
  border-radius: 20rpx 20rpx 0 0;
  
  .menu-item {
    padding: 30rpx;
    text-align: center;
    font-size: 32rpx;
    color: #333333;
    border-bottom: 1rpx solid #F0F0F0;
    
    &:active {
      background-color: #F8F8F8;
    }
    
    &.cancel {
      color: #999999;
      border: none;
      margin-top: 20rpx;
    }
  }
}
</style>