// 临时用户资料预览页（扫码非好友进入）
const friendAPI = require('../../../utils/friend-api.js');
const apiClient = require('../../../utils/api-client.js');
const app = getApp();

Page({
  data:{
    customId:'',
    user:{},
    loading:true,
    error:'',
    relationStatus:'',
    showAddButton:false,
    privacyBlocked:false,
    blockedRelation:false,
    statusAdd:0 //  0 不是好友 1 已发送添加好友申请 2 已好友
  },
  onLoad(query){
    const  customId  = (query?.customId || '10703945')+"" ;
    if(!customId){
      this.setData({ error:'缺少用户ID', loading:false });
      return;
    }
    this.setData({ customId });
    this.loadUser(customId);
  },
  async loadUser(customId){
    this.setData({ loading:true, error:'' });
    try{
      // 使用新的接口 /user/info/{customId} 获取用户信息
      const response = await apiClient.getUserInfoByCustomId(customId);
      
      if(!response || response.code !== 0 || !response.data){
        this.setData({ error:'用户不存在', loading:false });
        return;
      }

      const user = response.data;
      console.log('✅ 获取用户信息成功:', user);

      // 处理关系状态
      let relationStatus = user.relationStatus || 'can_add';
      if(!relationStatus){
        relationStatus = 'can_add'; // 未提供时默认可添加
      }

      // 处理年龄：优先使用接口返回的 age，如果没有则根据 birthday 计算
      let calculatedAge = user.age;
      if(!calculatedAge && user.birthday){
        calculatedAge = this.calculateAge(user.birthday);
      }

      // 处理家乡地址：将数组转换为字符串
      let hometownText = '';
      if (user.hometown) {
        if (Array.isArray(user.hometown)) {
          hometownText = user.hometown.filter(item => item).join(' ');
        } else if (typeof user.hometown === 'string') {
          hometownText = user.hometown;
        }
      }

      // 判断是否显示添加好友按钮和状态
      // 根据 relationStatus 判断：
      // - "self": 自己，不显示添加按钮
      // - "friend": 已是好友，statusAdd = 2
      // - "pending": 已发送申请，statusAdd = 1
      // - 其他: 可添加，statusAdd = 0
      let showAddButton = false;
      let statusAdd = 0;
      
      if (relationStatus === 'self') {
        // 自己，不显示添加按钮
        showAddButton = false;
        statusAdd = 0;
      } else if (relationStatus === 'friend') {
        // 已是好友
        showAddButton = false;
        statusAdd = 2;
      } else if (relationStatus === 'pending' || relationStatus === 'requested') {
        // 已发送申请
        showAddButton = false;
        statusAdd = 1;
      } else {
        // 可以添加好友
        showAddButton = true;
        statusAdd = 0;
      }

      console.log('👀 用户预览信息:', {
        relationStatus,
        showAddButton,
        statusAdd,
        calculatedAge,
        hometownText
      });

      this.setData({
        user: user,  // 使用完整的用户数据对象
        relationStatus,
        showAddButton,
        privacyBlocked: relationStatus === 'privacy_limited',
        blockedRelation: relationStatus === 'blocked',
        calculatedAge: calculatedAge,
        hometownText: hometownText,
        loading: false,
        statusAdd: statusAdd
      });
    }catch(e){
      console.error('❌ 加载用户失败:', e);
      let errorMessage = '加载失败';
      if(e.message){
        errorMessage = e.message;
      } else if(e.errMsg){
        errorMessage = e.errMsg;
      }
      this.setData({ error: errorMessage, loading:false });
    }
  },
  reload(){
    if(this.data.customId){ this.loadUser(this.data.customId); }
  },
  async addFriend(){
    if(!this.data.user.customId) return;
    try{
      const dialogRes = await this.showAddFriendDialog(this.data.user.nickname||this.data.user.customId);
      if(!dialogRes.confirm) return;
      wx.showLoading({ title:'发送中...' });
      const  frienRes  = await friendAPI.addFriend(this.data.user.customId, dialogRes.message);
      console.log('frienRes -------frienRes ',frienRes);
      wx.hideLoading();
      wx.showToast({ title:'请求已发送', icon:'success' });
      this.setData({ relationStatus:'pending', showAddButton:false,statusAdd:1 });
    }catch(e){
      wx.hideLoading();
      wx.showToast({ title:e.message||'发送失败', icon:'none' });
    }
  },
  goChat(){
    const { user } = this.data;
    if(!user.customId) return;
    wx.navigateTo({ url:`/pages/message/chat/chat?targetId=${user.customId}&name=${encodeURIComponent(user.nickname||'好友')}&chatType=0` });
  },


  previewImage(e) {
    try {
      // 获取当前点击的图片索引和动态索引
      const avatar = e.currentTarget.dataset.avatar;
      // 🔥 设置标志，防止预览关闭后触发页面刷新
      this._skipNextOnShowReload = true;
      const imageUrls=[avatar];
      // 调用微信小程序的图片预览API
      wx.previewImage({
        current: avatar,
        urls: imageUrls,
        success: () => {
          // 预览打开成功，标志已设置，关闭时会触发 onShow
        },
        fail: (err) => {
          console.error('图片预览失败:', err);
          // 预览失败，清除标志
          this._skipNextOnShowReload = false;
          wx.showToast({
            title: '预览图片失败',
            icon: 'none'
          });
        }
      });
    } catch (error) {
      console.error('图片预览过程中出错:', error);
      // 出错时清除标志
      this._skipNextOnShowReload = false;
      wx.showToast({
        title: '预览图片失败',
        icon: 'none'
      });
    }
  },

  // 发送消息（与 goChat 功能相同）
  sendMessage() {
    const { user } = this.data;
    if (!user || !user.customId) {
      wx.showToast({
        title: '用户信息不存在',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/message/chat/chat?targetId=${user.customId}&name=${encodeURIComponent(user.nickname || user.customId || '好友')}&chatType=0`
    });
  },
  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 })
      });
    });
  },

  // 根据生日计算年龄
  calculateAge(birthday) {
    if (!birthday) {
      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())) {
        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
      return age >= 0 ? age : null;
    } catch (error) {
      console.error('计算年龄失败:', error, birthday);
      return null;
    }
  },

  // 复制ID
  copyId() {
    const { user } = this.data;
    const id = user?.customId || (user?.id ? 'findme_' + user.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'
        });
      }
    });
  },

  // 跳转到二维码页面
  navigateToQRCode() {
    const { user } = this.data;
    if (!user || !user.customId) {
      wx.showToast({
        title: '用户信息不存在',
        icon: 'none'
      });
      return;
    }
    
    // 传递陌生人的 customId 参数
    wx.navigateTo({
      url: `/subpackages/qr/qr-code/qr-code?customId=${user.customId}`,
      success: (res) => {
        console.log('跳转二维码页面成功', res);
      },
      fail: (err) => {
        console.error('跳转二维码页面失败', err);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  }
});
