<template>
    <app-modal class="main-address-edit" direction="right" height="100%" v-model:show="showModal">
        <app-view class="g-form" style="">
            <template #header>
                <app-navbar title="新增收货地址" />
            </template>
            <Form ref="formRef" class="g-form__container" @submit="formSubmit">
                <CellGroup inset>
                    <Field v-model="formData.ReceiverName" name="ReceiverName" label="收货人" placeholder="必填"
                        :rules="formRules.ReceiverName" />
                    <Field v-model="formData.PhoneNum" type="tel" name="PhoneNum" label="联系电话" placeholder="必填"
                        :rules="formRules.PhoneNum" />
                    <Field label="收货地区" placeholder="请选择" is-link>
                        <template #input>
                            <app-region v-model="formData.DistrictID" />
                        </template>
                    </Field>
                    <Field v-model="formData.Address" name="refernum" label="详细地址" placeholder="详细地址" />
                </CellGroup>
            </Form>
            <template #footer>
                <div class="g-form__footer">
                    <Button type="primary" @click="formRef?.submit" round block>确定</Button>
                </div>
            </template>
        </app-view>
    </app-modal>
</template>

<script lang="ts" setup>
import { reactive, shallowRef, PropType } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, Toast, FieldRule } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { validateRules } from '@/constants/regex'
import { useNavigation } from '@/hooks/navigation'
import { useAddressForm } from '@/business/user'
import AppModal from '@/components/base/modal/index.vue'
import AppRegion from '@mobile/components/base/region/index.vue'

const props = defineProps({
    selectedRow: {
        type: Object as PropType<Model.UserReceiveInfoRsp>,
        default: () => ({})
    }
})

const { router } = useNavigation()
const { formData, addOrUpdate } = useAddressForm(props.selectedRow)
const formRef = shallowRef<FormInstance>()
const showModal = shallowRef(true)

// 表单验证规则
const formRules: { [key in keyof Proto.UserReceiveInfoReq]?: FieldRule[] } = {
    ReceiverName: [{
        required: true,
        message: '请输入收货人',
    }],
}

// 表单提交
const formSubmit = () => {
    fullloading((hideLoading) => {
        addOrUpdate().then(() => {
            hideLoading()
            Toast.fail('保存成功')
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

// 关闭弹窗
const closed = () => {
    showModal.value = false
}

// 暴露组件属性给父组件调用
defineExpose({
    closed,
})
</script>