import {userModify} from '../../api/user';
import { uploadImage } from '../../utils/upload.js';
const app = getApp();
Page({
  data: {
    userInfo:{},
    pathUrl:'',//保存接口需要传的值
  },
  onLoad(options) {
    this.setData({
      userInfo: app.globalData.userInfo
    });
  },
  // 昵称
  onInputChange(e) {
    this.setData({
      "userInfo.nickname": e.detail.value
    })
  },
  // 头像
  async onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    // 上传到服务器
    const res = await uploadImage(avatarUrl);
    this.setData({
      "userInfo.avatar":avatarUrl,
      pathUrl: res.path
    });
  },
  async getPhoneNumber(e) {
    if (e.detail.errMsg === "getPhoneNumber:ok") {
      const { encryptedData, iv } = e.detail;
      console.log('加密手机号数据:', encryptedData, iv);
      const res = await userModify({phone:{
        encryptedData,
        iv
      }});
      this.setData({
        "userInfo.phone":res.data.phone,
      });
    } else {
      wx.showToast({ title: '授权失败', icon: 'none' });
    }
  },
  async onSave(){
    let params = {
      nickname:this.data.userInfo.nickname,
      avatar:this.data.pathUrl
    }
    const res = await userModify(params);
    if(res.code == 200){
      wx.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 2000
      });
      app.globalData.userInfo = res.data;
    }else{
      wx.showToast({
        title: res.message || '保存失败',
        icon: 'none',
        duration: 2000
      });
    }
  }
})