<template>
  <div class="nursing-status-container">
    <div class="nursing-status-header">
      <h3>护理状态</h3>
    </div>

    <div v-if="loading" class="loading-container">
      <el-row justify="center">
        <el-col :span="6">
          <el-empty description="正在加载数据..." image-size="100" />
        </el-col>
      </el-row>
    </div>

    <template v-else>
      <!-- 护理状态表格 -->
      <el-table
        :data="nursingItems"
        border
        style="width: 100%"
        class="nursing-table"
        :header-cell-style="{ backgroundColor: '#f5f7fa' }"
      >
        <el-table-column prop="item" label="项目" width="180" align="center" />
        <el-table-column prop="currentStatus" label="当前状态" width="260" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.currentStatus)" size="small" class="status-tag">
              {{ scope.row.currentStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="operation" label="操作" align="center">
          <template #default="scope">
            <div class="operation-content">
              <!-- 护理级别选项 - 水平排列 -->
              <div v-if="scope.row.item === '护理级别'" class="options-horizontal">
                <div
                  v-for="option in nursingLevelList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentNursingLevel },
                  ]"
                  @click="selectNursingLevel(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>

              <!-- 病情选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '病情'" class="options-horizontal">
                <div
                  v-for="option in conditionList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentCondition },
                  ]"
                  @click="selectCondition(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>

              <!-- 护理常规选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '护理常规'" class="options-horizontal">
                <div
                  v-for="option in nursingRoutineList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentNursingRoutine },
                  ]"
                  @click="selectNursingRoutine(option.nursingOrderName)"
                >
                  {{ getShortName(option.nursingOrderName, 10) }}
                </div>
              </div>

              <!-- 饮食选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '饮食'" class="options-horizontal">
                <div
                  v-for="option in dietList"
                  :key="option.definitionId"
                  :class="['option-item', { selected: option.nursingOrderName === currentDiet }]"
                  @click="selectDiet(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>

              <!-- 体位选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '体位'" class="options-horizontal">
                <div
                  v-for="option in positionList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentPosition },
                  ]"
                  @click="selectPosition(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>

              <!-- 陪护选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '陪护'" class="options-horizontal">
                <div
                  v-for="option in companionCareList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentCompanionCare },
                  ]"
                  @click="selectCompanionCare(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>

              <!-- 隔离等级选项 - 水平排列 -->
              <div v-else-if="scope.row.item === '隔离等级'" class="options-horizontal">
                <div
                  v-for="option in isolationLevelList"
                  :key="option.definitionId"
                  :class="[
                    'option-item',
                    { selected: option.nursingOrderName === currentIsolationLevel },
                  ]"
                  @click="selectIsolationLevel(option.nursingOrderName)"
                >
                  {{ option.nursingOrderName }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 操作按钮区域 -->
      <div class="nursing-status-actions">
        <el-button @click="handleCancel" size="small">取消</el-button>
        <el-button type="primary" @click="handleConfirm" size="small">确定</el-button>
      </div>
    </template>
  </div>
</template>
<script setup>
import { getCurrentInstance, onMounted, ref, reactive, watch } from 'vue';
import { getNursingOrdersInfos, saveNursingOrders, getEncounterNursingOrders } from './api';
import { patientInfo } from '../../store/patient.js';
// 导入获取诊断信息的API
import { getEncounterDiagnosis } from '@/views/doctorstation/components/api';

const { proxy } = getCurrentInstance();
const loading = ref(false);

// 护理状态数据列表
const nursingLevelList = ref([]);
const conditionList = ref([]);
const dietList = ref([]);
const positionList = ref([]);
const companionCareList = ref([]);
const isolationLevelList = ref([]);
const nursingRoutineList = ref([]);
const nursingStatusList = ref([]);

// 当前选中的值 - 使用null表示未选择
const currentNursingLevel = ref(null);
const currentCondition = ref(null);
const currentDiet = ref(null);
const currentPosition = ref(null);
const currentNursingRoutine = ref(null);
const currentCompanionCare = ref(null);
const currentIsolationLevel = ref(null);

// 跟踪明确取消选择的项目，用于处理保存后的数据加载
const lastModifiedItems = reactive({
  nursingLevel: false,
  condition: false,
  nursingRoutine: false,
  diet: false,
  position: false,
  companionCare: false,
  isolationLevel: false,
});

// 护理项目列表
const nursingItems = reactive([
  {
    item: '护理级别',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '病情',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '护理常规',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '饮食',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '体位',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '陪护',
    currentStatus: '',
    changing: '',
    operation: '',
  },
  {
    item: '隔离等级',
    currentStatus: '',
    changing: '',
    operation: '',
  },
]);

// 获取标签类型
const getStatusType = (status) => {
  if (status === '无') return 'default';
  return 'primary'; // 改为蓝色
};

// 获取短名称（用于显示）
const getShortName = (fullName, maxLength) => {
  if (fullName.length <= maxLength) return fullName;
  return fullName.substring(0, maxLength) + '...';
};

// 护理级别选择处理
const selectNursingLevel = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentNursingLevel.value === value) {
    currentNursingLevel.value = null;
    lastModifiedItems.nursingLevel = true; // 标记为已明确取消选择
  } else {
    currentNursingLevel.value = value;
    lastModifiedItems.nursingLevel = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const nursingLevelItem = nursingItems.find((item) => item.item === '护理级别');
  if (nursingLevelItem) {
    nursingLevelItem.currentStatus = currentNursingLevel.value || '';
  }
};

