<template>
	<view class="modifyWrapper">
		<form>
			<view class="uni-forms-item">
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="userinfo.avatar"></image>
				</button>
			</view>
			<view class="uni-forms-item">
				<input type="text" class="alias-input" maxlength="6" v-model="userinfo.alias" />
			</view>
			<view class="uni-forms-item">
				<button form-type="submit" class="alias-submit" type="primary" @click="formSubmit">确认修改</button>
			</view>
			<view class="uni-forms-item">
				<button class="alias-submit" type="primary" @click="forExit">退出登录</button>
			</view>
		</form>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'

	export default {
		computed: {
			...mapState('m_user', ['userinfo'])
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken']),
			// 选择头像
			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.userinfo.avatar = avatarUrl
			},
			formSubmit() {
				// 上传头像
				wx.uploadFile({
					url: uni.$http.baseUrl + '/file/uploading',
					filePath: this.userinfo.avatar,
					name: 'file',
					header: {
						'token': uni.getStorageSync('token')
					},
					success: res => {
						const result = JSON.parse(res.data)
						this.userinfo.avatar = result.data.url
						// 表单提交
						this.sendFormData()
					},
					fail: res => {
						if (res.errMsg === 'uploadFile:fail createUploadTask:fail file not found') {
							// 表单提交
							this.sendFormData()
						} else {
							uni.$showMsg('修改头像失败，请重新选择')
						}
					}
				})
			},
			// 表单提交
			sendFormData() {
				wx.request({
					url: uni.$http.baseUrl + '/ucenter/mini-program-openid-uid/wxAlias',
					method: 'GET',
					data: {
						alias: this.userinfo.alias,
						avatar: this.userinfo.avatar
					},
					header: {
						'token': uni.getStorageSync('token') // 默认值
					},
					success: res1 => {
						uni.$showMsg('修改成功！', 3000)
						// 更新成功
						// 将数据更新到vuex中
						this.updateUserInfo(this.userinfo)
					}
				})
			},
			forExit() {
				this.updateToken("")
				// 跳转个人信息页面
				uni.switchTab({
					url: '/pages/my/my'
				})
			}
		}
	}
</script>

<!-- 设置页面背景 -->
<style lang="scss">
	page{
		height: 100%;
		padding: 0 20rpx;
		// background-color: #FFF;
	}
</style>

<style lang="scss" scoped>
	.modifyWrapper{
		width: 95%;
		height: 100%;
	}
	.alias-input {
		height: 100rpx;
		font-size: 40rpx;
		// border: 1px solid #aaa;
		border-radius: 30rpx;
		padding-left: 10rpx;
		margin-top: 20rpx;
		background-color: white;
	}

	.alias-submit {
		margin-top: 50rpx;
		width: 300rpx;
		border-radius: 50rpx;
		background-color: #35b882;
	}
</style>
