import { client } from "../../../utils/api";
import { updateuserinfo, userInfo } from "../../../utils/request";

Page({
  data: {
    userinfo: {
      nickname: '创作小助手',
      id: '10010',
      avatar: 'https://cdn.zhuangb123.com/avatar/boy/a2cfe723-98ddc-12de-723b8f51b-71b1e3.jpeg',
      description: 'AI 创作，让想象力触手可及 ✨'
    },
    oldAvatar: '',
    newAvatar: ''
  },

  onLoad() {
    this.setData({ userinfo: wx.getStorageSync('userInfo') });
  },

  handleBack() {
    wx.navigateBack({
      fail: () => wx.switchTab({ url: '/pages/my/my' }),
    })
  },
  handleChangeAvatar() {
    let that = this
    wx.chooseImage({
      count: 1,
      success(res) {
        let userInfo = that.data.userinfo;
        let oldAvatar = userInfo.avatar;
        userInfo.avatar = res.tempFilePaths[0];

        that.setData({
          userinfo: userInfo,
          oldAvatar: oldAvatar
        })
      }
    });
  },
  handleNicknameInput(e: any) {
    let userinfo = this.data.userinfo;
    userinfo.nickname = e.detail.value;
    this.setData({
      userinfo: userinfo,
    })
  },
  handleSave() {
    let nickname = this.data.userinfo;
    if (nickname.nickname.length < 2) {
      wx.showToast({ title: '昵称至少2个字符', icon: 'none' })
      return
    }

    let that = this;
    let update = () => {
      updateuserinfo(nickname.nickname, nickname.avatar).then((res: any) => {
        if (!res.code) {
          userInfo().then((res: any) => {
            wx.setStorageSync('userInfo', res.data);

            that.setData({ userinfo: res.data });
          })
        }
      })
    }
    if (this.data.userinfo.avatar.indexOf('http://tmp/') === -1) {
      update();
      return;
    }

    client.upload(this.data.userinfo.avatar, {}).then((res: any) => {
      if (res.code == 0) {
        nickname.avatar = res.data.url;
        update();
      } else {
        wx.showModal({ title: '温馨提示', content: '头像上传失败' })
      }
    })
  },
})