// 病情选择处理
const selectCondition = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentCondition.value === value) {
    currentCondition.value = null;
    lastModifiedItems.condition = true; // 标记为已明确取消选择
  } else {
    currentCondition.value = value;
    lastModifiedItems.condition = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const conditionItem = nursingItems.find((item) => item.item === '病情');
  if (conditionItem) {
    conditionItem.currentStatus = currentCondition.value || '';
  }
};

// 护理常规选择处理
const selectNursingRoutine = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentNursingRoutine.value === value) {
    currentNursingRoutine.value = null;
    lastModifiedItems.nursingRoutine = true; // 标记为已明确取消选择
  } else {
    currentNursingRoutine.value = value;
    lastModifiedItems.nursingRoutine = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const nursingRoutineItem = nursingItems.find((item) => item.item === '护理常规');
  if (nursingRoutineItem) {
    nursingRoutineItem.currentStatus = currentNursingRoutine.value || '';
  }
};

// 饮食选择处理
const selectDiet = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentDiet.value === value) {
    currentDiet.value = null;
    lastModifiedItems.diet = true; // 标记为已明确取消选择
  } else {
    currentDiet.value = value;
    lastModifiedItems.diet = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const dietItem = nursingItems.find((item) => item.item === '饮食');
  if (dietItem) {
    dietItem.currentStatus = currentDiet.value || '';
  }
};

// 体位选择处理
const selectPosition = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentPosition.value === value) {
    currentPosition.value = null;
    lastModifiedItems.position = true; // 标记为已明确取消选择
  } else {
    currentPosition.value = value;
    lastModifiedItems.position = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const positionItem = nursingItems.find((item) => item.item === '体位');
  if (positionItem) {
    positionItem.currentStatus = currentPosition.value || '';
  }
};

// 陪护选择处理
const selectCompanionCare = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentCompanionCare.value === value) {
    currentCompanionCare.value = null;
    lastModifiedItems.companionCare = true; // 标记为已明确取消选择
  } else {
    currentCompanionCare.value = value;
    lastModifiedItems.companionCare = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const companionCareItem = nursingItems.find((item) => item.item === '陪护');
  if (companionCareItem) {
    companionCareItem.currentStatus = currentCompanionCare.value || '';
  }
};

