const api = require('../../config/api')
const util = require('../../utils/util')
const upload = require('../../utils/upload')

Page({
  data: {
		userInfo: {}
  },

	onShow() {
		this.getUserInfo()
	},

	getUserInfo() {
		util.showLoad('加载中')
    util.request(api.UserInfo).then(res => {
      util.hideLoad()
      if (res.errno === 0) {
				wx.setStorageSync('userInfo', res.data)
				this.setData({ userInfo: res.data })
      } else util.showToast(res.errmsg)
    }).catch(() => {
      util.hideLoad()
      util.showErrorToast('网络连接失败')
    })	
	},

	// 更新头像
	updateUser(avatar) {
		util.request(api.UserUpdate, { id: this.data.userInfo.id, avatar }, 'POST').then(res => {
			util.hideLoad()
			if (res.errno === 0) this.getUserInfo()
			else util.showErrorToast(res.errmsg)
		}).catch(() => {
			util.hideLoad()
			util.showErrorToast('网络连接失败')
		})
	},

	// 更换头像
	chooseMedia() {
		const that = this
		wx.chooseMedia({
			count: 1,
			mediaType: ['image'],
			success: async suc => {
				try {
					util.showLoad('上传中')
					const filePath = suc.tempFiles[0].tempFilePath
					const url = await upload.uploadImage(filePath)
					that.updateUser(url)
				} catch (error) {
					util.hideLoad()
					util.showErrorToast(error)
				}
			},
			fail: () => {
				util.hideLoad()
				util.showToast('已取消')
			}
		})
	},
	
  // 退出登录
  logout() {
    wx.showModal({
      confirmColor: '#D32D2F',
      content: '确定退出登录吗？',
      success: res => {
        if (res.confirm) {
          util.request(api.Logout, {}, 'POST')
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          wx.reLaunch({ url: '/pages/index/index' })
        }
      }
    })
  }
})