<template>
  <div class="app-container">
    <div class="left-menu">
      <div class="back-button" @click="goBack">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        返回患者列表
      </div>
      <el-menu :default-active="activeMenu" class="medical-menu" @select="handleSelect">
        <el-menu-item index="medicalRecord">
          <span>营养病例</span>
        </el-menu-item>
        <el-menu-item index="visitRecord">
          <span>就诊记录</span>
        </el-menu-item>
        <el-menu-item index="checkLabel">
          <span>检查指标</span>
        </el-menu-item>
        <el-menu-item index="nutritionScreeningAdd" v-show="false">
          <span>营养筛查新增</span>
        </el-menu-item>
        <el-menu-item index="nutritionScreening">
          <span>营养筛查</span>
        </el-menu-item>
        <el-menu-item index="nutritionEvaluationAdd" v-show="false">
          <span>营养评估新增</span>
        </el-menu-item>
        <el-menu-item index="nutritionEvaluation">
          <span>营养评估</span>
        </el-menu-item>
        <el-menu-item index="nutritionDiagnosis">
          <span>营养诊断</span>
        </el-menu-item>
        <el-sub-menu index="nutritionIntervention">
          <template #title>营养干预</template>
          <el-menu-item index="nutritionSetting">营养设定</el-menu-item>
          <el-menu-item index="enteralNutrition">肠内营养</el-menu-item>
          <el-menu-item index="parenteralNutrition">肠外营养</el-menu-item>
          <el-menu-item index="dietTherapy">膳食治疗</el-menu-item>
        </el-sub-menu>
        <el-menu-item index="nutritionMonitor">
          <span>营养监测</span>
        </el-menu-item>
        <el-menu-item index="nutritionEducation">
          <span>营养宣教</span>
        </el-menu-item>
      </el-menu>
      <div class="search-bar">
        <el-input v-model="searchValue" placeholder="姓名/床号/门诊号" size="small" class="search-input" @keyup.enter="handleSearch" />
        <el-button size="small" type="primary" class="search-btn" @click="handleSearch">搜索</el-button>
      </div>
      <div class="patient-tabs">
        <el-tabs v-model="patientTab" size="small" stretch @tab-change="handleTabChange">
          <el-tab-pane :label="`待诊${waitingCount}`" name="wait" />
          <el-tab-pane :label="`诊中${treatingCount}`" name="doing" />
          <el-tab-pane :label="`已诊${treatedCount}`" name="done" />
        </el-tabs>
      </div>
      <div class="patient-table">
        <el-table
          :data="patientList"
          border
          size="small"
          height="80%"
          :show-header="true"
          class="table-patients"
          :row-class-name="tableRowClassName"
          @row-click="handleRowClick"
        >
          <el-table-column prop="name" label="姓名" width="60" />
          <el-table-column prop="gender" label="性别" width="50" />
          <el-table-column prop="age" label="年龄" width="80" />
        </el-table>
      </div>
      <div class="nav-btns">
        <el-button size="small" @click="handlePrev">上一位</el-button>
        <el-button size="small" type="primary" @click="handleNext">下一位</el-button>
      </div>
    </div>
    <div class="main-content">
      <el-row>
        <div class="patient-left-info">
          <el-row class="info-row">
            <span class="name">{{ patientInfo.name }}</span>
            <span class="age">{{ patientInfo.age }}</span>
            <span class="gender-icon" :class="patientInfo.gender === '男' ? 'male' : 'female'">
              {{ patientInfo.gender === '男' ? '♂' : '♀' }}
            </span>
          </el-row>
          <el-row style="margin-top: 10px; margin-left: 10%">
            <el-button size="small" @click="handleEdit">编辑</el-button>
            <el-button size="small" type="primary" @click="handleDetail">详情</el-button>
          </el-row>
        </div>
        <div class="patient-right-info">
          <el-row>
            <span>门诊号：{{ patientInfo.outpatientNo }}</span>
            <span style="margin-left: 30px">科室：{{ patientInfo.deptName }}</span>
            <span style="margin-left: 30px">营养诊断：</span>
          </el-row>
          <el-row>
            <span>会诊结果：</span>
          </el-row>
        </div>
      </el-row>
      <component :is="currentComponent" v-if="currentComponent" :patient-info="patientInfo" @change="handleSelect" />
    </div>

    <!-- 患者详情弹窗 -->
    <DetailDialog
      v-model:visible="showDetailDialog"
      :detail-data="detailData"
      :physical-activity-dict="physicalActivityDict"
      @close="handleDetailClose"
    />
    <!-- 新增：编辑弹窗 -->
    <EditDialog v-model:visible="showEditDialog" :edit-data="editData" @close="handleEditClose" @save="handleEditSave" />
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, getCurrentInstance, toRefs, defineAsyncComponent} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ArrowLeft} from '@element-plus/icons-vue';
import {listTreatmentUser, getTreatmentUser} from '@/api/workbench/treatmentUser';
import DetailDialog from './detailDialog.vue';
import EditDialog from './editDialog.vue';

