const friendAPI = require('../../utils/friend-api.js');

Page({
  data: {
    remark: '',
    nickname: '',
    friendId: ''
  },
  onLoad(options) {
    // 接收参数
    const nickname = options.nickname ? decodeURIComponent(options.nickname) : '';
    const friendId = options.friendId ? decodeURIComponent(options.friendId) : (options.customId ? decodeURIComponent(options.customId) : '');
    const remark = options.remark ? decodeURIComponent(options.remark) : '';
    
    this.setData({
      nickname: nickname,
      friendId: friendId,
      remark: remark
    });
  },
  onRemarkInput(e) {
    this.setData({ remark: e.detail.value });
  },
  async onSaveRemark() {
    const { remark, friendId } = this.data;
    
    if (!friendId) {
      wx.showToast({ title: '参数错误', icon: 'none' });
      return;
    }
    
    wx.showLoading({ title: '保存中...', mask: true });
    
    try {
      const response = await friendAPI.updateFriendRelation(friendId, { remark: remark });
      
      if (response && (response.code === 0 || response.code === 200 || response.code === '0' || response.code === '200')) {
        // 更新上一页的好友信息
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        if (prevPage && prevPage.setData) {
          prevPage.setData({ 'friendInfo.remark': remark });
        }
        
        wx.hideLoading();
        wx.showToast({ title: '保存成功', icon: 'success' });
        setTimeout(() => wx.navigateBack(), 1500);
      } else {
        throw new Error(response.message || '保存失败');
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({ title: error.message || '保存失败', icon: 'none' });
    }
  }
})
