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

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

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

import {
  getDepartOptionApi,
  updateDoctorDepartBindApi,
} from '#/views/doctor/doctor/api';

const gridApi = ref();
const data = ref<Record<string, any>>();
const optionData = ref<{ label: string; value: number }[]>([]);

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  draggable: true,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    const suId = data.value?.su_id;
    if (suId == null) {
      message.error('缺少医生信息');
      return;
    }
    const departId =
      data.value?.depart_id === undefined || data.value?.depart_id === null
        ? 0
        : Number(data.value.depart_id);
    await updateDoctorDepartBindApi({
      doctor_id: suId,
      depart_id: Number.isNaN(departId) ? 0 : departId,
    });
    modalApi.close();
    message.success('保存成功');
    gridApi.value?.reload?.();
    gridApi.value?.query?.();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      gridApi.value = modalApi.getData()?.gridApi ?? null;
      const payload = modalApi.getData<Record<string, any>>();
      const { values } = payload ?? {};
      if (values) {
        data.value = JSON.parse(JSON.stringify(values));
        if (
          data.value.depart_id === undefined ||
          data.value.depart_id === null
        ) {
          data.value.depart_id = undefined;
        } else {
          data.value.depart_id = Number(data.value.depart_id) || undefined;
        }
        loadDepartOptions();
      }
    }
  },
});

/** 加载科室下拉选项 */
const loadDepartOptions = () => {
  getDepartOptionApi().then((res: any) => {
    const list = Array.isArray(res) ? res : [];
    optionData.value = list.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  });
};
</script>

<template>
  <Modal class="w-[400px]" title="编辑科室">
    <div v-if="data" class="py-4">
      <Select
        v-model:value="data.depart_id"
        :options="optionData"
        allow-clear
        placeholder="请选择科室（清空表示未绑定）"
        show-search
        :filter-option="
          (input: string, option: any) =>
            String(option?.label ?? '')
              .toLowerCase()
              .includes(input.trim().toLowerCase())
        "
        style="width: 100%"
      />
    </div>
  </Modal>
</template>