// 隔离等级选择处理
const selectIsolationLevel = (value) => {
  // 如果点击的是当前选中的值，则取消选中（设为null）
  if (currentIsolationLevel.value === value) {
    currentIsolationLevel.value = null;
    lastModifiedItems.isolationLevel = true; // 标记为已明确取消选择
  } else {
    currentIsolationLevel.value = value;
    lastModifiedItems.isolationLevel = false; // 有选择值，清除取消标记
  }
  // 更新当前状态显示
  const isolationLevelItem = nursingItems.find((item) => item.item === '隔离等级');
  if (isolationLevelItem) {
    isolationLevelItem.currentStatus = currentIsolationLevel.value || '';
  }
};

// 从后端获取护理状态数据
const fetchNursingStatusData = () => {
  // 显示加载状态
  loading.value = true;

  // 调用后端接口
  getNursingOrdersInfos({
    // encounterId: patientInfo.value.encounterId
  })
    .then((res) => {
      // 隐藏加载状态
      loading.value = false;

      if (res.code === 200 && res.data) {
        // 填充各列表数据
        nursingLevelList.value = res.data.nursingList || [];
        conditionList.value = res.data.conditionList || [];
        dietList.value = res.data.dietList || [];
        positionList.value = res.data.positionList || [];
        companionCareList.value = res.data.companionCareList || [];
        isolationLevelList.value = res.data.isolationLevelList || [];
        nursingRoutineList.value = res.data.nursingRoutineList || [];

        // 确保选项数据加载完成后，如果有患者信息则获取患者护理医嘱信息
        if (patientInfo.value?.encounterId) {
          fetchPatientNursingOrders();
        }
      }
    })
    .catch((error) => {
      // 隐藏加载状态
      loading.value = false;

      // 记录错误日志
      console.error('获取护理状态数据失败:', error);

      // 添加用户友好的错误提示
      if (proxy && proxy.$message) {
        proxy.$message({
          message: '获取护理状态数据失败，请稍后重试',
          type: 'error',
        });
      }
    });
};

// 组件挂载时自动获取数据
onMounted(() => {
  fetchNursingStatusData();
});

// 监听患者信息变化，重新获取数据
watch(
  patientInfo,
  (newInfo) => {
    if (newInfo?.encounterId) {
      // 重置当前状态
      resetCurrentStatus();
      // 重新获取护理选项数据
      fetchNursingStatusData();
      // 延迟一小段时间再获取患者的护理医嘱信息，确保选项数据已经加载完成
      setTimeout(() => {
        fetchPatientNursingOrders();
      }, 100);
    }
  },
  { deep: true }
);

// 重置当前选择状态
const resetCurrentStatus = () => {
  currentNursingLevel.value = null;
  currentCondition.value = null;
  currentDiet.value = null;
  currentPosition.value = null;
  currentNursingRoutine.value = null;
  currentCompanionCare.value = null;
  currentIsolationLevel.value = null;

  // 重置取消选择跟踪对象
  Object.keys(lastModifiedItems).forEach((key) => {
    lastModifiedItems[key] = false;
  });

  // 更新显示状态
  nursingItems.forEach((item) => {
    item.currentStatus = '';
  });
};

