<template>
  <BasePatientList
    :filtered-card-data="filteredCardData"
    :active-card-id="cardId"
    :loading="queryloading"
    @item-click="handleItemClick"
    @search="handleSearch"
    @refresh="getList"
  />
</template>

<script setup>
import {computed, onMounted, reactive, ref, watch} from 'vue';
import BasePatientList from './index.vue';
import {getPatientList} from '@/views/inpatientDoctor/home/components/api';

defineOptions({
  name: 'PatientListWithData',
});

const props = defineProps({
  /** 接口 status 参数，默认 5（在院） */
  status: {
    type: [String, Number],
    default: undefined,
  },
  /** 首次加载自动选中第一条 */
  autoSelectFirst: {
    type: Boolean,
    default: true,
  },
  /** 外部已选中的患者信息（用于避免重复自动选中） */
  selectedPatient: {
    type: Object,
    default: null,
  },
  /**
   * 选中患者时回调（给你外部写 store 用）
   * (patient) => void
   */
  onSelect: {
    type: Function,
    default: null,
  },
});

const emit = defineEmits(['item-click']);

// 这段逻辑就是你说的 “@index.vue (4-11) 那套带数据的”
const searchData = reactive({
  keyword: '',
  patientType: 1,
  type: 1,
  timeLimit: 3,
});

const cardId = ref('');
const cardAllData = ref([]);
const isFirstLoad = ref(true);
const queryloading = ref(false);

const filteredCardData = computed(() => cardAllData.value);

const getList = () => {
  queryloading.value = true;
  getPatientList({ status: props.status, searchKey: searchData.keyword })
    .then((res) => {
      cardAllData.value = res?.data?.records || [];
    })
    .finally(() => {
      queryloading.value = false;
    });
};

watch(
  () => filteredCardData.value,
  (newData) => {
    if (!props.autoSelectFirst) return;
    if (
      newData &&
      newData.length > 0 &&
      !cardId.value &&
      isFirstLoad.value &&
      !props.selectedPatient?.encounterId
    ) {
      const firstPatient = newData[0];
      if (firstPatient?.encounterId) {
        handleItemClick(firstPatient);
        isFirstLoad.value = false;
      }
    }
  },
  { immediate: true }
);

const handleItemClick = (node) => {
  cardId.value = node.encounterId;
  props.onSelect?.(node);
  emit('item-click', node);
};

const handleSearch = (keyword) => {
  searchData.keyword = keyword;
  getList();
};

onMounted(() => {
  getList();
});
</script>