// 动态导入组件
const MedicalRecord = defineAsyncComponent(() => import('./levelMenu.vue'));
const NutritionScreening = defineAsyncComponent(() => import('@/views/patients/screening/index.vue'));
const NutritionEvaluation = defineAsyncComponent(() => import('@/views/patients/evaluation/index.vue'));
const NutriDiagnosis = defineAsyncComponent(() => import('@/views/patients/nutriDiagnosis/index.vue'));
const CheckLabel = defineAsyncComponent(() => import('@/views/patients/checkLabel/index.vue'));
const NutritionScreeningAdd = defineAsyncComponent(() => import('@/views/patients/screening/add.vue'));
const NutritionEvaluationAdd = defineAsyncComponent(() => import('@/views/patients/evaluation/add.vue'));

const NutritionEducation = defineAsyncComponent(() => import('@/views/patients/nutritionEducation/index.vue'));
const NutritionSetting = defineAsyncComponent(() => import('@/views/patients/nutritionSetting/index.vue'));
const DietTherapy = defineAsyncComponent(() => import('@/views/patients/dietTherapy/index.vue'));

const componentMap = {
  medicalRecord: MedicalRecord, // “营养病例”对应MedicalRecord.vue
  checkLabel: CheckLabel, // “检查标签”对应CheckLabel.vue
  nutritionDiagnosis: NutriDiagnosis,

  nutritionScreening: NutritionScreening,
  nutritionScreeningAdd: NutritionScreeningAdd,
  nutritionEvaluation: NutritionEvaluation,
  nutritionEvaluationAdd: NutritionEvaluationAdd,

  nutritionEducation: NutritionEducation,
  nutritionSetting: NutritionSetting,
  dietTherapy: DietTherapy
  // ... 其它映射
};
const currentComponent = ref(componentMap['medicalRecord']); // 默认显示
const route = useRoute();
const router = useRouter();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const activeMenu = ref('medicalRecord');

const patientInfo = ref({
  id: '',
  name: '',
  age: '',
  gender: '',
  type: '',
  deptId: '',
  deptName: '',
  outpatientNo: ''
});

// 弹窗控制
const showDetailDialog = ref(false);
const detailData = ref({});
const physicalActivityDict = ref([]);

const showEditDialog = ref(false);
const editData = ref({} as any);

const handleSelect = (key: string, other?: string[]) => {
  if (key == 'nutritionScreeningAdd' || key == 'nutritionEvaluationAdd') {
    activeMenu.value = key.replace('Add', '');
  } else {
    activeMenu.value = key;
  }
  currentComponent.value = componentMap[key] || null;
  patientInfo.value['other'] = other;
  patientInfo.value.type = route.query.type;
  patientInfo.value.outpatientNo = route.query.outpatientNo;
};

