<template>
	<view class="content">
		<view class="edgeInsetTop"></view>
		<!-- #ifndef MP-WEIXIN -->
			<wanl-image-cutter @ok="getCropperImage" @cancel="oncancle" :url="url" :fixed="false" :blob="false"
				:maxWidth="500" :maxHeight="500" />
		<!-- #endif -->
		<view class="text-center" :style="{backgroundImage: `url(${$wanlshop.maks()})`}">
			<!-- #ifdef MP-WEIXIN -->
				<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="avatar" :src="$wanlshop.oss(user.avatar, 100, 100)" mode="aspectFill"/>
				</button>
			<!-- #endif -->
			<!-- #ifndef MP-WEIXIN -->
				<view @tap="chooseImage" class="cu-avatar avatar" v-if="path"
					:style="{ backgroundImage: 'url(' + path + ')' }"></view>
				<view @tap="chooseImage" class="cu-avatar avatar" v-else
					:style="{ backgroundImage: 'url(' + $wanlshop.oss(user.avatar, 100, 100) + ')' }"></view>
			<!-- #endif -->
			<view class="text-sm">点击修改头像</view>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	export default {
		data() {
			return {
				url: '',
				path: ''
			};
		},
		computed: {
			...mapState(['user'])
		},
		methods: {
			onChooseAvatar(e) {
				this.uploadFile(e.detail.avatarUrl);
			},
			getCropperImage(e) {
				this.path = e.path;
				this.url = '';
				// 上传图片
				this.uploadFile(e.path);
			},
			uploadFile(file) {
				uni.request({
					url: '/wanlshop/common/uploadData',
					success: updata => {
						uni.uploadFile({
							url: updata.data.uploadurl,
							filePath: file,
							name: 'file',
							formData: updata.data.storage == 'local' ? null : updata.data.multipart,
							success: res => {
								uni.request({
									url: '/wanlshop/user/profile',
									method: 'POST',
									data: {
										avatar: JSON.parse(res.data).data.url
									},
									success: data => {
										this.$store.commit('user/setUserInfo', {
											avatar: data.data.avatar
										});
									}
								});
							},
							fail: error => {
								this.$wanlshop.msg(JSON.parse(error.data).msg);
							}
						});
					}
				});
			},
			chooseImage() {
				uni.chooseImage({
					count: 1, // 默认9
					sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
					success: res => {
						// 设置url的值，显示控件
						this.url = res.tempFilePaths[0];
					}
				});
			},
			oncancle() {
				this.url = '';
			}
		}
	};
</script>

<style>
	.avatar-wrapper {
		display: flex;
		justify-content: center;
		background-color: transparent;
	}
	.avatar-wrapper::after{
		border: 0;
	}
	.avatar {
		border-radius: 9999px;
		overflow: hidden;
		height: 240rpx;
		width: 240rpx;
		margin: 150rpx 0 40rpx;
		border: 1rpx solid #fe6600;
	}
</style>