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

const { required } = useValidator()

const actionType = ref('add')

const props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'orgName',
    label: '机构名称',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'orgNo',
    label: '机构编号',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'logRecordTime',
    label: '日志记录时间',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'dataDate',
    label: '操作日期',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'operationTime',
    label: '操作时间',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'userName',
    label: '操作账号',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'userIp',
    label: '操作IP',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'operationType',
    label: '操作类型',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  },
  {
    field: 'logDetail',
    label: '日志详情',
    component: 'Input',
    componentProps: {
      disabled: actionType.value === 'update'
    }
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  orgName: [required()],
  orgNo: [required()],
  logRecordTime: [required()],
  dataDate: [required()],
  operationTime: [required()],
  userName: [required()],
  userIp: [required()],
  operationType: [required()],
  logDetail: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = 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
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    actionType.value = 'update'
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>
