<script setup lang="ts">
import { Form, FormSchema } from '@common/src/components/Form'
import { useForm } from '@common/src/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@common/src/hooks/web/useValidator'

const props = defineProps({
  currentRow: {
    type: Object,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  actionType: {
    type: String,
    default: ''
  }
})
const { required } = useValidator()
const rules = reactive({
  field: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

const getDetail = async () => {
  const { success, data } = await find(props.currentRow?.id || null)
  if (success) {
    setValues(data)
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    getDetail()
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" :is-col="false" />
</template>
