<template>
	<view class="content">
		<uni-list>
			<uni-list-item>
				<template v-slot:body>
					<view class="avatar-box">
						<image class="avatar-img" :src="(userInfo && userInfo.avatar) || '/static/uni-center/logo.png'" @click="chooseImg" mode="aspectFill"></image>
					</view>
				</template>
			</uni-list-item>
			<uni-list-item title="姓名" :right-text="userInfo && userInfo.name"></uni-list-item>
		</uni-list>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	
	const db = uniCloud.database();
	const userTable = db.collection('uni-id-users')
	export default {
		data() {
			return {
				
			}
		},
		computed: {
			...mapGetters({
				userInfo: 'user/info'
			})
		},
		onLoad() {
			if(!this.userInfo)console.error('判断登录状态,如果没有登录则没有userinfo,页面报错');
		},
		methods: {
			...mapMutations({
				login:'user/login'
			}),
			// 选择图片
			chooseImg(){
				uni.chooseImage({
					count:1,
					success:(res)=> {
						
						uni.$on('uploadAvatarAfter', ({url})=>{
							console.log(url);
							this.uploadUserInfo({avatar:url});
						})
						let options = {
							width:600,
							height:600
						}
						uni.navigateTo({
							url:'./uploadCutImageToUnicloud?path=' + res.tempFilePaths[0] + `&options=${JSON.stringify(options)}`,
							animationType:"fade-in"
						});
					}
				})
			},
			/**
			 * @param {Object} data 更新用户信息
			 * key 需要更新的用户字段
			 * value 更新后的用户字段值
			 */
			uploadUserInfo(data){
				console.log(this.userInfo._id)
				userTable.doc(this.userInfo._id)
				.update(data)
				.then(res=>{
					console.log(data)
					this.login(data)
				})
				.catch(err=>{
					console.log(err);
				})
			}
		}
	}
</script>

<style>
.content{
		width: 750rpx;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		/* align-items: center; */
		flex: 1;
	}
	.avatar-box{
		width: 700rpx;
		height: 200rpx;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}
	.avatar-img{
		width: 150rpx;
		height: 150rpx;
		border-radius: 75rpx;
		
		border-width: 1rpx;
		border-color: #999999;
	}
</style>
