<script lang="ts" setup>
import { ref } from 'vue'
import { formSchema } from './data'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { BasicForm, useForm } from '@/components/Form'
import { BasicModal, useModalInner } from '@/components/Modal'
import { createDept, updateDept } from '@/api/system/dept'
import type { Department } from '@/api/system/dept/types'

defineOptions({ name: 'DeptFormModal' })

const emit = defineEmits(['success', 'register'])
const { t } = useI18n()

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

const isUpdate = ref(false)
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data: Department) => {
  isUpdate.value = true
  setFieldsValue({
    ...data,
    parentId: data.parentId === '0' ? undefined : data.parentId,
  })
})

async function handleSubmit() {
  try {
    const values = await validate<Department>()
    setModalProps({ confirmLoading: true })
    values.parentId = values.parentId ? values.parentId : '0'
    await (isUpdate.value ? updateDept(values) : createDept(values))
    closeModal()
    emit('success')
    useMessage().createMessage.success(t('common.saveSuccessText'))
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? t('action.edit') : t('action.create')"
    @register="registerModal"
    @ok="handleSubmit"
    @cancel="isUpdate = false"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
