// pages/me/profile/index.js
import api from '../../../utils/Api.js'
import Schedule from '../../../utils/Schedule.js'
import Wx from '../../../utils/Wx.js'
const {
  $Toast
} = require('../../../iview/base/index');
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    user: {},

    nickname: '',
    genders: ["男", "女"],
    gender: 0,
    phone: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.setData({
      user: app.globalData.userInfo,
      gender: app.globalData.userInfo.gender,
      phone: app.globalData.userInfo.phone
    })
  },

  handlePhoneAuth: function(event) {
    Wx.login().then(res => {
      let encryptedData = event.detail.encryptedData
      let iv = event.detail.iv
      this.decodePhoneData(res.code, encryptedData, iv)
    })
  },

  /**
   * 解密手机号数据
   */
  decodePhoneData: function(code, encryptedData, iv) {
    let that = this
    api.getPhoneNumber({
      code: code,
      encryptedData: encryptedData,
      iv: iv
    }).then(res => {
      if (!res.code) {
        $Toast({
          content: '手机号授权成功',
          type: 'success'
        });
        this.setData({
          phone: res.data.phone
        })
      } else {
        $Toast({
          content: '手机号授权失败',
          type: 'error'
        });
      }
    })
  },

  handleNickname: function(event) {
    this.setData({
      nickname: event.detail.value
    })
  },

  handleGenderChange: function(event) {
    this.setData({
      gender: parseInt(event.detail.value) + 1
    })
  },

  // 保存资料
  handleSubmit: function() {
    api.me.update({
      nickname: this.data.nickname,
      gender: parseInt(this.data.gender),
      avatar: this.data.user.avatar
    }).then(res => {
      $Toast({
        content: res.msg,
        type: !res.code ? 'success' : 'error'
      });
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1200)
    })
  },

  /**
   * 选择头像控件触发事件
   */
  chooseAvatar: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        api.me.uploadAvatar("avatar", res.tempFilePaths[0]).then(res => {
          // 这里为什么需要自己转JSON呢？？？
          res = JSON.parse( res )
          $Toast({
            content: res.msg,
            type: 'success'
          })
          if (!res.code) {
            let user = that.data.user
            user.avatar = res.avatar_url
            that.setData({
              user: user
            })
          }
        })
      }
    })
  }
})