<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 props = defineProps({
  currentRow: {
    type: Object as PropType<any>,
    default: () => null
  }
})

const formSchema = ref<FormSchema[]>([
  {
    field: 'id',
    label: '主键',
    component: 'Input'
  },
  {
    field: 'organId',
    label: '机构号',
    component: 'InputNumber'
  },
  {
    field: 'name',
    label: '角色名称',
    component: 'Input'
  },
  {
    field: 'dataScope',
    label: '权限范围',
    component: 'InputNumber'
  },
  {
    field: 'createBy',
    label: '创建人',
    component: 'Input'
  },
  {
    field: 'createDate',
    label: '创建时间',
    component: 'DatePicker'
  },
  {
    field: 'updateBy',
    label: '最近修改人',
    component: 'Input'
  },
  {
    field: 'updateDate',
    label: '最近修改时间',
    component: 'Input'
  },
  {
    field: 'remarks',
    label: '描述',
    component: 'Input'
  },
  {
    field: 'delFlag',
    label: '逻辑删除标记(0.正常，1.删除)',
    component: 'Input'
  }
])

const rules = reactive({
  component: [required()],
  path: [required()],
  id: [required()],
  organId: [required()],
  name: [required()],
  dataScope: [required()],
  createBy: [required()],
  createDate: [required()],
  updateBy: [required()],
  updateDate: [required()],
  remarks: [required()],
  delFlag: [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
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

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