<template>
    <app-view class="g-form">
        <template #header>
            <app-navbar :title="$t('user.avater.title')" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onSubmit">
            <CellGroup inset>
                <Field :label="$t('user.avater.cardbackphotourl')" :rules="formRules.headurl">
                    <template #input>
                        <app-uploader @success="onUploadSuccess" />
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <template #footer>
            <div class="g-form__footer inset">
                <Button round block type="danger" @click="formRef?.submit">{{ $t('operation.confirm') }}</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 '@mobile/router/navigation'
import { updateUserHeadUrl } from '@/services/api/user'
import { useLoginStore, useUserStore, i18n } from '@/stores'
import AppUploader from '@mobile/components/base/uploader/index.vue'

const { router } = useNavigation()
const loginStore = useLoginStore()
const userStore = useUserStore()

const { global: { t } } = i18n

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

// 表单验证规则
const formRules: { [key: string]: FieldRule[] } = {
    headurl: [{
        message: t('user.avater.tips1'),
        validator: () => {
            return !!formData.headurl
        }
    }],
}

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

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