<template>
	<fs-form ref="formRef" :model="userInfo">
		<view class="text-center">
			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="handleUpload">
				<fs-avatar size="140rpx" bgColor="#EBEFF5" :src="userInfo.photo">
					<fs-icon type="icon-photo" size="50rpx"></fs-icon>
				</fs-avatar>
			</button>
		</view>
		<fs-form-item required label="姓名">
			<fs-field placeholder="请输入姓名" v-model="userInfo.name"></fs-field>
		</fs-form-item>
		<fs-form-item required label="手机号">
			<fs-field placeholder="请输入手机号" v-model="userInfo.mobile"></fs-field>
		</fs-form-item>
		<fs-form-item label="性别">
			<fs-radio-group inline v-model="userInfo.sex">
				<fs-radio value="1">男</fs-radio>
				<fs-radio value="2">女</fs-radio>
			</fs-radio-group>
		</fs-form-item>
		<fs-gutter height="100rpx"></fs-gutter>
		<fs-button block round @click="handleSave">保存</fs-button>
	</fs-form>
</template>

<script setup>
import useForm from '@/hooks/useForm'
import useValidator from '@/hooks/useValidator'
import { useUserStore } from '@/stores/user'
import utils from '@/utils/utils'

const user = useUserStore()
const userInfo = computed(() => user.userInfo)
const validator = useValidator()

const rules = {
	name: {
		required: true,
		message: '请输入姓名'
	},
	mobile: { validator: validator.mobile }
}
const formRef = ref(null)
const form = useForm(rules, 'formRef')

const { proxy } = getCurrentInstance()
const handleUpload = e => {
	wx.editImage({
		src: e.detail.avatarUrl,
		success: res => {
			utils
				.uploadFile({
					filePath: res.tempFilePath,
					url: proxy.$uploadUrl
				})
				.then(res => {
					userInfo.value.photo = res
				})
		}
	})
}

const handleSave = () => {
	form.validate().then(() => {
		user.setUserInfo(userInfo.value)
		uni.navigateBack()
	})
}
</script>

<style lang="scss" scoped>
.avatar-wrapper {
	margin: 30rpx;
	width: 140rpx;
	height: 140rpx;
	border-radius: 50%;
	border: none;
	padding: 0;
	display: inline-block;
	background-color: transparent;
	&::after {
		border: none;
	}
}
</style>
