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

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

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

import {
  getSubjectsOptionApi,
  updateDoctorSubjectsBindApi,
} from '#/views/doctor/doctor/api';

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

/** 下拉按诊疗科目 name 搜索（不区分大小写） */
function filterSubjectByName(input: string, option: any) {
  const q = input.trim().toLowerCase();
  if (!q) return true;
  const name = String(option?.name ?? '').toLowerCase();
  const code = String(option?.code ?? '').toLowerCase();
  return name.includes(q) || code.includes(q);
}

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 sid =
      data.value?.subjects_id === undefined || data.value?.subjects_id === null
        ? 0
        : Number(data.value.subjects_id);
    await updateDoctorSubjectsBindApi({
      doctor_id: suId,
      subjects_id: Number.isNaN(sid) ? 0 : sid,
    });
    modalApi.close();
    message.success('保存成功');
    gridApi.value?.reload();
  },
  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.subjects_id === undefined ||
          data.value.subjects_id === null
        ) {
          data.value.subjects_id = undefined;
        } else {
          data.value.subjects_id = Number(data.value.subjects_id) || undefined;
        }
        loadSubjectsOptions();
      }
    }
  },
});

const loadSubjectsOptions = () => {
  getSubjectsOptionApi().then((res: any) => {
    const list = Array.isArray(res) ? res : [];
    optionData.value = list.map((item: any) => ({
      label: item.code ? `${item.name}（${item.code}）` : item.name,
      value: item.id,
      name: item.name ?? '',
      code: item.code ?? '',
    }));
  });
};
</script>

<template>
  <Modal class="w-[60%]" title="绑定诊疗科目">
    <div v-if="data" style="width: 60%; margin: 30px auto">
      <Select
        v-model:value="data.subjects_id"
        :options="optionData"
        :filter-option="filterSubjectByName"
        allow-clear
        placeholder="请选择诊疗科目（清空表示未绑定，可输入名称搜索）"
        show-search
        style="width: 100%"
      />
    </div>
  </Modal>
</template>
