var app = getApp()
var http = require('../../utils/request')
var config = require('../../config/env')

var DEFAULT_AVATAR = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI9t2NHfLvvMiaiaCJQn3KP2P0vAHp1QBP0piavhGfhKCARlGd6z1EbR58ibJXKCp5WVlNnojwA/640'

function randomNickname() {
  var digits = ''
  for (var i = 0; i < 4; i++) {
    digits += Math.floor(Math.random() * 10)
  }
  return '用户' + digits
}

Page({
  data: {
    statusBarHeight: 44,
    loading: false,
    avatarUrl: DEFAULT_AVATAR,
    nickname: '',
    phone: ''
  },

  onLoad: function () {
    this.setData({
      statusBarHeight: app.globalData.statusBarHeight,
      nickname: randomNickname()
    })
  },

  onPickAvatar: function () {
    var self = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        if (res.tempFiles && res.tempFiles[0]) {
          self.setData({ avatarUrl: res.tempFiles[0].tempFilePath })
        }
      }
    })
  },

  onNicknameInput: function (e) {
    this.setData({ nickname: e.detail.value || '' })
  },

  onNicknameBlur: function (e) {
    var val = (e.detail.value || '').trim()
    if (!val) {
      this.setData({ nickname: randomNickname() })
    } else {
      this.setData({ nickname: val })
    }
  },

  onGetPhoneNumber: function (e) {
    var self = this
    if (!e.detail || !e.detail.code) {
      wx.showToast({ title: '需要授权手机号才能完成注册', icon: 'none' })
      return
    }
    self.setData({ loading: true })
    http.post('/api/v1/user/phone', { code: e.detail.code }).then(function (data) {
      self.setData({
        loading: false,
        phone: '已授权'
      })
      wx.showToast({ title: '手机号授权成功', icon: 'success' })
    }).catch(function (err) {
      self.setData({ loading: false })
      wx.showToast({ title: err.message || '手机号授权失败', icon: 'none' })
    })
  },

  uploadAvatar: function (tempPath) {
    return new Promise(function (resolve, reject) {
      var token = wx.getStorageSync('token')
      wx.uploadFile({
        url: config.API_BASE + '/api/v1/user/avatar',
        filePath: tempPath,
        name: 'file',
        header: { Authorization: 'Bearer ' + token },
        success: function (res) {
          try {
            var data = JSON.parse(res.data)
            if (data.code === 0 && data.data && data.data.avatar) {
              resolve(data.data.avatar)
            } else {
              reject(new Error(data.message || '上传失败'))
            }
          } catch (e) {
            reject(new Error('上传失败'))
          }
        },
        fail: function () { reject(new Error('上传失败')) }
      })
    })
  },

  onSubmit: function () {
    var self = this
    var nickname = (self.data.nickname || '').trim()
    var avatarUrl = self.data.avatarUrl

    if (!self.data.phone) {
      wx.showToast({ title: '请先授权手机号', icon: 'none' })
      return
    }

    if (!nickname) {
      wx.showToast({ title: '请输入昵称', icon: 'none' })
      return
    }

    self.setData({ loading: true })

    var avatarPromise = (avatarUrl && avatarUrl !== DEFAULT_AVATAR)
      ? self.uploadAvatar(avatarUrl)
      : Promise.resolve('')

    avatarPromise.then(function (permanentUrl) {
      return http.put('/api/v1/user/profile', {
        nickname: nickname,
        avatar: permanentUrl || ''
      })
    }).then(function () {
      return app.loadProfile()
    }).then(function () {
      self.setData({ loading: false })
      wx.switchTab({ url: '/pages/index/index' })
    }).catch(function (err) {
      self.setData({ loading: false })
      wx.showToast({ title: err.message || '保存失败', icon: 'none' })
    })
  },

  onAgreement: function () {
    wx.showModal({ title: '提示', content: '用户协议和隐私政策内容建设中', showCancel: false })
  }
})
