<script setup lang="ts">
import { CellGroup as VanCellGroup, Field as VanField } from 'vant'
import { defineExpose, onMounted, onUnmounted, ref } from 'vue'

interface UserFormProps {
  setRef?: (refValue: any) => void
  removeRef?: (refValue: any) => void
  formGroupName?: string
  formData?: any
}

const props = withDefaults(defineProps<UserFormProps>(), {
  setRef: () => {},
  removeRef: () => {},
  formGroupName: 'userInfo',
  formData: () => ({}),
})

const formData = ref({
  name: '',
  phone: '',
  email: '',
  ...props.formData,
})

async function validate() {
  if (!formData.value.name) {
    throw new Error('姓名不能为空')
  }
  if (!formData.value.phone) {
    throw new Error('手机号不能为空')
  }
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(formData.value.phone)) {
    throw new Error('手机号格式不正确')
  }
  return Promise.resolve()
}

function getFormData() {
  return {
    name: formData.value.name,
    phone: formData.value.phone,
    email: formData.value.email,
  }
}

function resetForm() {
  formData.value = {
    name: '',
    phone: '',
    email: '',
  }
}

const exposeObj = {
  validate,
  getFormData,
  resetForm,
  formGroupName: props.formGroupName,
}

defineExpose(exposeObj)

onMounted(() => {
  props.setRef(exposeObj)
})

onUnmounted(() => {
  props.removeRef(exposeObj)
})
</script>

<template>
  <div class="user-form">
    <VanCellGroup inset>
      <VanField
        v-model="formData.name"
        label="姓名"
        placeholder="请输入姓名"
        :rules="[{ required: true, message: '请输入姓名' }]"
      />
      <VanField
        v-model="formData.phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请输入手机号' }]"
      />
      <VanField
        v-model="formData.email"
        label="邮箱"
        placeholder="请输入邮箱"
      />
    </VanCellGroup>
  </div>
</template>

<style scoped lang="less">
.user-form {
  padding: 16px;
}
</style>
