<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="600px" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="OperationOrderDrawer">
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './schema';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import * as OperationOrderApi from '/@/api/order/operationOrderApi';

  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const entityId = ref(0);

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

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    entityId.value = data?.record?.id;

    if (unref(isUpdate)) {
      await setFieldsValue({
        ...data.record,
        hospitalId: { label: data.record.hospitalName, value: data.record.hospitalId },
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setDrawerProps({ confirmLoading: true });
      const {
        hospitalId,
        ...rest
      } = values;
      const action = !unref(isUpdate) ? OperationOrderApi.add : OperationOrderApi.update;
      const data = !unref(isUpdate)
        ? {
            ...rest,
            hospitalId: hospitalId.value,
            hospitalName: hospitalId.label,
          }
        : Object.assign({},
          {
            ...rest,
            id: unref(entityId),
            hospitalId: hospitalId.value,
            hospitalName: hospitalId.label,
          },
        );
      await action(data);
      closeDrawer();
      emit('success');
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