const goBack = () => {
  router.back();
};

const searchValue = ref('');
const patientTab = ref('wait');
const patientList = ref([]);
const loading = ref(false);

const currentPatientIndex = ref(0);

const tableRowClassName = ({row, rowIndex}) => {
  return rowIndex === currentPatientIndex.value ? 'current-row' : '';
};

const handleRowClick = (row, column, event) => {
  activeMenu.value = 'medicalRecord';
  currentComponent.value = componentMap['medicalRecord'];
  const idx = patientList.value.findIndex((item) => item === row);
  patientInfo.value = row;
  patientInfo.value.type = route.query.type;
  patientInfo.value.outpatientNo = route.query.outpatientNo;
  if (idx !== -1) {
    currentPatientIndex.value = idx;
  }
};

const handlePrev = () => {
  activeMenu.value = 'medicalRecord';
  currentComponent.value = componentMap['medicalRecord'];
  if (currentPatientIndex.value > 0) {
    patientInfo.value = patientList.value[currentPatientIndex.value - 1];
    patientInfo.value.type = route.query.type;
    patientInfo.value.outpatientNo = route.query.outpatientNo;
    currentPatientIndex.value--;
  }
};

const handleNext = () => {
  activeMenu.value = 'medicalRecord';
  currentComponent.value = componentMap['medicalRecord'];
  patientInfo.value = patientList.value[currentPatientIndex.value + 1];
  patientInfo.value.type = route.query.type;
  patientInfo.value.outpatientNo = route.query.outpatientNo;
  if (currentPatientIndex.value < patientList.value.length - 1) {
    currentPatientIndex.value++;
  }
};
const handleTabChange = (tab: string) => {
  if (tab == 'wait') {
    getList();
  } else {
    patientList.value = [];
  }
};
// 编辑按钮处理
const handleEdit = async () => {
  if (!patientInfo.value.id) {
    proxy?.$modal.msgError('请先选择患者');
    return;
  }

  try {
    // 获取患者详细信息
    const res = await getTreatmentUser(patientInfo.value.id);
    editData.value = res.data;
    showEditDialog.value = true;
  } catch (error) {
    console.error('获取患者详情失败:', error);
    proxy?.$modal.msgError('获取患者详情失败');
  }
};

// 详情按钮处理
const handleDetail = async () => {
  if (!patientInfo.value.id) {
    proxy?.$modal.msgError('请先选择患者');
    return;
  }

  try {
    // 获取患者详细信息
    const res = await getTreatmentUser(patientInfo.value.id);
    detailData.value = res.data;
    showDetailDialog.value = true;
  } catch (error) {
    console.error('获取患者详情失败:', error);
    proxy?.$modal.msgError('获取患者详情失败');
  }
};

// 详情弹窗关闭处理
const handleDetailClose = () => {
  showDetailDialog.value = false;
  detailData.value = {};
};

const handleEditClose = () => {
  showEditDialog.value = false;
  editData.value = {};
};

const handleEditSave = (data) => {
  // 可在此处调用保存API，保存后刷新列表
  showEditDialog.value = false;
  proxy?.$modal.msgSuccess('保存成功');
  getList();
};

const waitingCount = ref(0);
const treatingCount = ref(0);
const treatedCount = ref(0);

