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

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

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

import { getDoctorTitleOptionApi } from '#/views/doctor/pharmacist/api';
import { updateDoctorTitleBindApi } 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 titleId =
      data.value?.title_id === undefined || data.value?.title_id === null
        ? 0
        : Number(data.value.title_id);
    await updateDoctorTitleBindApi({
      doctor_id: suId,
      title_id: Number.isNaN(titleId) ? 0 : titleId,
    });
    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.title_id === undefined ||
          data.value.title_id === null
        ) {
          data.value.title_id = undefined;
        } else {
          data.value.title_id = Number(data.value.title_id) || undefined;
        }
        loadTitleOptions();
      }
    }
  },
});

/** 加载职称下拉选项（医生 type=1） */
const loadTitleOptions = () => {
  getDoctorTitleOptionApi().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.title_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>
