<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { TableData } from '@/api/param/SysOrgan/types'
import { getSysOrgType } from '@/api/param/SysOrgan'
import { transfDictList } from '@/utils'

const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<TableData>,
    default: () => null
  },
  actionType: {
    type: String,
    default: 'add'
  }
})

const formSchema = reactive<FormSchema[]>([
  {
    field: 'code',
    label: '机构号',
    component: 'Input'
  },
  {
    field: 'orgname',
    label: '机构名称',
    component: 'Input'
  },
  {
    field: 'parentId',
    label: '上级机构号',
    component: 'Input'
  },
  {
    field: 'grade',
    label: '机构层级',
    component: 'Input'
  },
  // {
  //   field: 'orgLeveType',
  //   label: '机构类型',
  //   component: 'Select',
  //   optionApi: async () => {
  //     const res = await getSysOrgType()
  //     return transfDictList(res.body.result)
  //   },
  //   componentProps: {
  //     style: {
  //       width: '100%'
  //     }
  //   }
  // },
  // {
  //   field: 'address',
  //   label: '归属区域',
  //   component: 'Input'
  // },
  {
    field: 'createDate',
    label: '开始日期',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYYMMDD',
      style: {
        width: '100%'
      }
    }
  },
  {
    field: 'updateDate',
    label: '结束日期',
    component: 'DatePicker',
    componentProps: {
      type: 'date',
      valueFormat: 'YYYYMMDD',
      style: {
        width: '100%'
      }
    }
  },
  {
    field: 'fullName',
    label: '机构全称',
    component: 'Input',
    hidden:true
  }
])

const rules = reactive({
  code: [required()],
  orgname: [required()],
  orgLeveType: [required()],
  address: [required()],
  startdate: [required()],
  enddate: [required()],
  parentId: [required()],
  grade: [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>