const getList = async () => {
  loading.value = true;
  try {
    const params: any = {
      pageNum: 1,
      pageSize: 10
    };
    if (searchValue.value) {
      params.searchFlag = searchValue.value;
    }
    const res = await listTreatmentUser(params);
    console.log('res', JSON.stringify(res));

    patientList.value = (res.rows || []).map((item) => ({
      id: item.id,
      name: item.treatName,
      type: item.type, // 0: 门诊，1: 住院
      deptId: item.doorId,
      deptName: item.deptName,
      outpatientNo: item.outpatientNo,
      gender: item.sex === '0' ? '男' : item.sex === '1' ? '女' : '',
      age: item.age
    }));
    waitingCount.value = patientList.value.length;

    // 如果有患者数据，根据路由参数或默认选中第一个
    if (patientList.value.length > 0) {
      const {id} = route.query;
      if (id) {
        // 查找从工作台点击进入的患者
        const targetIndex = patientList.value.findIndex((patient) => patient.id === id);
        if (targetIndex !== -1) {
          patientInfo.value = patientList.value[targetIndex];
          patientInfo.value.type = route.query.type;
          patientInfo.value.outpatientNo = route.query.outpatientNo;
          currentPatientIndex.value = targetIndex;
        } else {
          // 如果没找到，默认选中第一个
          patientInfo.value = patientList.value[0];
          currentPatientIndex.value = 0;
        }
      } else {
        // 没有路由参数，默认选中第一个
        patientInfo.value = patientList.value[0];
        patientInfo.value.type = route.query.type;
        patientInfo.value.outpatientNo = route.query.outpatientNo;
        currentPatientIndex.value = 0;
      }
    }

    loading.value = false;
  } catch (error) {
    console.error('获取列表失败:', error);
    loading.value = false;
  }
};

const handleSearch = () => {
  getList();
};

onMounted(() => {
  // 获取体力活动字典
  const {physical_activity} = toRefs(proxy?.useDict('physical_activity'));
  physicalActivityDict.value = physical_activity?.value || [];
  patientInfo.value.type = route.query.type;
  patientInfo.value.outpatientNo = route.query.outpatientNo;
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  height: calc(100vh - 50px);
  background-color: #f5f7fa;
  margin: -10px;
}

.left-menu {
  width: 220px;
  background-color: #fff;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
  padding-bottom: 60px;
  /* 增加底部padding，为按钮留出空间 */
  position: relative;
  overflow: hidden;
  /* 防止内容溢出 */
}

.back-button {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #409eff;
  border-bottom: 1px solid #e6e6e6;
  font-size: 14px;

  .el-icon {
    font-size: 16px;
  }

  &:hover {
    background-color: #f5f7fa;
  }
}

.medical-menu {
  border-right: none;

  :deep(.el-menu-item) {
    font-size: 14px;
    height: 40px;
    line-height: 40px;
  }
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 8px 12px 0 12px;
  gap: 6px;
}

.search-input {
  flex: 1;
}

.search-btn {
  margin-left: 0;
}

.patient-tabs {
  padding: 0 12px;
  margin-top: 8px;
}

.patient-table {
  min-width: 220px;
  overflow-x: auto;
}

.table-patients {
  table-layout: fixed;
  width: 100%;
  min-width: 220px;
  white-space: nowrap;
  .el-table__header th {
    background: #f5f7fa;
    color: #409eff;
    font-weight: bold;
    font-size: 13px;
    padding: 4px 0;
  }
  .el-table__row {
    cursor: pointer;
  }
  .el-table__row.current-row {
    background: #eaf4ff !important;
  }
}

.nav-btns {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 12px;
  padding: 0 12px;
  background: #fff;
  z-index: 1;
  width: calc(100% - 24px);
  margin: 0 auto;
}

.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

.patient-left-info {
  background-color: #fff;
  height: 100px;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
  width: 11%;
}

.patient-right-info {
  background-color: #fff;
  height: 100px;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  width: 86%;
  margin-left: 30px;
}

.info-row {
  display: flex;
  align-items: center;
  white-space: nowrap;
}
.info-row .name {
  font-size: 22px;
}
.info-row .age {
  margin-left: 30px;
}
.gender-icon {
  margin-left: 30px;
  font-size: 25px;
  font-weight: bold;
  line-height: 1;
  display: inline-block;
  vertical-align: middle;
}
.gender-icon.female {
  color: #ff4949;
}
.gender-icon.male {
  color: #409eff;
}
</style>
