<template>
  <div class="page-container">
    <div class="page-header">
      <span class="breadcrumb-label">当前位置：</span>
      <span class="breadcrumb-path">院区信息管理</span>
      <span class="breadcrumb-separator">&gt;</span>
      <span class="breadcrumb-current">患者管理</span>
    </div>

    <!-- 查询栏第一行 -->
    <div class="search-bar">
      <div class="search-item">
        <label>患者姓名：</label>
        <input type="text" v-model="searchForm.name" placeholder="请输入患者姓名" />
      </div>
      <div class="search-item">
        <label>所属科室：</label>
        <select v-model="searchForm.deptCode" @change="onDeptChange">
          <option value="">全部</option>
          <option v-for="(dept, index) in deptList" :key="index" :value="dept">{{ dept }}</option>
        </select>
      </div>
      <div class="search-item">
        <label>所属病区：</label>
        <select v-model="searchForm.wardCode" @change="onWardChange">
          <option value="">全部</option>
          <option v-for="(ward, index) in wardList" :key="index" :value="ward">{{ ward }}</option>
        </select>
      </div>
      <div class="search-item">
        <label>房间号：</label>
        <select v-model="searchForm.roomNo" @change="onRoomChange">
          <option value="">全部</option>
          <option v-for="(room, index) in roomList" :key="index" :value="room">{{ room }}</option>
        </select>
      </div>
      <div class="search-item">
        <label>床位号：</label>
        <select v-model="searchForm.bedNo">
          <option value="">全部</option>
          <option v-for="(bed, index) in bedList" :key="index" :value="bed">{{ bed }}</option>
        </select>
      </div>
    </div>

    <!-- 查询栏第二行 -->
    <div class="search-bar">
      <div class="search-item">
        <label>住院号：</label>
        <input type="text" v-model="searchForm.inpatientNo" placeholder="请输入住院号" />
      </div>
      <div class="search-item">
        <label>护理级别：</label>
        <select v-model="searchForm.nurseLevel">
          <option value="">全部</option>
          <option v-for="(level, index) in nurseLevelList" :key="index" :value="level">{{ formatNurseLevel(level) }}</option>
        </select>
      </div>
      <div class="search-item">
        <label>在院状态：</label>
        <select v-model="searchForm.inpatientStatus">
          <option value="">全部</option>
          <option v-for="(status, index) in inpatientStatusList" :key="index" :value="status">{{ formatInpatientStatus(status) }}</option>
        </select>
      </div>
      <div class="search-item">
        <label>入院时间：</label>
        <input type="date" v-model="searchForm.admissionDateStart" />
        <span class="date-sep">~</span>
        <input type="date" v-model="searchForm.admissionDateEnd" />
      </div>
      <button class="search-btn" @click="handleSearch">查询</button>
      <button class="reset-btn" @click="handleReset">重置</button>
    </div>

    <!-- 数据列表 -->
    <div class="table-container">
      <div v-if="loading" class="loading-mask">
        <div class="loading-spinner"></div>
        <span>加载中...</span>
      </div>
      <table class="data-table" v-show="!loading">
        <thead>
          <tr>
            <th>患者姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>住院号</th>
            <th>所属科室</th>
            <th>所属病区</th>
            <th>房间号</th>
            <th>床位号</th>
            <th>护理级别</th>
            <th>在院状态</th>
            <th>入院时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in tableData" :key="item.id">
            <td>{{ item.name }}</td>
            <td>{{ item.sex }}</td>
            <td>{{ item.age }}</td>
            <td>{{ item.inpatientNo }}</td>
            <td>{{ item.deptCode }}</td>
            <td>{{ item.wardCode }}</td>
            <td>{{ item.roomNo }}</td>
            <td>{{ item.bedNo }}</td>
            <td>{{ formatNurseLevel(item.nurseLevel) }}</td>
            <td>{{ formatInpatientStatus(item.inpatientStatus) }}</td>
            <td>{{ formatDate(item.admissionDateTime) }}</td>
            <td>
              <button class="detail-btn" @click="showDetail(item)">详情</button>
            </td>
          </tr>
          <tr v-if="tableData.length === 0">
            <td colspan="12" class="empty-tip">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="total > 0">
      <span class="pagination-info">共 {{ total }} 条记录</span>
      <div class="pagination-controls">
        <button class="page-btn" :disabled="currentPage === 1" @click="changePage(1)">首页</button>
        <button class="page-btn" :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
        <span class="page-numbers">
          <button 
            v-for="page in displayPages" 
            :key="page" 
            class="page-num" 
            :class="{ active: page === currentPage }"
            @click="changePage(page)"
          >{{ page }}</button>
        </span>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">下一页</button>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="changePage(totalPages)">末页</button>
        <span class="page-size-selector">
          <select v-model="pageSize" @change="handlePageSizeChange">
            <option :value="10">10条/页</option>
            <option :value="20">20条/页</option>
            <option :value="50">50条/页</option>
            <option :value="100">100条/页</option>
          </select>
        </span>
        <span class="page-jump">
          跳至 <input type="number" v-model.number="jumpPage" min="1" :max="totalPages" @keyup.enter="handleJumpPage" /> 页
        </span>
      </div>
    </div>

    <!-- 详情弹窗 -->
    <div class="modal-overlay" v-if="detailVisible" @click.self="detailVisible = false">
      <div class="modal-content detail-modal">
        <div class="modal-header">
          <span>患者详情 - {{ currentPatient.name }}</span>
          <button class="close-btn" @click="detailVisible = false">×</button>
        </div>
        <div class="modal-body">
          <!-- 主页签 -->
          <div class="tab-bar">
            <div class="tab-item" :class="{ active: activeTab === 'basic' }" @click="activeTab = 'basic'">基本信息</div>
            <div class="tab-item" :class="{ active: activeTab === 'diagnose' }" @click="activeTab = 'diagnose'">诊断信息</div>
            <div class="tab-item" :class="{ active: activeTab === 'order' }" @click="activeTab = 'order'">医嘱信息</div>
            <div class="tab-item" :class="{ active: activeTab === 'fee' }" @click="activeTab = 'fee'">费用信息</div>
            <div class="tab-item" :class="{ active: activeTab === 'exam' }" @click="activeTab = 'exam'">检查检验</div>
          </div>

          <!-- 基本信息页面 -->
          <div class="tab-content" v-show="activeTab === 'basic'">
            <!-- 个人信息 -->
            <div class="info-group">
              <div class="group-title">个人信息</div>
              <div class="detail-grid">
                <div class="detail-item"><span class="label">患者姓名：</span><span class="value">{{ currentPatient.name }}</span></div>
                <div class="detail-item"><span class="label">性别：</span><span class="value">{{ currentPatient.sex }}</span></div>
                <div class="detail-item"><span class="label">年龄：</span><span class="value">{{ currentPatient.age }}</span></div>
                <div class="detail-item"><span class="label">医保类型：</span><span class="value">{{ currentPatient.medicalInsuranceType }}</span></div>
              </div>
            </div>

            <!-- 住院信息 -->
            <div class="info-group">
              <div class="group-title">住院信息</div>
              <div class="detail-grid">
                <div class="detail-item"><span class="label">住院号：</span><span class="value">{{ currentPatient.inpatientNo }}</span></div>
                <div class="detail-item"><span class="label">住院流水号：</span><span class="value">{{ currentPatient.inpatientSerialNo }}</span></div>
                <div class="detail-item"><span class="label">所属科室：</span><span class="value">{{ currentPatient.deptCode }}</span></div>
                <div class="detail-item"><span class="label">所属病区：</span><span class="value">{{ currentPatient.wardCode }}</span></div>
                <div class="detail-item"><span class="label">房间号：</span><span class="value">{{ currentPatient.roomNo }}</span></div>
                <div class="detail-item"><span class="label">床位号：</span><span class="value">{{ currentPatient.bedNo }}</span></div>
                <div class="detail-item"><span class="label">在院状态：</span><span class="value">{{ formatInpatientStatus(currentPatient.inpatientStatus) }}</span></div>
                <div class="detail-item"><span class="label">入院时间：</span><span class="value">{{ formatDate(currentPatient.admissionDateTime) }}</span></div>
                <div class="detail-item"><span class="label">入科时间：</span><span class="value">{{ formatDate(currentPatient.deptDateTime) }}</span></div>
                <div class="detail-item"><span class="label">出院时间：</span><span class="value">{{ formatDate(currentPatient.dischargedDateTime) }}</span></div>
              </div>
            </div>

            <!-- 医护信息 -->
            <div class="info-group">
              <div class="group-title">医护信息</div>
              <div class="detail-grid">
                <div class="detail-item"><span class="label">责任医生：</span><span class="value">{{ currentPatient.doctorCode }}</span></div>
                <div class="detail-item"><span class="label">责任护士：</span><span class="value">{{ currentPatient.nurseCode }}</span></div>
                <div class="detail-item"><span class="label">护理级别：</span><span class="value">{{ formatNurseLevel(currentPatient.nurseLevel) }}</span></div>
                <div class="detail-item"><span class="label">病情状况：</span><span class="value">{{ currentPatient.conditionStatus }}</span></div>
              </div>
            </div>

            <!-- 诊疗信息 -->
            <div class="info-group">
              <div class="group-title">诊疗信息</div>
              <div class="detail-grid">
                <div class="detail-item full-width"><span class="label">入院诊断：</span><span class="value">{{ currentPatient.diagnose }}</span></div>
                <div class="detail-item full-width"><span class="label">过敏信息：</span><span class="value">{{ currentPatient.allergen }}</span></div>
                <div class="detail-item"><span class="label">饮食状况：</span><span class="value">{{ currentPatient.dietType }}</span></div>
                <div class="detail-item full-width"><span class="label">安全防范：</span><span class="value">{{ currentPatient.notice }}</span></div>
              </div>
            </div>
          </div>

          <!-- 诊断信息页面 -->
          <div class="tab-content" v-show="activeTab === 'diagnose'">
            <table class="info-table">
              <thead>
                <tr>
                  <th>诊断时间</th>
                  <th>诊断类型</th>
                  <th>诊断描述</th>
                  <th>诊断状态</th>
                  <th>诊断医生</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in diagnoseList" :key="index">
                  <td>{{ formatDateTime(item.diagnoseTime) }}</td>
                  <td>{{ item.diagnoseType }}</td>
                  <td>{{ item.diagnoseDesc }}</td>
                  <td>{{ formatDiagnoseStatus(item.diagnoseStatus) }}</td>
                  <td>{{ item.diagnoseDoctor }}</td>
                  <td>{{ item.remark }}</td>
                </tr>
                <tr v-if="diagnoseList.length === 0"><td colspan="6" class="empty-tip">暂无数据</td></tr>
              </tbody>
            </table>
          </div>

          <!-- 医嘱信息页面 -->
          <div class="tab-content" v-show="activeTab === 'order'">
            <table class="info-table">
              <thead>
                <tr>
                  <th>医嘱类型</th>
                  <th>医嘱名称</th>
                  <th>药物</th>
                  <th>用量</th>
                  <th>单位</th>
                  <th>用药方式</th>
                  <th>用药频率</th>
                  <th>执行状态</th>
                  <th>开始时间</th>
                  <th>结束时间</th>
                  <th>开嘱医生</th>
                  <th>开嘱时间</th>
                  <th>停嘱医生</th>
                  <th>停嘱时间</th>
                  <th>备注</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in orderList" :key="index">
                  <td>{{ formatOrderType(item.orderType) }}</td>
                  <td>{{ item.orderName }}</td>
                  <td>{{ item.medicine }}</td>
                  <td>{{ item.dosage }}</td>
                  <td>{{ item.dosageUnit }}</td>
                  <td>{{ item.medicationWay }}</td>
                  <td>{{ item.medicationFreq }}</td>
                  <td>{{ formatExecStatus(item.execStatus) }}</td>
                  <td>{{ formatDateTime(item.startTime) }}</td>
                  <td>{{ formatDateTime(item.endTime) }}</td>
                  <td>{{ item.orderDoctor }}</td>
                  <td>{{ formatDateTime(item.orderTime) }}</td>
                  <td>{{ item.stopDoctor }}</td>
                  <td>{{ formatDateTime(item.stopTime) }}</td>
                  <td>{{ item.remark }}</td>
                </tr>
                <tr v-if="orderList.length === 0"><td colspan="15" class="empty-tip">暂无数据</td></tr>
              </tbody>
            </table>
          </div>

          <!-- 费用信息页面 -->
          <div class="tab-content" v-show="activeTab === 'fee'">
            <table class="info-table">
              <thead>
                <tr>
                  <th>费用产生日期</th>
                  <th>项目名称</th>
                  <th>金额</th>
                  <th>数量</th>
                  <th>单位</th>
                  <th>小计</th>
                  <th>备注</th>
                  <th>是否缴费</th>
                  <th>缴费时间</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in feeList" :key="index">
                  <td>{{ formatDateTime(item.chargeDate) }}</td>
                  <td>{{ item.itemName }}</td>
                  <td>{{ item.amount }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>{{ item.unit }}</td>
                  <td>{{ item.subtotal }}</td>
                  <td>{{ item.remark }}</td>
                  <td>{{ item.isPaid === 1 ? '是' : '否' }}</td>
                  <td>{{ formatDateTime(item.payTime) }}</td>
                </tr>
                <tr v-if="feeList.length === 0"><td colspan="9" class="empty-tip">暂无数据</td></tr>
              </tbody>
            </table>
          </div>

          <!-- 检查检验页面 -->
          <div class="tab-content" v-show="activeTab === 'exam'">
            <!-- 子页签 -->
            <div class="sub-tab-bar">
              <div class="sub-tab-item" :class="{ active: examSubTab === 'check' }" @click="examSubTab = 'check'">检查报告</div>
              <div class="sub-tab-item" :class="{ active: examSubTab === 'lab' }" @click="examSubTab = 'lab'">检验报告</div>
            </div>

            <!-- 检查报告 -->
            <div v-show="examSubTab === 'check'">
              <table class="info-table">
                <thead>
                  <tr>
                    <th>检查名称</th>
                    <th>检查部位</th>
                    <th>检查方式</th>
                    <th>光镜观察</th>
                    <th>影像所见</th>
                    <th>临床诊断</th>
                    <th>影像诊断</th>
                    <th>检查医生</th>
                    <th>检查时间</th>
                    <th>审核者</th>
                    <th>报告时间</th>
                    <th>备注</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in checkList" :key="index">
                    <td>{{ item.examName }}</td>
                    <td>{{ item.examPart }}</td>
                    <td>{{ item.examMethod }}</td>
                    <td>{{ item.microscopy }}</td>
                    <td>{{ item.imagingFindings }}</td>
                    <td>{{ item.clinicalDiagnosis }}</td>
                    <td>{{ item.imagingDiagnosis }}</td>
                    <td>{{ item.examDoctor }}</td>
                    <td>{{ formatDateTime(item.examTime) }}</td>
                    <td>{{ item.examiner }}</td>
                    <td>{{ formatDateTime(item.reportTime) }}</td>
                    <td>{{ item.remark }}</td>
                  </tr>
                  <tr v-if="checkList.length === 0"><td colspan="12" class="empty-tip">暂无数据</td></tr>
                </tbody>
              </table>
            </div>

            <!-- 检验报告 -->
            <div v-show="examSubTab === 'lab'">
              <table class="info-table">
                <thead>
                  <tr>
                    <th>检验名称</th>
                    <th>样品名称</th>
                    <th>样品编号</th>
                    <th>检验医生</th>
                    <th>检验时间</th>
                    <th>审核者</th>
                    <th>报告时间</th>
                    <th>备注</th>
                    <th>操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(item, index) in labList" :key="index">
                    <td>{{ item.testName }}</td>
                    <td>{{ item.sampleName }}</td>
                    <td>{{ item.sampleCode }}</td>
                    <td>{{ item.testDoctor }}</td>
                    <td>{{ formatDateTime(item.testTime) }}</td>
                    <td>{{ item.tester }}</td>
                    <td>{{ formatDateTime(item.reportTime) }}</td>
                    <td>{{ item.remark }}</td>
                    <td><button class="detail-btn" @click="showLabDetail(item)">详情</button></td>
                  </tr>
                  <tr v-if="labList.length === 0"><td colspan="9" class="empty-tip">暂无数据</td></tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 检验报告详情弹窗 -->
    <div class="modal-overlay" v-if="labDetailVisible" @click.self="labDetailVisible = false">
      <div class="modal-content lab-detail-modal">
        <div class="modal-header">
          <span>检验报告详情 - {{ currentLab.testName }}</span>
          <button class="close-btn" @click="labDetailVisible = false">×</button>
        </div>
        <div class="modal-body">
          <table class="info-table">
            <thead>
              <tr>
                <th>项目名称</th>
                <th>英文缩写</th>
                <th>结果值</th>
                <th>结果提示</th>
                <th>单位</th>
                <th>参考范围</th>
                <th>备注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in labDetailList" :key="index">
                <td>{{ item.itemName }}</td>
                <td>{{ item.itemAbbr }}</td>
                <td>{{ item.resultValue }}</td>
                <td>{{ item.resultHint }}</td>
                <td>{{ item.resultUnit }}</td>
                <td>{{ item.refRange }}</td>
                <td>{{ item.itemRemark }}</td>
              </tr>
              <tr v-if="labDetailList.length === 0"><td colspan="7" class="empty-tip">暂无数据</td></tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import request from '@/utils/request'

// 查询条件
const searchForm = reactive({
  name: '',
  deptCode: '',
  wardCode: '',
  roomNo: '',
  bedNo: '',
  inpatientNo: '',
  nurseLevel: '',
  inpatientStatus: '',
  admissionDateStart: '',
  admissionDateEnd: ''
})

// 下拉列表数据
const deptList = ref([])
const wardList = ref([])
const roomList = ref([])
const bedList = ref([])
const inpatientStatusList = ref([])
const nurseLevelList = ref([])

// 表格数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const jumpPage = ref(1)

// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value) || 1)

// 计算显示的页码
const displayPages = computed(() => {
  const pages = []
  const maxShow = 5
  let start = Math.max(1, currentPage.value - Math.floor(maxShow / 2))
  let end = Math.min(totalPages.value, start + maxShow - 1)
  if (end - start + 1 < maxShow) {
    start = Math.max(1, end - maxShow + 1)
  }
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
})

// 详情弹窗
const detailVisible = ref(false)
const currentPatient = ref({})
const activeTab = ref('basic')
const examSubTab = ref('check')

// 各页签数据（暂时空数据，待后端对接）
const diagnoseList = ref([])
const orderList = ref([])
const feeList = ref([])
const checkList = ref([])
const labList = ref([])

// 检验报告详情弹窗
const labDetailVisible = ref(false)
const currentLab = ref({})
const labDetailList = ref([])

onMounted(async () => {
  loading.value = true
  try {
    // 使用合并接口，一次请求获取所有数据
    const res = await request.get('/api/patient/init-data', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    if (res.code === 200 && res.data) {
      deptList.value = res.data.deptList || []
      wardList.value = res.data.wardList || []
      roomList.value = res.data.roomList || []
      bedList.value = res.data.bedList || []
      inpatientStatusList.value = res.data.inpatientStatusList || []
      nurseLevelList.value = res.data.nurseLevelList || []
      tableData.value = res.data.patientList?.records || res.data.patientList || []
      total.value = res.data.patientList?.total || tableData.value.length
    }
  } catch (error) {
    console.error('加载数据失败：', error)
  } finally {
    loading.value = false
  }
})

// 加载所属科室列表
const loadDeptList = async () => {
  try {
    const res = await request.get('/api/patient/dept-list')
    if (res.code === 200) {
      deptList.value = res.data || []
    }
  } catch (error) {
    console.error('加载科室列表失败：', error)
  }
}

// 加载病区列表
const loadWardList = async () => {
  try {
    const params = {}
    if (searchForm.deptCode) params.deptCode = searchForm.deptCode
    const res = await request.get('/api/patient/ward-list', { params })
    if (res.code === 200) {
      wardList.value = res.data || []
    }
  } catch (error) {
    console.error('加载病区列表失败：', error)
  }
}

// 加载房间号列表
const loadRoomList = async () => {
  try {
    const params = {}
    if (searchForm.wardCode) params.wardCode = searchForm.wardCode
    const res = await request.get('/api/patient/room-list', { params })
    if (res.code === 200) {
      roomList.value = res.data || []
    }
  } catch (error) {
    console.error('加载房间号列表失败：', error)
  }
}

// 加载床位号列表
const loadBedList = async () => {
  try {
    const params = {}
    if (searchForm.roomNo) params.roomNo = searchForm.roomNo
    const res = await request.get('/api/patient/bed-list', { params })
    if (res.code === 200) {
      bedList.value = res.data || []
    }
  } catch (error) {
    console.error('加载床位号列表失败：', error)
  }
}

// 加载在院状态列表
const loadInpatientStatusList = async () => {
  try {
    const res = await request.get('/api/patient/inpatient-status-list')
    if (res.code === 200) {
      inpatientStatusList.value = res.data || []
    }
  } catch (error) {
    console.error('加载在院状态列表失败：', error)
  }
}

// 加载护理级别列表
const loadNurseLevelList = async () => {
  try {
    const res = await request.get('/api/patient/nurse-level-list')
    if (res.code === 200) {
      nurseLevelList.value = res.data || []
    }
  } catch (error) {
    console.error('加载护理级别列表失败：', error)
  }
}

// 科室变化时
const onDeptChange = () => {
  searchForm.wardCode = ''
  searchForm.roomNo = ''
  searchForm.bedNo = ''
  loadWardList()
  roomList.value = []
  bedList.value = []
}

// 病区变化时
const onWardChange = () => {
  searchForm.roomNo = ''
  searchForm.bedNo = ''
  loadRoomList()
  bedList.value = []
}

// 房间号变化时
const onRoomChange = () => {
  searchForm.bedNo = ''
  loadBedList()
}

// 加载数据
const loadData = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    if (searchForm.name) params.name = searchForm.name
    if (searchForm.deptCode) params.deptCode = searchForm.deptCode
    if (searchForm.wardCode) params.wardCode = searchForm.wardCode
    if (searchForm.roomNo) params.roomNo = searchForm.roomNo
    if (searchForm.bedNo) params.bedNo = searchForm.bedNo
    if (searchForm.inpatientNo) params.inpatientNo = searchForm.inpatientNo
    if (searchForm.nurseLevel) params.nurseLevel = searchForm.nurseLevel
    if (searchForm.inpatientStatus) params.inpatientStatus = searchForm.inpatientStatus
    if (searchForm.admissionDateStart) params.admissionDateStart = searchForm.admissionDateStart
    if (searchForm.admissionDateEnd) params.admissionDateEnd = searchForm.admissionDateEnd
    
    const res = await request.get('/api/patient/list', { params })
    if (res.code === 200) {
      tableData.value = res.data?.records || res.data || []
      total.value = res.data?.total || tableData.value.length
    }
  } catch (error) {
    console.error('加载数据失败：', error)
  }
}

