// 好友详情页面
const app = getApp();
const friendAPI = require('../../../utils/friend-api.js');
const { initPageSystemInfo } = require('../../../utils/system-info-modern.js');

Page({
  data: {
    // 好友信息
    friendInfo: null,
    loading: true,
    
    // 系统信息
    statusBarHeight: 0,
    navBarHeight: 0,
    
    // 操作状态
    isDeleting: false
  },

  onLoad(options) {
    console.log('好友详情页面加载:', options);
    
    // 初始化系统信息
    this.initSystemInfo();
    
    // 获取好友ID
    const customId = options.customId;
    if (customId) {
      this.loadFriendDetail(customId);
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 初始化系统信息
  initSystemInfo() {
    const pageSystemInfo = initPageSystemInfo();
    this.setData({
      statusBarHeight: pageSystemInfo.statusBarHeight,
      navBarHeight: pageSystemInfo.navBarHeight
    });
  },

  // 加载好友详情
  async loadFriendDetail(customId) {
    try {
      this.setData({ loading: true });
      
      console.log('🔥 加载好友详情:', customId);
      const response = await friendAPI.getFriendDetail(customId);
      
      if (response && response.code === 0) {
        const friendInfo = response.data;
        console.log('✅ 获取好友详情成功:', friendInfo);
        
        this.setData({
          friendInfo: friendInfo,
          loading: false
        });
      } else {
        throw new Error(response?.message || '获取好友详情失败');
      }
      
    } catch (error) {
      console.error('❌ 加载好友详情失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 发送消息
  sendMessage() {
    const { friendInfo } = this.data;
    if (!friendInfo) return;
    
    console.log('💬 发送消息给:', friendInfo.nickname);
    
    // 跳转到聊天页面
    const currentUserId = app.globalData.userInfo?.user?.customId || '';
          // 🔥 修复：不传递conversationId，让聊天页面从API获取正确的会话ID
    
          wx.navigateTo({
        url: `/pages/message/chat/chat?targetId=${friendInfo.customId}&name=${encodeURIComponent(friendInfo.nickname)}&chatType=0`
      });
  },

  // 视频通话
  videoCall() {
    const { friendInfo } = this.data;
    if (!friendInfo) return;
    
    console.log('📹 视频通话:', friendInfo.nickname);
    wx.showToast({
      title: '视频通话功能开发中',
      icon: 'none'
    });
  },

  // 设置备注
  setRemark() {
    const { friendInfo } = this.data;
    if (!friendInfo) return;
    
    wx.showModal({
      title: '设置备注',
      editable: true,
      placeholderText: '请输入备注名',
      content: friendInfo.remark || '',
      success: async (res) => {
        if (res.confirm && res.content !== friendInfo.remark) {
          try {
            wx.showLoading({ title: '设置中...' });
            
            // 这里需要调用更新好友备注的API
            // await friendAPI.updateFriendRemark(friendInfo.customId, res.content);
            
            // 更新本地数据
            this.setData({
              'friendInfo.remark': res.content
            });
            
            wx.hideLoading();
            wx.showToast({
              title: '设置成功',
              icon: 'success'
            });
            
          } catch (error) {
            wx.hideLoading();
            wx.showToast({
              title: '设置失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 删除好友
  deleteFriend() {
    const { friendInfo } = this.data;
    if (!friendInfo) return;
    
    wx.showModal({
      title: '删除好友',
      content: `确定要删除好友"${friendInfo.nickname}"吗？删除后将无法收到对方消息。`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: async (res) => {
        if (res.confirm) {
          try {
            this.setData({ isDeleting: true });
            wx.showLoading({ title: '删除中...' });
            
            console.log('🗑️ 删除好友:', friendInfo.customId);
            await friendAPI.deleteFriend(friendInfo.customId);
            
            wx.hideLoading();
            wx.showToast({
              title: '已删除好友',
              icon: 'success'
            });
            
            // 延迟返回并刷新好友列表
            setTimeout(() => {
              // 通知好友页面刷新
              const pages = getCurrentPages();
              const friendsPage = pages.find(page => page.route === 'pages/social/friends/friends');
              if (friendsPage && friendsPage.loadFriends) {
                friendsPage.loadFriends();
              }
              
              wx.navigateBack();
            }, 1000);
            
          } catch (error) {
            console.error('❌ 删除好友失败:', error);
            wx.hideLoading();
            this.setData({ isDeleting: false });
            
            wx.showToast({
              title: error.message || '删除失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 更多操作
  showMoreActions() {
    const { friendInfo } = this.data;
    if (!friendInfo) return;
    
    const actions = ['设置备注', '删除好友'];
    
    wx.showActionSheet({
      itemList: actions,
      success: (res) => {
        switch(res.tapIndex) {
          case 0:
            this.setRemark();
            break;
          case 1:
            this.deleteFriend();
            break;
        }
      }
    });
  },

  // 查看位置
  viewLocation() {
    const { friendInfo } = this.data;
    if (!friendInfo || !friendInfo.locationInfo) {
      wx.showToast({
        title: '暂无位置信息',
        icon: 'none'
      });
      return;
    }
    
    const { locationInfo } = friendInfo;
    wx.openLocation({
      latitude: locationInfo.latitude,
      longitude: locationInfo.longitude,
      name: friendInfo.nickname,
      address: locationInfo.address || '未知位置'
    });
  }
});