// 获取患者的护理医嘱信息
const fetchPatientNursingOrders = () => {
  // 确保有有效的就诊ID
  if (!patientInfo.value?.encounterId) return;

  // 调用API获取患者的护理医嘱数据
  getEncounterNursingOrders({
    encounterId: patientInfo.value.encounterId,
  })
    .then((res) => {
      if (res.code === 200 && res.data) {
        // 根据后端返回的definitionId匹配对应的选项
        // 护理级别 (categoryEnum: 26)
        // 只有当项目未被标记为明确取消选择时，才从后端加载数据
        if (!lastModifiedItems.nursingLevel && res.data.nursing?.definitionId) {
          const definitionId = res.data.nursing.definitionId;
          // 在nursingLevelList中查找对应的选项
          const matchedItem = nursingLevelList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentNursingLevel.value = matchedItem.nursingOrderName;
            const nursingLevelItem = nursingItems.find((item) => item.item === '护理级别');
            if (nursingLevelItem) {
              nursingLevelItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentNursingLevel.value = null;
            const nursingLevelItem = nursingItems.find((item) => item.item === '护理级别');
            if (nursingLevelItem) {
              nursingLevelItem.currentStatus = '';
            }
          }
        } else {
          currentNursingLevel.value = null;
          const nursingLevelItem = nursingItems.find((item) => item.item === '护理级别');
          if (nursingLevelItem) {
            nursingLevelItem.currentStatus = '';
          }
        }

        // 病情 (categoryEnum: 38)
        if (!lastModifiedItems.condition && res.data.condition?.definitionId) {
          const definitionId = res.data.condition.definitionId;
          const matchedItem = conditionList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentCondition.value = matchedItem.nursingOrderName;
            const conditionItem = nursingItems.find((item) => item.item === '病情');
            if (conditionItem) {
              conditionItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentCondition.value = null;
            const conditionItem = nursingItems.find((item) => item.item === '病情');
            if (conditionItem) {
              conditionItem.currentStatus = '';
            }
          }
        } else {
          currentCondition.value = null;
          const conditionItem = nursingItems.find((item) => item.item === '病情');
          if (conditionItem) {
            conditionItem.currentStatus = '';
          }
        }

        // 护理常规 (categoryEnum: 39)
        if (!lastModifiedItems.nursingRoutine && res.data.nursingRoutine?.definitionId) {
          const definitionId = res.data.nursingRoutine.definitionId;
          const matchedItem = nursingRoutineList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentNursingRoutine.value = matchedItem.nursingOrderName;
            const nursingRoutineItem = nursingItems.find((item) => item.item === '护理常规');
            if (nursingRoutineItem) {
              nursingRoutineItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentNursingRoutine.value = null;
            const nursingRoutineItem = nursingItems.find((item) => item.item === '护理常规');
            if (nursingRoutineItem) {
              nursingRoutineItem.currentStatus = '';
            }
          }
        } else {
          currentNursingRoutine.value = null;
          const nursingRoutineItem = nursingItems.find((item) => item.item === '护理常规');
          if (nursingRoutineItem) {
            nursingRoutineItem.currentStatus = '';
          }
        }

        // 饮食 (categoryEnum: 27)
        if (!lastModifiedItems.diet && res.data.diet?.definitionId) {
          const definitionId = res.data.diet.definitionId;
          const matchedItem = dietList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentDiet.value = matchedItem.nursingOrderName;
            const dietItem = nursingItems.find((item) => item.item === '饮食');
            if (dietItem) {
              dietItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentDiet.value = null;
            const dietItem = nursingItems.find((item) => item.item === '饮食');
            if (dietItem) {
              dietItem.currentStatus = '';
            }
          }
        } else {
          currentDiet.value = null;
          const dietItem = nursingItems.find((item) => item.item === '饮食');
          if (dietItem) {
            dietItem.currentStatus = '';
          }
        }

        // 体位 (categoryEnum: 40)
        if (!lastModifiedItems.position && res.data.position?.definitionId) {
          const definitionId = res.data.position.definitionId;
          const matchedItem = positionList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentPosition.value = matchedItem.nursingOrderName;
            const positionItem = nursingItems.find((item) => item.item === '体位');
            if (positionItem) {
              positionItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentPosition.value = null;
            const positionItem = nursingItems.find((item) => item.item === '体位');
            if (positionItem) {
              positionItem.currentStatus = '';
            }
          }
        } else {
          currentPosition.value = null;
          const positionItem = nursingItems.find((item) => item.item === '体位');
          if (positionItem) {
            positionItem.currentStatus = '';
          }
        }

        // 陪护 (categoryEnum: 41)
        if (!lastModifiedItems.companionCare && res.data.companionCare?.definitionId) {
          const definitionId = res.data.companionCare.definitionId;
          const matchedItem = companionCareList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentCompanionCare.value = matchedItem.nursingOrderName;
            const companionCareItem = nursingItems.find((item) => item.item === '陪护');
            if (companionCareItem) {
              companionCareItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentCompanionCare.value = null;
            const companionCareItem = nursingItems.find((item) => item.item === '陪护');
            if (companionCareItem) {
              companionCareItem.currentStatus = '';
            }
          }
        } else {
          currentCompanionCare.value = null;
          const companionCareItem = nursingItems.find((item) => item.item === '陪护');
          if (companionCareItem) {
            companionCareItem.currentStatus = '';
          }
        }

        // 隔离等级 (categoryEnum: 42)
        if (!lastModifiedItems.isolationLevel && res.data.isolationLevel?.definitionId) {
          const definitionId = res.data.isolationLevel.definitionId;
          const matchedItem = isolationLevelList.value.find(
            (item) => item.id === definitionId || item.definitionId === definitionId
          );
          if (matchedItem) {
            currentIsolationLevel.value = matchedItem.nursingOrderName;
            const isolationLevelItem = nursingItems.find((item) => item.item === '隔离等级');
            if (isolationLevelItem) {
              isolationLevelItem.currentStatus = matchedItem.nursingOrderName;
            }
          } else {
            currentIsolationLevel.value = null;
            const isolationLevelItem = nursingItems.find((item) => item.item === '隔离等级');
            if (isolationLevelItem) {
              isolationLevelItem.currentStatus = '';
            }
          }
        } else {
          currentIsolationLevel.value = null;
          const isolationLevelItem = nursingItems.find((item) => item.item === '隔离等级');
          if (isolationLevelItem) {
            isolationLevelItem.currentStatus = '';
          }
        }
      }
    })
    .catch((error) => {
      console.error('获取患者护理医嘱信息失败:', error);
    });
};