// 切换页码
const changePage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpPage.value = page
    loading.value = true
    loadData().finally(() => { loading.value = false })
  }
}

// 修改每页条数
const handlePageSizeChange = () => {
  currentPage.value = 1
  loading.value = true
  loadData().finally(() => { loading.value = false })
}

// 跳转到指定页
const handleJumpPage = () => {
  const page = Math.min(Math.max(1, jumpPage.value), totalPages.value)
  changePage(page)
}

// 查询
const handleSearch = async () => {
  currentPage.value = 1
  loading.value = true
  try {
    await loadData()
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = async () => {
  searchForm.name = ''
  searchForm.deptCode = ''
  searchForm.wardCode = ''
  searchForm.roomNo = ''
  searchForm.bedNo = ''
  searchForm.inpatientNo = ''
  searchForm.nurseLevel = ''
  searchForm.inpatientStatus = ''
  searchForm.admissionDateStart = ''
  searchForm.admissionDateEnd = ''
  currentPage.value = 1
  loading.value = true
  try {
    await Promise.all([loadWardList(), loadRoomList(), loadBedList(), loadData()])
  } finally {
    loading.value = false
  }
}

// 查看详情
const showDetail = async (item) => {
  try {
    const res = await request.get(`/api/patient/detail/${item.id}`)
    if (res.code === 200) {
      currentPatient.value = res.data
      activeTab.value = 'basic'
      examSubTab.value = 'check'
      // 清空各页签数据
      diagnoseList.value = []
      orderList.value = []
      feeList.value = []
      checkList.value = []
      labList.value = []
      detailVisible.value = true
      // 加载诊断信息（使用患者ID查询）
      loadDiagnoseList(res.data.id)
      // 加载医嘱信息（使用患者ID查询）
      loadOrderList(res.data.id)
      // 加载费用信息（使用患者ID查询）
      loadChargeList(res.data.id)
      // 加载检查报告（使用患者ID查询）
      loadExamList(res.data.id)
      // 加载检验报告（使用患者ID查询）
      loadTestList(res.data.id)
    }
  } catch (error) {
    console.error('获取详情失败：', error)
  }
}

// 加载诊断信息列表
const loadDiagnoseList = async (patientId) => {
  try {
    const res = await request.get(`/api/patient/diagnosis/${patientId}`)
    if (res.code === 200) {
      diagnoseList.value = res.data || []
    }
  } catch (error) {
    console.error('加载诊断信息失败：', error)
  }
}

// 加载医嘱信息列表
const loadOrderList = async (patientId) => {
  try {
    const res = await request.get(`/api/patient/orders/${patientId}`)
    if (res.code === 200) {
      orderList.value = res.data || []
    }
  } catch (error) {
    console.error('加载医嘱信息失败：', error)
  }
}

// 加载费用信息列表
const loadChargeList = async (patientId) => {
  try {
    const res = await request.get(`/api/patient/charges/${patientId}`)
    if (res.code === 200) {
      feeList.value = res.data || []
    }
  } catch (error) {
    console.error('加载费用信息失败：', error)
  }
}

// 加载检查报告列表
const loadExamList = async (patientId) => {
  try {
    const res = await request.get(`/api/patient/exams/${patientId}`)
    if (res.code === 200) {
      checkList.value = res.data || []
    }
  } catch (error) {
    console.error('加载检查报告失败：', error)
  }
}

// 加载检验报告列表
const loadTestList = async (patientId) => {
  try {
    const res = await request.get(`/api/patient/tests/${patientId}`)
    if (res.code === 200) {
      labList.value = res.data || []
    }
  } catch (error) {
    console.error('加载检验报告失败：', error)
  }
}

// 查看检验报告详情
const showLabDetail = async (item) => {
  currentLab.value = item
  labDetailList.value = []
  labDetailVisible.value = true
  // 加载检验项目明细
  try {
    const res = await request.get(`/api/patient/test-items/${item.id}`)
    if (res.code === 200) {
      labDetailList.value = res.data || []
    }
  } catch (error) {
    console.error('加载检验项目明细失败：', error)
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  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')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  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 formatDiagnoseStatus = (status) => {
  const map = {
    1: '确诊',
    2: '疑似',
    3: '排除',
    4: '待查'
  }
  return map[status] || status || ''
}

// 格式化护理级别
const formatNurseLevel = (level) => {
  const map = {
    '0': '特级',
    '1': '一级',
    '2': '二级',
    '3': '三级',
    '-1': '未设置'
  }
  return map[String(level)] || level || ''
}

// 格式化在院状态
const formatInpatientStatus = (status) => {
  const map = {
    '1': '入院',
    '2': '已入科',
    '3': '待入科',
    '4': '已出院',
    '-1': '未设置'
  }
  return map[String(status)] || status || ''
}

// 格式化医嘱类型
const formatOrderType = (type) => {
  const map = {
    1: '长期医嘱',
    2: '临时医嘱',
    3: '出院医嘱'
  }
  return map[type] || type || ''
}

// 格式化执行状态
const formatExecStatus = (status) => {
  const map = {
    1: '未执行',
    2: '执行中',
    3: '已执行',
    4: '已停止'
  }
  return map[status] || status || ''
}
</script>

<style scoped>
.page-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}
.page-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  margin-bottom: 20px;
  font-size: 14px;
}
.breadcrumb-label { color: #666; }
.breadcrumb-path { color: #666; }
.breadcrumb-separator { margin: 0 5px; color: #666; }
.breadcrumb-current { color: #409eff; }

/* 查询栏 */
.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 10px;
  padding: 12px 15px;
  background: #f5f7fa;
  border-radius: 4px;
}
.search-item {
  display: flex;
  align-items: center;
}
.search-item label {
  margin-right: 6px;
  color: #666;
  font-size: 14px;
  white-space: nowrap;
}
.search-item input,
.search-item select {
  padding: 6px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
}
.search-item input { width: 100px; }
.search-item select { width: 100px; }
.search-item input[type="date"] { width: 120px; }
.date-sep {
  margin: 0 3px;
  color: #666;
}
.search-btn {
  padding: 6px 16px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  font-size: 13px;
}
.search-btn:hover { background: #66b1ff; }
.reset-btn {
  padding: 6px 16px;
  background: #fff;
  color: #666;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
  font-size: 13px;
}
.reset-btn:hover { border-color: #409eff; color: #409eff; }

/* 数据表格 */
.table-container {
  overflow-x: auto;
}
.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}
.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
  white-space: nowrap;
}
.data-table th {
  background: #f5f7fa;
  font-weight: 500;
  color: #333;
}
.data-table tbody tr:hover {
  background: #f5f7fa;
}
.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 0;
}
.detail-btn {
  padding: 4px 12px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}
.detail-btn:hover { background: #66b1ff; }

/* 加载状态 */
.loading-mask {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
}
.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal-content {
  background: #fff;
  border-radius: 8px;
  max-width: 90%;
  max-height: 90%;
  overflow: hidden;
}
.detail-modal {
  width: 1100px;
  height: 600px;
}
.detail-modal .modal-body {
  height: calc(600px - 60px);
  overflow-y: auto;
}
/* 检验报告详情弹窗 */
.lab-detail-modal {
  width: 850px;
  height: 450px;
}
.lab-detail-modal .modal-body {
  height: calc(450px - 60px);
  overflow-y: auto;
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  font-size: 16px;
  font-weight: 500;
}
.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}
.close-btn:hover { color: #333; }
.modal-body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 详情区域 */
.detail-section {
  margin-bottom: 20px;
}
.detail-section h4 {
  margin: 0 0 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #333;
}

/* 信息分组 */
.info-group {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
}
.group-title {
  background: #f5f7fa;
  padding: 10px 15px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #e4e7ed;
}
.info-group .detail-grid {
  padding: 15px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}
.detail-item {
  display: flex;
  font-size: 14px;
}
.detail-item .label {
  color: #666;
  white-space: nowrap;
}
.detail-item .value {
  color: #333;
}
.detail-item.full-width {
  grid-column: span 4;
}

/* 页签样式 */
.tab-bar {
  display: flex;
  border-bottom: 2px solid #e4e7ed;
  margin-bottom: 15px;
}
.tab-item {
  padding: 10px 20px;
  cursor: pointer;
  color: #666;
  font-size: 14px;
  border-bottom: 2px solid transparent;
  margin-bottom: -2px;
  transition: all 0.3s;
}
.tab-item:hover {
  color: #409eff;
}
.tab-item.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

/* 子页签样式 */
.sub-tab-bar {
  display: flex;
  margin-bottom: 15px;
  gap: 10px;
}
.sub-tab-item {
  padding: 6px 16px;
  cursor: pointer;
  color: #666;
  font-size: 13px;
  background: #f5f7fa;
  border-radius: 4px;
  transition: all 0.3s;
}
.sub-tab-item:hover {
  background: #e4e7ed;
}
.sub-tab-item.active {
  background: #409eff;
  color: #fff;
}

/* 页签内容 */
.tab-content {
  min-height: 400px;
  max-height: 450px;
  overflow-y: auto;
}

/* 信息表格 */
.info-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 13px;
}
.info-table th,
.info-table td {
  padding: 10px 8px;
  text-align: left;
  border: 1px solid #ebeef5;
  white-space: nowrap;
}
.info-table th {
  background: #f5f7fa;
  font-weight: 500;
  color: #333;
}
.info-table tbody tr:hover {
  background: #f5f7fa;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px 0;
  border-top: 1px solid #eee;
}
.pagination-info {
  color: #666;
  font-size: 14px;
}
.pagination-controls {
  display: flex;
  align-items: center;
  gap: 5px;
}
.page-btn {
  padding: 6px 12px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
}
.page-btn:hover:not(:disabled) {
  color: #409eff;
  border-color: #c6e2ff;
}
.page-btn:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}
.page-numbers {
  display: flex;
  gap: 5px;
}
.page-num {
  min-width: 32px;
  height: 28px;
  padding: 0 6px;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  color: #606266;
}
.page-num:hover {
  color: #409eff;
  border-color: #c6e2ff;
}
.page-num.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}
.page-size-selector select {
  padding: 5px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
  margin-left: 10px;
}
.page-jump {
  font-size: 13px;
  color: #606266;
  margin-left: 10px;
}
.page-jump input {
  width: 50px;
  padding: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
  margin: 0 5px;
}
</style>
