<template>
    <app-view class="g-form">
        <template #header>
            <app-navbar title="头像" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onSubmit">
            <CellGroup inset>
                <Field label="用户头像" :rules="formRules.headurl">
                    <template #input>
                        <app-uploader @success="onUploadSuccess" />
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <template #footer>
            <div class="g-form__footer">
                <Button round block type="primary" @click="formRef?.submit">确定</Button>
            </div>
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, reactive } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, FieldRule, showFailToast } from 'vant'
import { fullloading } from '@/utils/vant'
import { useNavigation } from '@/hooks/navigation'
import { updateUserHeadUrl } from '@/services/api/user'
import { loginStore, userStore } from '@/stores'
import AppUploader from '@mobile/components/base/uploader/index.vue'

const { userId } = loginStore.$mapGetters()
const { router } = useNavigation()

const formRef = shallowRef<FormInstance>()
const formData = reactive<Model.UserHeadUrlReq>({
    userid: userId.value, // 用户ID
    headurl: '', // 头像地址
})

// 表单验证规则
const formRules: { [key in keyof Model.UserHeadUrlReq]?: FieldRule[] } = {
    headurl: [{
        message: '请上传头像',
        validator: () => {
            return !!formData.headurl
        }
    }],
}

const onUploadSuccess = (filePath: string) => {
    formData.headurl = filePath
}

const onSubmit = () => {
    fullloading((hideLoading) => {
        updateUserHeadUrl(formData).then(() => {
            hideLoading()
            userStore.actions.getUserData()
            router.back()
        }).catch((err) => {
            showFailToast(err)
        })
    })
}
</script>