<template>
	<view class="container">
		<view class="image-cropper">
			<image :src="selectedImage.path" mode="aspectFill"></image>
			<!-- <image src="@/static/images/mine/headImg.jpg"></image> -->
		</view>

		<button type="default" @click="chooseImage">选择头像</button>
		<button type="primary" @click="submitImage">提交</button>
	</view>
</template>

<script setup>
	import {onMounted, ref} from 'vue';
	import {uploadAvatarFile,updateUserInfoHeaderFileId} from '@/api/mine';
	import { useUserStore } from '@/store/user.js';
	import $modal from '@/plugins/modal.js';
	import $tab from '@/plugins/tab.js'
	import config from '@/config';
	const userStore=useUserStore();
	const defaultAvatarPath='/static/images/mine/headImg.jpg'
	//所选头像信息
	const selectedImage = ref({});

	onMounted(()=>{
		selectedImage.value={
			path:userStore.user.photo==""?defaultAvatarPath:config.baseUrlPre+userStore.user.photo
		}
	})
	function chooseImage() {
		
		let chooseFile = uni.chooseFile;
		if (typeof wx !== 'undefined' && typeof wx.chooseMessageFile === 'function') {
			//切换微信小程序选择文件的方法
			chooseFile = wx.chooseMessageFile;
		}
		if (typeof chooseFile !== 'function') {
			return reject({
				errMsg: ERR_MSG_FAIL + ' 请指定 type 类型，该平台仅支持选择 image 或 video。',
			});
		}
		chooseFile({
			count: 1,
			type: 'image',
			success: (res) => {
				selectedImage.value = res.tempFiles[0];
			}
		});
	};

	const submitImage = () => {
		if (!selectedImage.value) return;
		const data = {
			name: selectedImage.value.name,
			filePath: selectedImage.value.path
		}
		uploadAvatarFile(data).then(res => {
			if('success'===res.returnMsg){
				const params={
					userid:userStore.useId,
					headerFileId:res.returnParams
				}
				updateUserInfoHeaderFileId(params).then(res=>{
					if('success'===res.returnMsg){
						$modal.msgSuccess('提交成功');
						setTimeout(() => {
							$tab.navigateBack()
						}, 1000);
					}
				})
			}
			
		}).catch(err => {
			$modal.msgError('文件' + data.name + '上传失败,请重新上传')
			switch (err) {
				case -201:
					console.log('文件上传失败 未找到该文件');
					break;
				case -20201:
					console.log('文件上传失败 返回值不是JSON字符串');
					break;
			}
			
		})

		
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 20px;
		box-sizing: border-box;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.image-cropper image {
		width: 200px;
		height: 200px;
		border-radius: 50%;
		margin-bottom: 30px;
	}

	button {
		margin-top: 10px;
		width: 90%;
	}
</style>