// 定义暴露的属性
defineExpose({
  refreshData: fetchNursingStatusData,
});

// 取消按钮处理函数
const handleCancel = () => {
  // 重置所有选择状态
  resetCurrentStatus();

  // 重新获取患者的护理医嘱信息
  if (patientInfo.value?.encounterId) {
    fetchPatientNursingOrders();
  }

  // 添加提示信息
  if (proxy && proxy.$message) {
    proxy.$message({
      message: '已取消设置',
      type: 'info',
    });
  }
};

// 日期格式化函数
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 确认按钮处理函数
const handleConfirm = async () => {
  // 检查是否有有效的就诊ID和患者ID
  if (!patientInfo.value?.encounterId || !patientInfo.value?.patientId) {
    if (proxy && proxy.$message) {
      proxy.$message({
        message: '请先选择患者',
        type: 'warning',
      });
    }
    return;
  }

  // 显示加载状态
  loading.value = true;

  // 获取真实诊断ID
  let conditionId = null;
  let encounterDiagnosisId = null;

  try {
    // 确保patientInfo和encounterId存在
    if (patientInfo.value && patientInfo.value.encounterId) {
      console.log('开始获取诊断信息，encounterId:', patientInfo.value.encounterId);
      // 调用API获取患者的诊断信息
      const diagnosisRes = await getEncounterDiagnosis(patientInfo.value.encounterId);
      // 检查API响应是否成功
      if (
        diagnosisRes &&
        diagnosisRes.code === 200 &&
        diagnosisRes.data &&
        Array.isArray(diagnosisRes.data) &&
        diagnosisRes.data.length > 0
      ) {
        const firstDiagnosis = diagnosisRes.data[0];
        console.log('获取到的第一个诊断信息:', firstDiagnosis);

        // 直接使用API返回的真实诊断ID
        if (firstDiagnosis.conditionId && firstDiagnosis.encounterDiagnosisId) {
          conditionId = firstDiagnosis.conditionId;
          encounterDiagnosisId = firstDiagnosis.encounterDiagnosisId;
          console.log(
            '使用API返回的真实诊断ID - conditionId:',
            conditionId,
            'encounterDiagnosisId:',
            encounterDiagnosisId
          );
        }
      }
    }

    // 如果无法获取真实诊断ID，才使用encounterId作为后备
    if (!conditionId || !encounterDiagnosisId) {
      conditionId = patientInfo.value?.encounterId;
      encounterDiagnosisId = patientInfo.value?.encounterId;
      console.log('使用encounterId作为诊断ID的后备值:', conditionId);
    }

    // 准备提交的数据，包含就诊相关信息和护理项目数组
    const submitData = {
      // 就诊id - 从store中获取真实的就诊ID
      encounterId: patientInfo.value.encounterId,
      // 患者id - 从store中获取真实的患者ID
      patientId: patientInfo.value.patientId,
      // 诊断ID - 使用真实的诊断ID
      conditionId: conditionId,
      // 就诊诊断id - 使用真实的诊断ID
      encounterDiagnosisId: encounterDiagnosisId,
      // 医嘱开始时间，格式化为yyyy-MM-dd HH:mm:ss
      startTime: formatDate(new Date()),
    };

    // 准备护理项目数据数组，按照后端要求的格式
    const nursingOrdersSaveDetailDtoList = [];

    // 添加护理级别 - 根据选项找到对应的definitionId
    const selectedLevel = nursingLevelList.value.find(
      (item) => item.nursingOrderName === currentNursingLevel.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedLevel?.definitionId || null,
      categoryEnum: 26, // 护理级别的categoryCode
    });

    // 添加病情
    const selectedCondition = conditionList.value.find(
      (item) => item.nursingOrderName === currentCondition.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedCondition?.definitionId || null,
      categoryEnum: 38, // 病情的categoryCode
    });

    // 添加护理常规
    const selectedRoutine = nursingRoutineList.value.find(
      (item) => item.nursingOrderName === currentNursingRoutine.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedRoutine?.definitionId || null,
      categoryEnum: 39, // 护理常规的categoryCode
    });

    // 添加饮食
    const selectedDiet = dietList.value.find((item) => item.nursingOrderName === currentDiet.value);
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedDiet?.definitionId || null,
      categoryEnum: 27, // 膳食的categoryCode
    });

    // 添加体位
    const selectedPosition = positionList.value.find(
      (item) => item.nursingOrderName === currentPosition.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedPosition?.definitionId || null,
      categoryEnum: 40, // 体位的categoryCode
    });

    // 添加陪护
    const selectedCompanion = companionCareList.value.find(
      (item) => item.nursingOrderName === currentCompanionCare.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedCompanion?.definitionId || null,
      categoryEnum: 41, // 陪护的categoryCode
    });

    // 添加隔离等级
    const selectedIsolation = isolationLevelList.value.find(
      (item) => item.nursingOrderName === currentIsolationLevel.value
    );
    nursingOrdersSaveDetailDtoList.push({
      definitionId: selectedIsolation?.definitionId || null,
      categoryEnum: 42, // 隔离等级的categoryCode
    });

    // 将护理项目数组添加到提交数据中
    submitData.nursingOrdersSaveDetailDtoList = nursingOrdersSaveDetailDtoList;

    // 在控制台输出传给后端的数据
    console.log('提交给后端的护理状态数据:', submitData);

    // 调用API保存数据
    const res = await saveNursingOrders(submitData);

    // 处理成功响应
    if (res.code === 200) {
      if (proxy && proxy.$message) {
        proxy.$message({
          message: '护理医嘱保存成功',
          type: 'success',
        });
      }

      // 先重置当前状态，确保清除所有选择和跟踪标记
      resetCurrentStatus();
      // 延迟一小段时间再获取数据，确保后端已更新
      setTimeout(() => {
        // 重新加载患者的护理医嘱信息
        fetchPatientNursingOrders();
      }, 100);
    } else {
      if (proxy && proxy.$message) {
        proxy.$message({
          message: res.message || '保存失败',
          type: 'error',
        });
      }
    }
  } catch (error) {
    // 处理错误
    console.error('保存护理医嘱失败:', error);
    if (proxy && proxy.$message) {
      proxy.$message({
        message: '保存失败，请稍后重试',
        type: 'error',
      });
    }
  } finally {
    // 隐藏加载状态
    loading.value = false;

    // 保存成功后，重新获取患者的护理医嘱信息以更新显示
    if (patientInfo.value?.encounterId) {
      fetchPatientNursingOrders();
    }
  }
};
</script>
<style lang="scss" scoped>
/* 操作按钮区域样式 */
.nursing-status-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}
.nursing-status-container {
  height: 100%;
  padding: 15px;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  overflow: auto;
}

