<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :confirmDisabled="getConfirmDisabled"
    :title="getTitle"
    width="600px"
    @ok="handleSubmit"
  >
    <a-spin :spinning="isLoading">
      <BasicForm @register="registerForm" />
    </a-spin>
  </BasicDrawer>
</template>
<script lang="ts" setup name="DoctorDrawer">
  import { defineEmits, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, StatusValEnum } from './schema';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import * as DoctorApi from '/@/api/system/doctorApi';
  import { useAsyncState } from '@vueuse/core';
  import { Doctor } from '/@/api/model/doctor';

  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,
  });

  // id 查询
  const {
    state: detail,
    isReady: isDetailReady,
    isLoading,
    execute,
  } = useAsyncState(
    () => {
      return DoctorApi.getById(entityId.value).then((res: Doctor) => res);
    },
    null,
    {
      immediate: 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 execute();
      if (detail.value) {
        const formData: any = { ...detail.value };
        if (detail.value.hospital) {
          formData.hospitalId = { label: detail.value.hospital.name, value: detail.value.hospital.id };
        } else {
          formData.hospitalId = { label: '(已删除/不存在)', value: detail.value.hospitaId };
        }
        await setFieldsValue(formData);
      }
    }
  });

  const getConfirmDisabled = computed(() => {
    if (unref(isUpdate)) {
      return !unref(isDetailReady);
    } else {
      return false;
    }
  });

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

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