<script lang="ts" setup>
import { ref } from 'vue'
import { formSchema } from './data'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createTenant, updateTenant } from '@/api/system/tenant'
import type { Tenant } from '@/api/system/tenant/types'

defineOptions({ name: 'TenantFormModal' })

const emit = defineEmits(['success', 'register'])

const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: formSchema,
  showActionButtonGroup: false,
})

const isUpdate = ref(false)
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  isUpdate.value = true
  setFieldsValue(data)
})

async function handleSubmit() {
  try {
    const values = await validate<Tenant>()
    setModalProps({ confirmLoading: true })
    await (isUpdate.value ? updateTenant(values) : createTenant(values))
    closeModal()
    emit('success')
    useMessage().createMessage.success('保存成功')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? '编辑' : '新增'"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="isUpdate = false"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
