<!-- 个人资料修改 -->
<template>
	<view>
		<u-cell-group>
			<u-cell-item title="头像修改">
				<u-upload
					slot="right-icon"
					:action="action"
					:custom-btn="true"
					:before-upload="beforeUpload"
					:multiple="false"
					:show-upload-list="false"
					:limitType="['png', 'jpg']"
					@on-success="uploadSuccess"
				>
					<u-avatar slot="addBtn" :src="avatarUrl" mode="circle" size="100"></u-avatar>
				</u-upload>
			</u-cell-item>
		</u-cell-group>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 上传地址
				action: this.config.uploadUrl,
				avatarUrl: ''
			}
		},
		onShow() {
			this.getMemberinfo()
		},
		methods: {
			/**
			 * 获取用户基本信息
			 */
			getMemberinfo(){
				uni.showLoading({
					mask: true,
					title: '数据请求中...'
				})
				this.$u.api.getmemberinfo().then(res => {
					if (res.code === 200){
						this.avatarUrl = res.data.avatar;
						uni.hideLoading()
					} else {
						this.$refs.uToast.show({
							title: res.msg,
							type: 'error'
						})
						uni.hideLoading()
					}
				}).catch(err => {
					this.$refs.uToast.show({
						title: err.msg,
						type: 'error'
					})
					uni.hideLoading()
				})
			},
			/**
			 * 上传组件上传触发
			 * @param {Object} index
			 * @param {Object} list
			 */
			beforeUpload(index, list) {
				uni.showLoading({
					title: '图片上传中...',
					mask: true
				})
			},
			/**
			 * 上传组件成功触发
			 * @param { Object } res
			 */
			uploadSuccess(res) {
				if (res.code === 200) {
					this.$u.api.modifyUserInfo({
						avatar: res.data.url
					}).then(res => {
						if (res.code === 200) {
							this.getMemberinfo()
							this.$refs.uToast.show({
								title: '修改成功!',
								type: 'success'
							})
							uni.hideLoading()
						} else {
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error'
							})
							uni.hideLoading()
						}
					}).catch(() => {
						uni.hideLoading()
						this.$refs.uToast.show({
							title: '系统异常',
							type: 'error'
						})
					})
				} else {
					uni.hideLoading();
					this.$refs.uToast.show({
						title: res.msg,
						type: 'error'
					})
				}
			}
		}
	}
</script>

<style>

</style>