.nursing-status-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.nursing-status-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.loading-container {
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nursing-table {
  flex: 1;
  overflow: auto;
  font-size: 14px;
  color: #303133;

  ::v-deep .el-table__header {
    font-weight: 600;
  }

  ::v-deep .el-table__cell {
    padding: 12px 10px; /* 增加左右内边距 */
    text-align: left; /* 调整为左对齐 */
    border-right: 1px solid #ebeef5;
    white-space: normal; /* 允许换行 */
    word-break: break-word;
    min-height: 40px; /* 设置最小高度 */
  }

  ::v-deep .el-table__row:hover {
    background-color: #f5f7fa;
  }

  ::v-deep .el-table__row:nth-child(odd) {
    background-color: #fafafa;
  }

  /* 为操作列设置更宽的最小宽度 */
  ::v-deep .el-table__column--operation {
    min-width: 400px !important;
  }
}

.status-tag {
  padding: 4px 12px;
  border-radius: 4px;
  background-color: #409eff; /* 蓝色背景 */
  color: #ffffff; /* 白色文字 */
}

.condition-text {
  color: #409eff;
  font-weight: 500;
}

.operation-content {
  display: flex;
  height: 100%;
  width: 100%;
  overflow: visible;
}

/* 水平排列样式 */
.options-horizontal {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: flex-start;
  width: 100%;
  align-items: flex-start;
}

.option-item {
  padding: 6px 12px;
  margin: 2px 0;
  border-radius: 4px;
  background-color: #f0f2f5;
  color: #606266;
  font-size: 13px;
  text-align: center;
  transition: all 0.3s ease;
  cursor: pointer;
  white-space: normal; /* 允许文本换行 */
  max-width: 150px; /* 设置最大宽度 */
  min-width: 80px; /* 设置最小宽度 */
  word-break: keep-all; /* 保持单词完整性 */
}

/* 增强选中状态样式的优先级 */
.options-horizontal .option-item.selected {
  background-color: #409eff !important;
  color: #ffffff !important;
}

.option-item:hover:not(.selected) {
  background-color: #ecf5ff;
  color: #409eff;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .nursing-table {
    ::v-deep .el-table__cell {
      padding: 8px 8px;
    }

    ::v-deep .el-table__column--operation {
      min-width: 350px !important;
    }
  }

  .option-item {
    padding: 4px 8px;
    font-size: 12px;
    max-width: 130px;
  }
}

@media (max-width: 768px) {
  .nursing-status-container {
    padding: 10px;
  }

  .nursing-table {
    font-size: 12px;

    ::v-deep .el-table__cell {
      padding: 6px 6px;
    }

    ::v-deep .el-table__column--operation {
      min-width: 300px !important;
    }
  }

  .options-horizontal {
    gap: 5px;
  }

  .option-item {
    padding: 3px 6px;
    font-size: 11px;
    max-width: 120px;
  }
}
</style>
