// pages/personinfo/personinfo.js
import userApi from '../../api/user'
import uploadApi from '../../api/upload'
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    endDate: "",
    birth: "",
    sex: 0,
    array: ["未知", "男", "女"],
    userName: "",
    imgUrl: "",
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    //设置标题栏的高度
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        console.log(res.statusBarHeight)
        that.setData({
          statusBarHeight: res.statusBarHeight
        })
      },
    })
    //设置结束日期为今日
    var d = new Date();
    var endDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
    this.setData({
      endDate
    })
    let userInfo = await app.getWxUserInfo();
    let userId = userInfo.userId;
    let user = await userApi.getUserById(userId);
    let birth = user.info.birthday;
    birth == "" ? '1970-01-01' : birth;
    console.log(user)
    this.setData({
      sex: userInfo.gender,
      imgUrl: user.info.avatar,
      userName: user.info.name,
      birth: birth
    })

  },

  changeUserName: function (e) {
    this.setData({
      userName: e.detail.value
    })
  },
  changeBirth: function (e) {
    this.setData({
      birth: e.detail.value
    })
  },
  changeSex: function (e) {
    console.log(e.detail)
    this.setData({
      sex: e.detail.value
    })
  },
  upload: async function () {
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9      
      sizeType: ['original', 'compressed'],
      // 指定是原图还是压缩图，默认两个都有      
      sourceType: ['album', 'camera'],
      // 指定来源是相册还是相机，默认两个都有    
      success: async function (res) {
        // 返回选定照片的本地文件路径tempFilePath可以作为img标签的src属性显示图片 
        var imgUrl = await uploadApi.uploadAvatar(res.tempFilePaths[0]);
        _this.setData({
          imgUrl: imgUrl
        })
      }
    })
  },
  updateUser: async function () {
    var name = this.data.userName;
    var birthDay = this.data.birth;
    var avatar = this.data.imgUrl;
    var sex = this.data.sex;
    var userInfo = await app.getWxUserInfo();
    userInfo.name = name;
    userInfo.birthday = birthDay;
    userInfo.avatar = avatar;
    userInfo.sex = sex;
    wx.setStorage({
      data: userInfo,
      key: 'userInfo',
    })
    await userApi.updateUserInfo(name, birthDay, avatar, sex);
    wx.switchTab({

      url: '/pages/person/person',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: async function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})