<template>
    <app-modal class="main-address-edit" direction="right" height="100%" v-model:show="showModal" :refresh="refresh">
        <app-view class="g-form" style="">
            <template #header>
                <app-navbar :title="selectedRow.autoid ? '修改收货地址' : '新增收货地址'" @back="closed" />
            </template>
            <Form ref="formRef" class="g-form__container" @submit="formSubmit">
                <CellGroup inset>
                    <Field v-model="formData.ReceiverName" :rules="formRules.ReceiverName" name="ReceiverName"
                        label="收货人" placeholder="必填" />
                    <Field v-model="formData.PhoneNum" :rules="formRules.PhoneNum" type="tel" name="PhoneNum"
                        label="联系电话" placeholder="必填" />
                    <Field :rules="formRules.Region" name="Region" label="收货地区" placeholder="请选择" is-link>
                        <template #input>
                            <app-region v-model="formData.DistrictID" :label="regionName" @finish="onRegionFinish" />
                        </template>
                    </Field>
                    <Field v-model="formData.Address" :rules="formRules.Address" name="Address" label="详细地址"
                        placeholder="必填" />
                </CellGroup>
            </Form>
            <template #footer>
                <div class="g-form__footer">
                    <Button type="warning" @click="formDelete" round block v-if="selectedRow.autoid">删除</Button>
                    <Button type="primary" @click="formRef?.submit" round block>保存</Button>
                </div>
            </template>
        </app-view>
    </app-modal>
</template>

<script lang="ts" setup>
import { 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 { 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 { formData, regionName, addOrUpdate, deleteAddress } = useAddressForm(props.selectedRow)
const formRef = shallowRef<FormInstance>()
const showModal = shallowRef(true)
const refresh = shallowRef(false) // 是否刷新父组件数据

// 表单验证规则
const formRules: { [key in keyof Proto.UserReceiveInfoReq | 'Region']?: FieldRule[] } = {
    ReceiverName: [{
        required: true,
        message: '请输入收货人',
    }],
    PhoneNum: [{
        required: true,
        message: '请输入联系电话',
        validator: (val) => {
            if (validateRules.phone.validate(val)) {
                return true
            }
            return validateRules.phone.message
        }
    }],
    Region: [{
        message: '请选择收货地区',
        validator: () => {
            return !!formData.ProvinceID && !!formData.CityID && !!formData.DistrictID
        }
    }],
    Address: [{
        required: true,
        message: '请输入详细地址',
    }],
}

// 选择地区
const onRegionFinish = ([province, city, district]: number[]) => {
    formData.ProvinceID = province
    formData.CityID = city
    formData.DistrictID = district
    formRef.value?.validate('Region')
}

// 表单提交
const formSubmit = () => {
    fullloading((hideLoading) => {
        addOrUpdate().then(() => {
            hideLoading()
            closed(true)
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}

// 删除地址
const formDelete = () => {
    dialog('是否删除该收货地址？', {
        showCancelButton: true
    }).then(() => {
        fullloading((hideLoading) => {
            deleteAddress().then(() => {
                hideLoading()
                closed(true)
            }).catch((err) => {
                Toast.fail(err)
            })
        })
    })
}

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

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