// 搜索用户页面
const app = getApp();
const friendAPI = require('../../../utils/friend-api.js');

Page({
  data: {
    // 搜索相关
    searchKeyword: '',
    searchResults: [],
    loading: false,
    hasSearched: false,
    
    // 搜索类型
    searchType: 'all', // all, nickname, custom_id, phone
    searchTypes: [
      { value: 'all', label: '全部' },
      { value: 'nickname', label: '昵称' },
      { value: 'custom_id', label: 'ID' },
      { value: 'phone', label: '手机号' }
    ],
    
    // 分页
    currentPage: 1,
    pageSize: 20,
    hasMore: true,
    
    // 系统信息
    statusBarHeight: 0,
    navBarHeight: 0
  },

  onLoad(options) {
    console.log('搜索用户页面加载');
    this.initSystemInfo();
    
    // 如果有传入的搜索关键词，直接搜索
    if (options.keyword) {
      this.setData({
        searchKeyword: decodeURIComponent(options.keyword)
      });
      this.performSearch();
    }
  },

  // 初始化系统信息
  initSystemInfo() {
    try {
      // 使用新的API替代已弃用的wx.getSystemInfoSync
      const windowInfo = wx.getWindowInfo();
      const menuButton = wx.getMenuButtonBoundingClientRect();
      
      this.setData({
        statusBarHeight: windowInfo.statusBarHeight,
        navBarHeight: menuButton.bottom + 10
      });
    } catch (error) {
      console.error('获取系统信息失败，使用兜底方案:', error);
      // 兜底方案
      try {
        const systemInfo = wx.getSystemInfoSync();
        const menuButton = wx.getMenuButtonBoundingClientRect();
        
        this.setData({
          statusBarHeight: systemInfo.statusBarHeight,
          navBarHeight: menuButton.bottom + 10
        });
      } catch (fallbackError) {
        console.error('兜底方案也失败了:', fallbackError);
        // 设置默认值
        this.setData({
          statusBarHeight: 44,
          navBarHeight: 88
        });
      }
    }
  },

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

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 搜索确认
  onSearchConfirm() {
    this.performSearch();
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchKeyword: '',
      searchResults: [],
      hasSearched: false,
      currentPage: 1,
      hasMore: true
    });
  },

  // 切换搜索类型
  onSearchTypeChange(e) {
    const searchType = e.currentTarget.dataset.type;
    this.setData({
      searchType
    });
    
    if (this.data.searchKeyword) {
      this.performSearch();
    }
  },

  // 执行搜索
  async performSearch() {
    const keyword = this.data.searchKeyword.trim();
    if (!keyword) {
      wx.showToast({
        title: '请输入搜索关键词',
        icon: 'none'
      });
      return;
    }

    this.setData({
      loading: true,
      currentPage: 1,
      searchResults: [],
      hasMore: true
    });

    try {
      const response = await friendAPI.searchUsers(
        keyword,
        this.data.searchType,
        1,
        this.data.pageSize
      );

      // 根据正确的接口文档处理API响应结构
      const searchData = response.data || {};
      const users = searchData.users || [];
      const total = searchData.total || 0;
      
      this.setData({
        searchResults: users,
        hasSearched: true,
        hasMore: users.length >= this.data.pageSize && this.data.currentPage * this.data.pageSize < total,
        loading: false
      });

      if (users.length === 0) {
        wx.showToast({
          title: '未找到相关用户',
          icon: 'none'
        });
      }

    } catch (error) {
      console.error('搜索失败:', error);
      this.setData({
        loading: false,
        hasSearched: true
      });
      
      wx.showToast({
        title: error.message || '搜索失败',
        icon: 'none'
      });
    }
  },

  // 加载更多
  async loadMore() {
    if (!this.data.hasMore || this.data.loading) return;

    this.setData({ loading: true });

    try {
      const response = await friendAPI.searchUsers(
        this.data.searchKeyword,
        this.data.searchType,
        this.data.currentPage + 1,
        this.data.pageSize
      );

      const searchData = response.data || {};
      const newUsers = searchData.users || [];
      const total = searchData.total || 0;
      const newResults = [...this.data.searchResults, ...newUsers];
      
      this.setData({
        searchResults: newResults,
        currentPage: this.data.currentPage + 1,
        hasMore: newResults.length < total,
        loading: false
      });

    } catch (error) {
      console.error('加载更多失败:', error);
      this.setData({ loading: false });
    }
  },

  // 添加好友
  async addFriend(e) {
    const { customId, nickname } = e.currentTarget.dataset;
    
    try {
      // 显示输入框让用户输入验证消息
      const result = await this.showAddFriendDialog(nickname);
      if (!result.confirm) return;

      wx.showLoading({ title: '发送中...' });

      await friendAPI.addFriend(customId, result.message);

      wx.hideLoading();
      wx.showToast({
        title: '好友请求已发送',
        icon: 'success'
      });

      // 更新按钮状态
      const updatedResults = this.data.searchResults.map(user => {
        if (user.customId === customId) {
          return {
            ...user,
            relationStatus: 'pending',
            actionText: '等待验证',
            canAddFriend: false
          };
        }
        return user;
      });

      this.setData({
        searchResults: updatedResults
      });

    } catch (error) {
      wx.hideLoading();
      console.error('添加好友失败:', error);
      wx.showToast({
        title: error.message || '添加好友失败',
        icon: 'none'
      });
    }
  },

  // 显示添加好友对话框
  showAddFriendDialog(nickname) {
    return new Promise((resolve) => {
      wx.showModal({
        title: `添加 ${nickname} 为好友`,
        editable: true,
        placeholderText: '请输入验证消息',
        content: `我是 ${app.globalData.userInfo?.user?.nickname || ''}`,
        success: (res) => {
          resolve({
            confirm: res.confirm,
            message: res.content || `我是 ${app.globalData.userInfo?.user?.nickname || ''}`
          });
        },
        fail: () => {
          resolve({ confirm: false });
        }
      });
    });
  },

  // 查看用户详情
  viewUserDetail(e) {
    const { customId } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/social/user-detail/user-detail?customId=${customId}`
    });
  },

  // 发送消息
  sendMessage(e) {
    const { customId, nickname } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/message/chat/chat?targetId=${customId}&name=${encodeURIComponent(nickname)}&chatType=0`
    });
  }
});
