// pages/user/user.js
const api = require('../../config/api.js');
const util = require('../../utils/util.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    birthday: '',
    region: [],
    customItem: '全部',
    gender: 0,
    mobile: null
  },

  async getPhoneNumber(e) {
    let {encryptedData,iv} =  e.detail
    if (!encryptedData) return;
    let res = await util.request(api.decryptedPhoneNum, { encryptedData,iv, sessionKey: this.sessionKey })

    console.log(res)
    this.setData({
      mobile: res.phoneNum
    })
  },


  updateMobile(ev) {
    this.setData({mobile: ev.detail.value})
  },

  updateNickName(ev) {
    this.setData({nickname: ev.detail.value})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo()
    let userInfo = wx.getStorageSync('userInfo')
    userInfo.avatar = userInfo.avatarUrl
    this.sessionKey = userInfo.sessionKey
    delete userInfo.avatarUrl

    this.setData({ ...userInfo })
  },


  loginSuccess() {
    this.onLoad()
  },
  async getUserInfo() {
    const {data} = await util.request(api.UserInfo)
    data.region = data.city ? data.city.split('，') : []
    data.birthday = data.birthday || '1990-01-01'
    this.setData({
      ...data
    })
  },

  updateSex(e) {
    this.setData({gender: e.currentTarget.dataset.sex})
  },

  bindDateChange(e) {
    this.setData({ birthday: e.detail.value })
  },

  bindRegionChange (e) {
    this.setData({ region: e.detail.value })
  },

  selectPhoto() {
    wx.chooseImage({
      count: 1,
      sizeType: 'compressed',
      success: (res) => {
        const src = res.tempFilePaths[0]
        // this.file = res.tempFiles[0]
        wx.navigateTo({
          url: './imageCropper?image=' + src,
        })
        // this.setData({ avatar: src })
      }
    })
  },

  async save() {
    console.log(this.file)
    if (this.file) {
      let avatar = await (new Promise(r => {
        wx.uploadFile({
          filePath: this.data.avatar,
          name: 'file',
          url: api.UploadFile,
          header: {'X-Nideshop-Token': wx.getStorageSync('token')},
          success: (res) => {
            this.file = null
            r(JSON.parse(res.data).data)
          }
        })
      }));

      this.data.avatar = avatar
    }

    this.data.city = this.data.region && this.data.region.join('，')
    const body = {...this.data}
    delete body.region
    const {data} = await util.request(api.UpdateUserInfo, body, 'POST', 'application/json')
    wx.navigateBack()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

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

  },

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

  },

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

  },

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

  },

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

  }
})