<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { Form, FormItem, message } from 'ant-design-vue';

import DoctorPicker from '#/components/form/components/doctor-picker.vue';

import { updateSpecialPrescriptionDoctorApi } from '../api';

const formState = ref({
  id: undefined as number | undefined,
  special_prescription_doctor_id: undefined as number | undefined,
});

const gridApiRef = ref<any>(null);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    modalApi.setState({ confirmLoading: true });
    try {
      await updateSpecialPrescriptionDoctorApi({
        id: formState.value.id!,
        special_prescription_doctor_id: formState.value.special_prescription_doctor_id || null,
      });
      message.success('绑定成功');
      gridApiRef.value?.reload();
      modalApi.close();
    } catch {
      message.error('绑定失败');
    } finally {
      modalApi.setState({ confirmLoading: false });
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, gridApi } = modalApi.getData<Record<string, any>>();
      gridApiRef.value = gridApi;
      formState.value = {
        id: values?.id,
        special_prescription_doctor_id: values?.special_prescription_doctor_id || undefined,
      };
    }
  },
});
</script>

<template>
  <Modal title="换绑特色方默认医生" class="w-[500px]">
    <Form :model="formState" layout="vertical">
      <FormItem label="特色方默认挂号医生">
        <DoctorPicker
          v-model:value="formState.special_prescription_doctor_id"
          :store-id="formState.id"
        />
      </FormItem>
    </Form>
  </Modal>
</template>
