<template>
	<button
		open-type="chooseAvatar"
		hover-class="none"
		class="w-full h-full overflow-hidden !hover:bg-transparent !active:bg-transparent"
		@chooseavatar="onChooseAvatar"
	>
		<slot :show-value="showValue">
			<image
				:src="showValue"
				mode="scaleToFill"
				class="w-full h-full flex-none rounded-full overflow-hidden"
			/>
		</slot>
	</button>
</template>

<script>
import { getFileBaseURL } from '@/configs/request'
import defaultAvatar from '@/static/avatar.png'

export default {
	props: {
		defaultValue: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			showValue: defaultAvatar,
			url: ''
		}
	},

	watch: {
		defaultValue: {
			handler(value) {
				if (!value) {
					return
				}

				this.showValue = value
			},
			immediate: true
		}
	},
	methods: {
		onChooseAvatar(event) {
			const { avatarUrl } = event.detail
			this.showValue = avatarUrl
			this.uploadAvatar()
		},
		async uploadAvatar() {
			const res = await this.$api.uploadFile({
				name: 'file',
				filePath: this.showValue
			})

			if (res.success) {
				this.url = res.msg
				this.$emit('changeAvatar', this.url)
				// this.submitAvatar()
			} else {
				this.$toast('头像上传失败！')
			}
		},
		async submitAvatar() {
			const params = {
				avatar: this.url
			}

			const res = await this.$api.userHeadimg(params)
			if (res.success) {
				await this.$toast('头像设置成功')
			}
		}
	}
}
</script>

<style></style>
