<template>
  <BasicModal
    v-bind="$attrs"
    destroyOnClose
    @register="registerModal"
    :title="getTitle"
    :width="width"
    @ok="handleSubmit"
    :showFooter="true"
  >
    <div class="!px-4 !pt-4">
      <BasicForm @register="registerForm" layout="vertical" />
    </div>
  </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 { dataFormSchema } from './data';

  import {
    archivesPatientReturnAdd,
    archivesPatientReturnEdit,
    archivesPatientReturnDetail,
  } from '/@/api/biz/archives/patientReturnApi';
  import dayjs from 'dayjs';

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

  const getTitle = computed(() => (!unref(isUpdate) ? '新增转归记录' : '编辑转归记录'));
  const width = '35%';
  const isUpdate = ref(false);
  const rowId = ref();
  const patientBasicId = ref('');

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    patientBasicId.value = data.record?.patientBasicId;

    if (unref(isUpdate)) {
      const resData = await archivesPatientReturnDetail(data.record.id);
      rowId.value = resData.id;
      await setFieldsValue({
        ...resData,
      });
    } else {
      await setFieldsValue({
        returnTime: dayjs().format('YYYY-MM-DD'),
      });
    }
  });

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