<script setup lang="ts">
import type { MedicalData, MedicalString } from '@/request/model/medical-record.model';
import type { RegisterModel } from '@/request/model';
import type RegisterForm from '@/components/RegisterForm.vue';

import { Notify } from '@/platform';
import { useRequest } from 'alova/client';
import { editMedicalRecordMethod } from '@/request/api/medical.api';
import { getMedicalReportData } from '@/request/model/medical-record.model';
import { updateMedicalPatient } from '@/request/model/medical-patient.model';

const props = defineProps<Partial<MedicalString>>();
const emits = defineEmits<{
  complete: [MedicalString];
  cancel: [];
}>();

const {
  data: form,
  loading: submitting,
  send: submit,
} = useRequest(editMedicalRecordMethod, { initialData: { ...props }, immediate: false }).onSuccess(({ data }) => emits('complete', data));

const formRef = ref<InstanceType<typeof RegisterForm> | null>(null);
const report = computed(() => {
  try {
    return getMedicalReportData(props.report ?? '');
  } catch (e: any) {
    Notify.error(e.message);
    emits('cancel');
  }
});
watch(
  () => report.value?.patient,
  (value) => {
    if (!value) return;
    nextTick(() => formRef.value?.setValues(value));
  },
  { immediate: true, flush: 'post' }
);

function onSubmitFromForm(payload: { model: RegisterModel; modelLabel: Partial<RegisterModel> }) {
  submit(updateMedicalPatient(form.value, payload));
}
</script>

<template>
  <div class="p-6" style="height: calc(100vh - 30px)">
    <RegisterForm ref="formRef" :search-forbidden-field="false" @submit="onSubmitFromForm" />
    <van-loading class="flex justify-center" v-if="formRef?.loading" type="spinner" size="64" color="#38ff6e" />
    <div v-else class="flex gap-4 mb-6 px-4 py-3">
      <van-button block type="primary" plain :disabled="submitting" @click="emits('cancel')">取消</van-button>
      <van-button block type="primary" :loading="submitting" @click="formRef?.submit()">保存</van-button>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>
