<template>
    <mx-submit-layout :title="prevData.settingName" :loading="loading" @submit="handleSubmit">
        <uv-form ref="form" :model="model" :rules="rules">
            <name-gender-fields/>
            <phone-with-change-field/>
            <province-field disabled/>
            <gaokao-year-field v-if="isBind" disabled/>
            <school-info-fields v-if="isBind" disabled/>
            <type-major-fields :disabled="!enableAuthModify"/>
        </uv-form>
    </mx-submit-layout>
</template>

<script setup>
import {ref, watch} from 'vue'
import {useTransfer} from "@/hooks/useTransfer";
import {useUserStore} from "@/hooks/useUserStore";
import {improveUserInfo} from "@/api/login";
import {sleep, toast} from "@/uni_modules/uv-ui-tools/libs/function";
import PhoneWithChangeField from "@/pagesOther/pages/login/components/register-fields/phone-with-change-field.vue";
import NameGenderFields from "@/pagesOther/pages/login/components/register-fields/name-gender-fields.vue";
import ProvinceField from "@/pagesOther/pages/login/components/register-fields/province-field.vue";
import {createBasicInfoModelRules} from "@/pagesOther/pages/login/components/hooks/defineFormModels";
import {useProvideFormData} from "@/pagesOther/pages/login/components/hooks/useFormDataInjection";
import _ from "lodash";
import TypeMajorFields from "@/pagesOther/pages/login/components/register-fields/type-major-fields.vue";
import GaokaoYearField from "@/pagesOther/pages/login/components/register-fields/gaokao-year-field.vue";
import SchoolInfoFields from "@/pagesOther/pages/login/components/register-fields/school-info-fields.vue";

const {prevData, relaunch} = useTransfer()
const {currentUser, isBind, enableAuthModify, GetInfo} = useUserStore()
const form = ref(null)
const model = ref({}) // 不要改变model.value, 因为内部有很多服务在监听它。
const loading = ref(false)

// form & service
const [m, r, modelToCommit] = createBasicInfoModelRules(model)
const [, rules] = useProvideFormData(m, r)

// hooks
watch(currentUser, () => _.assign(model.value, currentUser.value), {immediate: true})
console.log(currentUser)
// methods
const handleSubmit = async () => {
    await form.value.validate()
    if (loading.value) return
    loading.value = true
    try {
        const commit = modelToCommit()
        await improveUserInfo(commit)
        await GetInfo()
        toast('保存成功，即将返回首页')
        await sleep(1000)
        relaunch()
    } finally {
        loading.value = false
    }
}

</script>

<style scoped lang="scss">

</style>
