<template>
	<view>
		<page-title :showBack="true">更换头像</page-title>
		<view style="text-align: center;padding: 20upx;color: #6b6b6b; ">点击选择图片</view>
		<view style="margin-top: 50upx;text-align: center;width: 360upx;height: 360upx;margin: 0upx auto;background-color: #FFFFFF;">
			<cropper selWidth="660rpx" selHeight="660rpx" @upload="uploadImg" :avatarSrc="imgurl" avatarStyle="width:50vw;height:50vw;"> 
			</cropper>
		</view>
		<view v-if="isNew">
			<view style="margin-top: 100upx;"><button style="width: 50%;" @click="submitUpdate" type="primary">提交修改</button> </view>
		</view>
	</view>
</template>

<script>
	import cropper from "@/components/x-cropper/x-cropper.vue"
	import accountApi from '@/api/account';
	import uploadUtil from '@/utils/upload.js'
	import config from '@/config/index.js'
	import {mapGetters,mapMutations} from 'vuex'
	export default {
		components: {cropper},
		computed: mapGetters(['userInfo']),
		data() {
			return {
				isNew:false,
				imgurl:"",
				filePath:"",
				aid:"",
			}
		},
		onShow() {
			this.$store.dispatch('GetUserInfo').then(rs=>{
				//this.userInfoObj=rs;
				this.imgurl = rs.avatar;
				this.aid = rs.aid;
			})
			// this.imgurl = this.userInfo.avatar;
			// this.aid = this.userInfo.aid;
		},
		methods: {
			//上传返回图片
			uploadImg(rsp) {				
			  this.imgurl = rsp.path; 
			  // rsp.avatar.imgSrc = rsp.path; //更新头像方式二
			  uploadUtil.uploadFileObject(rsp.file).then(rs=>{
			  	if(rs.status==200){
			  		this.imgurl = rs.result.httpPath;
					this.filePath = rs.result.filePath;
					this.isNew=true;
			  	}
			  });
			},
			submitUpdate(){
				//提交更新
				let that=this;
				if(this.filePath !== '' && this.isNew){
					accountApi.updateAvatar({id:that.aid,avatar:that.filePath}).then(rs=>{
						if(rs.status == 200){
							// 更新下页面缓存
							that.$store.dispatch('InitData');
							uni.showModal({
								icon:'success',
								title:'更新成功',
								showCancel:false,
								success() {
									uni.navigateBack(-1);
								}
							});							
						} else {
							uni.showToast({
								title:'更新失败'
							})
						}
					})
				}
			},
		}
	}
</script>

<style lang="scss">
</style>
