<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { wardTypeDataFormSchema } from './data';

  import { wardTypeAdd } from '/@/api/biz/management/wardType';

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

  const getTitle = computed(() => (!unref(isUpdate) ? '新增病区属性' : '编辑病区属性'));
  const isUpdate = ref(false);
  const rowId = ref();

  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate }] = useForm({
    layout: 'vertical',
    showResetButton: true,
    labelWidth: 100,
    schemas: wardTypeDataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await wardTypeAdd({ ...values });
      createMessage.success('新增成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, configId: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false, canFullscreen: false });
    }
  }
</script>
