<template>
  <div class="inpatientDoctor-home-container">
    <el-container>
      <PatientList :selected-patient="patientInfo" :on-select="handleItemClick" />
      <el-container class="inpatientDoctor-home-main">
        <el-header height="auto"><inPatientBarDoctorFold /></el-header>
        <el-main>
          <el-tabs v-model="activeTabName" type="card" class="patient-tabs">
            <el-tab-pane label="住院病历" name="inhospitalEmr">
              <Emr ref="inhospitalEmrRef" />
            </el-tab-pane>
            <el-tab-pane label="诊断录入" name="diagnosis">
              <Diagnose ref="diagnosisRef" :patientInfo="currentPatientInfo" />
            </el-tab-pane>
            <el-tab-pane label="临床医嘱" name="prescription">
              <Advice ref="adviceRef" />
            </el-tab-pane>
            <!-- <el-tab-pane label="医技报告" name="fourth">Task</el-tab-pane> -->
            <el-tab-pane label="检验申请" name="test">
              <TestApplication ref="testApplicationRef" />
            </el-tab-pane>
            <el-tab-pane label="检查申请" name="examine">
              <ExamineApplication ref="examineApplicationRef" />
            </el-tab-pane>
            <el-tab-pane label="手术申请" name="surgery">
              <SurgeryApplication ref="surgeryApplicationRef" />
            </el-tab-pane>
            <el-tab-pane label="输血申请" name="blood">
              <BloodTtransfusionAapplication ref="bloodTtransfusionAapplicationRef" />
            </el-tab-pane>
            <el-tab-pane label="报告查询" name="report">
              <ReportQuery />
            </el-tab-pane>
            <!-- <el-tab-pane label="护理状态" name="nursing">
              <NursingStatus />
            </el-tab-pane> -->
          </el-tabs>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script setup>
import {
  getCurrentInstance,
  onBeforeMount,
  onMounted,
  reactive,
  ref,
  watch,
  provide,
  computed,
} from 'vue';

import Emr from './emr/index.vue';
import inPatientBarDoctorFold from '@/components/patientBar/inPatientBarDoctorFold.vue';
import PatientList from '@/components/PatientList/patient-list.vue';
import { patientInfo, updatePatientInfo } from './store/patient';
import { getPatientList } from './components/api';
import {
  Advice,
  Diagnose,
  BloodTtransfusionAapplication,
  ExamineApplication,
  SurgeryApplication,
  TestApplication,
  NursingStatus,
  ReportQuery,
} from './index.js';
const state = reactive({});
onBeforeMount(() => {});
onMounted(() => {
  // 如果 store 中已有患者信息，使用 store 中的
  if (patientInfo.value?.encounterId) {
    cardId.value = patientInfo.value.encounterId;
    isFirstLoad.value = false;
  }
  queryPatientData();
  getList();
});
defineExpose({ state });
const activeTabName = ref('inhospitalEmr');
const diagnosisRef = ref();
const adviceRef = ref();
const patientAside = ref(true);
const currentPatientInfo = ref({});
const testApplicationRef = ref();
const examineApplicationRef = ref();
const surgeryApplicationRef = ref();
const bloodTtransfusionAapplicationRef = ref();

// 患者列表相关逻辑
const searchData = reactive({
  keyword: '',
  patientType: 1,
  type: 1,
  timeLimit: 3,
});
const cardId = ref('');
const cardAllData = ref([]);
const isFirstLoad = ref(true);

const filteredCardData = computed(() => {
  return cardAllData.value;
});

const queryloading = ref(false);

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

watch(
  () => filteredCardData.value,
  (newData) => {
    // 如果有数据且当前没有选中患者，且是首次加载，默认选择第一条
    if (
      newData &&
      newData.length > 0 &&
      !cardId.value &&
      isFirstLoad.value &&
      !patientInfo.value?.encounterId
    ) {
      const firstPatient = newData[0];
      if (firstPatient?.encounterId) {
        handleItemClick(firstPatient);
        isFirstLoad.value = false;
      }
    }
  },
  { immediate: true }
);

const handleItemClick = (node) => {
  cardId.value = node.encounterId;
  updatePatientInfo(node);

  diagnosisRef.value?.getList();
  adviceRef.value?.getListInfo();
  adviceRef.value?.getDiagnosisInfo();
};

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

const queryPatientData = async () => {
  if (queryloading.value) return;
  try {
  } catch (error) {
    cardAllData.value = [];
  } finally {
    queryloading.value = false;
  }
};

// 监听 tab 切换，刷新对应的列表
watch(activeTabName, (newTab) => {
  if (newTab === 'test' && testApplicationRef.value?.refresh) {
    testApplicationRef.value.refresh();
  } else if (newTab === 'examine' && examineApplicationRef.value?.refresh) {
    examineApplicationRef.value.refresh();
  } else if (newTab === 'surgery' && surgeryApplicationRef.value?.refresh) {
    surgeryApplicationRef.value.refresh();
  } else if (newTab === 'blood' && bloodTtransfusionAapplicationRef.value?.refresh) {
    bloodTtransfusionAapplicationRef.value.refresh();
  }
});

provide('diagnosisInit', (value) => {
  currentPatientInfo.value = value;
  diagnosisRef.value.getList();
});
provide('getAdviceList', (value) => {
  adviceRef.value.getListInfo();
});
provide('adviceDiagnoInit', (value) => {
  adviceRef.value.getDiagnosisInfo();
});
</script>
<style lang="scss" scoped>
.inpatientDoctor-home-container {
  height: 100%;
  height: calc(100vh - 84px);
  .el-container {
    height: 100%;
  }
  :deep(.el-aside) {
    padding: 0;
  }
  .inpatientDoctor-home-main {
    background-color: #ffffff;
    :deep(.el-header) {
      padding: 0px;
      margin-bottom: 0px;
    }
    .el-main {
      padding: 0px 8px;
    }
    :deep(.patient-tabs) {
      height: 100%;
      .el-tabs__header {
        margin: 0;
      }
      .el-tabs__content {
        height: calc(100% - 40px);
      }
      .el-tab-pane {
        height: 100%;
      }
    }
  }
}
</style>
