import store from '../../../store'
import create from '../../../utils/create'
import fetch from '../../../utils/http'
import { get as getApi } from '../../../config/api'

const app = getApp()

create(store, {
  data: {
    UserInfo: {}, // 用户信息
  },
  onReady() {
    wx.setNavigationBarTitle({
      title: '个人资料'
    })
  },
  onLoad () {
    this.setData({
      UserInfo: app.globalData.UserInfo
    })
  },
  SaveUserInfo() { // 提交表单数据
    fetch({ ...getApi('user.update'), data: this.data.UserInfo }).then(() => {
      // 同步到 globalData
      app.globalData.UserInfo = { ...this.data.UserInfo }

      wx.showToast({
        title: '更新成功',
        icon: 'success',
      })
    }).catch((err) => {
      wx.showToast({
        title: '更新失败',
        icon: 'error',
      })
    })
  },
  FormInput(e) { // 表单输入数据绑定
    const key = e.target.dataset.name
    const val = e.detail.value
    
    this.setData({
      UserInfo: {
        ...this.data.UserInfo,
        [`${key}`]: val,
      }
    })
  }
})
