<script setup lang="ts">
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 { IBusiness } from '../../../../api/system-config/field/types'
import { findBusinessTable } from '../../../../api/system-config/field'

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<IBusiness>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  pageType: {
    type: Number,
    default: 0
  },
  actionType: {
    type: String,
    default: ''
  }
})
const { required } = useValidator()
const rules = reactive({
  serviceName: [required()],
  serviceNo: [required()],
  pageType: [required()],
  tableName: [required()],
  pageTemplate: [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
  }
}

// 切换 页面类型 时 更新表单项
watch(
  () => props.pageType,
  (val) => {
    setSchema([
      {
        field: 'pageTemplate',
        path: 'component',
        value: val === 1 ? 'Select' : 'Input'
      }
    ])
    setValues({
      pageTemplate: ''
    })
  }
)

const tableData = async () => {
  const { success, data } = await findBusinessTable(props.currentRow?.id || null)
  if (success) {
    // 编辑时候 初始化模版表单的类型
    if (props.actionType === 'edit') {
      setSchema([
        {
          field: 'pageTemplate',
          path: 'component',
          value: data.pageType === 1 ? 'Select' : 'Input'
        }
      ])
    }
    setValues({
      ...data,
      isEnabled: !!data.isEnabled
    })
  }
}

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

defineExpose({
  submit
})
</script>

<template>
  <Form
    :rules="rules"
    @register="formRegister"
    :schema="formSchema"
    :is-col="false"
    :disabled="props.actionType === 'detail'"
  />
</template>
