<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" class="query-form">
      <el-form-item label="手术编号" prop="surgeryNo">
        <el-input
          v-model="queryParams.surgeryNo"
          placeholder="请输入手术编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="手术名称" prop="surgeryName">
        <el-input
          v-model="queryParams.surgeryName"
          placeholder="请输入手术名称"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="手术状态" prop="statusEnum">
        <el-select v-model="queryParams.statusEnum" placeholder="请选择手术状态" clearable style="width: 200px">
          <el-option
            v-for="item in surgery_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手术类型" prop="surgeryTypeEnum">
        <el-select v-model="queryParams.surgeryTypeEnum" placeholder="请选择手术类型" clearable style="width: 200px">
          <el-option
            v-for="item in surgery_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="计划时间" prop="plannedTime">
        <el-date-picker
          v-model="queryParams.plannedTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item class="search-buttons">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"> 新增手术 </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="" plain icon="Refresh" @click="getPageList">刷新</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="surgeryList" row-key="id" :row-class-name="getRowClassName" highlight-current-row @current-change="handleCurrentChange">
      <!-- 申请日期：datetime - 2025-09-19 14:15:00 - 不可操作 -->
      <el-table-column label="申请日期" align="center" prop="createTime" width="160">
        <template #default="scope">
          {{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>

      <!-- 手术单号：string - OP2025092003 - 可查看详情 -->
      <el-table-column label="手术单号" align="center" prop="surgeryNo" width="180" show-overflow-tooltip>
        <template #default="scope">
          <el-link type="primary" :underline="false" @click="handleView(scope.row)">
            {{ scope.row.surgeryNo }}
          </el-link>
        </template>
      </el-table-column>

      <!-- 患者姓名：string - 张小明 - 不可操作 -->
      <el-table-column label="患者姓名" align="center" prop="patientName" width="90" />

      <!-- 申请医生：string - 张医生 - 不可操作 -->
      <el-table-column label="申请医生" align="center" prop="applyDoctorName" width="90" />

      <!-- 申请科室：string - 普外科 - 不可操作 -->
      <el-table-column label="申请科室" align="center" prop="applyDeptName" width="100" show-overflow-tooltip />

      <!-- 手术名称：string - 腹腔镜胆囊切除术 - 不可操作 -->
      <el-table-column label="手术名称" align="center" prop="surgeryName" min-width="140" show-overflow-tooltip />

      <!-- 手术类型：string - 择期手术 - 不可操作 -->
      <el-table-column label="手术类型" align="center" prop="surgeryTypeEnum_dictText" width="90" />

      <!-- 手术等级：string - 三级手术 - 不可操作 -->
      <el-table-column label="手术等级" align="center" prop="surgeryLevel_dictText" width="90" />

      <!-- 急诊标志：bool - 是/否 - 不可操作 -->
      <el-table-column label="急诊" align="center" prop="emergencyFlag" width="70">
        <template #default="scope">
          <el-tag v-if="scope.row.emergencyFlag === 1" type="danger" size="small">是</el-tag>
          <el-tag v-else type="info" size="small">否</el-tag>
        </template>
      </el-table-column>

      <!-- 植入高值耗材标志：bool - 是/否 - 不可操作 -->
      <el-table-column label="植入耗材" align="center" prop="implantFlag" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.implantFlag === 1" type="warning" size="small">是</el-tag>
          <el-tag v-else type="info" size="small">否</el-tag>
        </template>
      </el-table-column>

      <!-- 计划时间：datetime - 2025-09-20 08:00:00 - 不可操作 -->
      <el-table-column label="计划时间" align="center" prop="plannedTime" width="160">
        <template #default="scope">
          {{ parseTime(scope.row.plannedTime, '{y}-{m}-{d} {h}:{i}') }}
        </template>
      </el-table-column>

      <!-- 主刀医生：string - 王医生 - 不可操作 -->
      <el-table-column label="主刀医生" align="center" prop="mainSurgeonName" width="90" />

      <!-- 麻醉医生：string - 李医生 - 不可操作 -->
      <el-table-column label="麻醉医生" align="center" prop="anesthetistName" width="90" />

      <!-- 麻醉方式：string - 全身麻醉 - 不可操作 -->
      <el-table-column label="麻醉方式" align="center" prop="anesthesiaTypeEnum_dictText" width="90" />

      <!-- 手术部位：string - 腹部 - 不可操作 -->
      <el-table-column label="手术部位" align="center" prop="bodySite" width="90" show-overflow-tooltip />

      <!-- 手术室：string - 手术室1 - 不可操作 -->
      <el-table-column label="手术室" align="center" prop="operatingRoomName" width="100" show-overflow-tooltip />

      <!-- 手术室科室：string - 外科 - 不可操作 -->
      <el-table-column label="手术室科室" align="center" prop="operatingRoomOrgName" width="100" show-overflow-tooltip />

      <!-- 执行科室：string - 普外科 - 不可操作 -->
      <el-table-column label="执行科室" align="center" prop="orgName" width="100" show-overflow-tooltip />

      <!-- 状态：badge - 已安排 - 不可操作 -->
      <el-table-column label="状态" align="center" prop="statusEnum_dictText" width="90">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.statusEnum)">
            {{ scope.row.statusEnum_dictText }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作：action - 查看/编辑/删除/状态操作 - 可操作 -->
      <el-table-column label="操作" align="center" width="260" fixed="right">
        <template #default="scope">
          <!-- 查看：显示手术申请详情（只读模式） -->
          <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>

          <!-- 编辑：修改手术申请信息（只有状态为新开的能修改） -->
          <el-button link type="primary" @click="handleEdit(scope.row)" v-if="Number(scope.row.statusEnum) === 0">编辑</el-button>

          <!-- 删除：取消手术申请（新开状态直接删除，已排期状态变为已取消） -->
          <el-button link type="danger" @click="handleDelete(scope.row)" v-if="Number(scope.row.statusEnum) === 0 || Number(scope.row.statusEnum) === 1">取消</el-button>

          <!-- 排期：从新开变为已排期 -->
          <el-button link type="success" @click="handleSchedule(scope.row)" v-if="Number(scope.row.statusEnum) === 0">排期</el-button>

          <!-- 开始：从已排期变为手术中 -->
          <el-button link type="warning" @click="handleStart(scope.row)" v-if="Number(scope.row.statusEnum) === 1">开始</el-button>

          <!-- 完成：从手术中变为已完成 -->
          <el-button link type="primary" @click="handleComplete(scope.row)" v-if="Number(scope.row.statusEnum) === 2">完成</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getPageList"
      />
    </div>

    <!-- 新增或修改手术对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" @close="cancel" append-to-body :close-on-click-modal="false">
      <!-- 编辑模式下显示当前状态 -->
      <el-alert v-if="isEditMode && form.statusEnum !== undefined" :title="'当前状态: ' + getStatusText(form.statusEnum)" :type="getStatusType(form.statusEnum)" :closable="false" style="margin-bottom: 20px;" />
      <!-- 查看模式下显示提示 -->
      <el-alert v-if="isViewMode" title="当前为查看模式，所有字段均为只读状态" type="info" :closable="false" style="margin-bottom: 20px;" />

      <el-form ref="surgeryRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="id" prop="id" v-show="false">
          <el-input v-model="form.id" />s
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="患者" prop="patientId">
              <el-select v-model="form.patientId" placeholder="请选择患者" filterable style="width: 100%" :disabled="isEditMode || isViewMode" @focus="loadPatientList" @change="handlePatientChange">
                <el-option
                  v-for="item in patientList"
                  :key="item.id"
                  :label="item.name + ' (' + (item.idCard || '无身份证号') + ')'"
                  :value="item.id"
                />
              </el-select>
              <div v-if="isEditMode" class="form-tip" style="color: #909399; font-size: 12px; margin-top: 4px;">* 编辑模式下患者信息不可更改</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="就诊流水号" prop="encounterId">
              <el-select
                v-model="form.encounterId"
                placeholder="请选择就诊流水号"
                filterable
                clearable
                style="width: 100%"
                :loading="encounterLoading"
                :disabled="!form.patientId || isEditMode || isViewMode"
              >
                <el-option
                  v-for="item in encounterList"
                  :key="item.id"
                  :label="item.busNo + ' (' + getEncounterStatusText(item.statusEnum) + ')'"
                  :value="item.id"
                />
              </el-select>
              <!-- 编辑模式下，如果原有的encounterId不在列表中，显示原有值 -->
              <div v-if="isEditMode && form.encounterId && !encounterList.some(item => item.id === form.encounterId)" class="form-tip" style="color: #f56c6c; font-size: 12px; margin-top: 4px;">
                原就诊记录: {{ form.encounterNo || '无' }}
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请医生" prop="applyDoctorName">
              <el-input v-model="form.applyDoctorName" :disabled="true" placeholder="系统自动获取当前登录医生" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请科室" prop="applyDeptName">
              <el-input v-model="form.applyDeptName" :disabled="true" placeholder="系统自动获取当前登录医生所属科室" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手术名称" prop="surgeryName">
              <el-input v-model="form.surgeryName" placeholder="请输入手术名称" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术编码" prop="surgeryCode">
              <el-input v-model="form.surgeryCode" placeholder="请输入手术编码" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手术类型" prop="surgeryTypeEnum">
              <el-select v-model="form.surgeryTypeEnum" placeholder="请选择手术类型" style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in surgery_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术等级" prop="surgeryLevel">
              <el-select v-model="form.surgeryLevel" placeholder="请选择手术等级" style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in surgery_level"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划手术时间" prop="plannedTime">
              <el-date-picker
                v-model="form.plannedTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DDTHH:mm:ss"
                style="width: 100%"
                :disabled="isViewMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手术部位" prop="bodySite">
              <el-select v-model="form.bodySite" placeholder="请选择手术部位" style="width: 100%" :disabled="isViewMode" clearable>
                <el-option
                  v-for="item in surgical_site"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">手术团队</el-divider>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主刀医生" prop="mainSurgeonId">
              <el-select v-model="form.mainSurgeonId" placeholder="请选择主刀医生" filterable style="width: 100%" :disabled="isViewMode" @change="handleMainSurgeonChange">
                <el-option
                  v-for="item in doctorList"
                  :key="item.practitionerId"
                  :label="item.nickName"
                  :value="item.practitionerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="麻醉医生" prop="anesthetistId">
              <el-select v-model="form.anesthetistId" placeholder="请选择麻醉医生" filterable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in doctorList"
                  :key="item.practitionerId"
                  :label="item.nickName"
                  :value="item.practitionerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="助手1" prop="assistant1Id">
              <el-select v-model="form.assistant1Id" placeholder="请选择助手1" filterable clearable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in doctorList"
                  :key="item.practitionerId"
                  :label="item.nickName"
                  :value="item.practitionerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="助手2" prop="assistant2Id">
              <el-select v-model="form.assistant2Id" placeholder="请选择助手2" filterable clearable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in doctorList"
                  :key="item.practitionerId"
                  :label="item.nickName"
                  :value="item.practitionerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="巡回护士" prop="scrubNurseId">
              <el-select v-model="form.scrubNurseId" placeholder="请选择巡回护士" filterable clearable style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in nurseList"
                  :key="item.practitionerId"
                  :label="item.nickName"
                  :value="item.practitionerId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="麻醉方式" prop="anesthesiaTypeEnum">
              <el-select v-model="form.anesthesiaTypeEnum" placeholder="请选择麻醉方式" style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in anesthesia_type"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手术室" prop="operatingRoomId">
              <el-select
                v-model="form.operatingRoomId"
                filterable
                clearable
                placeholder="请选择手术室"
                :loading="operatingRoomLoading"
                style="width: 100%"
                :disabled="isViewMode"
                @change="handleOperatingRoomChange"
              >
                <el-option
                  v-for="item in operatingRoomList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行科室" prop="orgId">
              <el-tree-select
                v-model="form.orgId"
                :data="orgList"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                placeholder="请选择执行科室"
                check-strictly
                style="width: 100%"
                :disabled="isViewMode"
                @change="handleOrgChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">诊断信息</el-divider>

        <el-form-item label="术前诊断" prop="preoperativeDiagnosis">
          <el-input v-model="form.preoperativeDiagnosis" type="textarea" placeholder="请输入术前诊断" :rows="3" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="术后诊断" prop="postoperativeDiagnosis">
          <el-input v-model="form.postoperativeDiagnosis" type="textarea" placeholder="请输入术后诊断" :rows="3" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="手术经过描述" prop="surgeryDescription">
          <el-input v-model="form.surgeryDescription" type="textarea" placeholder="请输入手术经过描述" :rows="5" :disabled="isViewMode" />
        </el-form-item>

        <el-form-item label="术后医嘱" prop="postoperativeAdvice">
          <el-input v-model="form.postoperativeAdvice" type="textarea" placeholder="请输入术后医嘱" :rows="3" :disabled="isViewMode" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="手术费用" prop="surgeryFee">
              <el-input-number v-model="form.surgeryFee" :precision="2" :min="0" :max="9999999.99" :controls="false" style="width: 100%" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="麻醉费用" prop="anesthesiaFee">
              <el-input-number v-model="form.anesthesiaFee" :precision="2" :min="0" :max="9999999.99" :controls="false" style="width: 100%" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总费用" prop="totalFee">
              <el-input-number v-model="form.totalFee" :precision="2" :min="0" :max="9999999.99" :controls="false" style="width: 100%" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="切口等级" prop="incisionLevel">
              <el-select v-model="form.incisionLevel" placeholder="请选择切口等级" style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in incision_level"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="愈合等级" prop="healingLevel">
              <el-select v-model="form.healingLevel" placeholder="请选择愈合等级" style="width: 100%" :disabled="isViewMode">
                <el-option
                  v-for="item in healingLevelOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="并发症描述" prop="complications">
          <el-input v-model="form.complications" type="textarea" placeholder="请输入并发症描述" :rows="3" :disabled="isViewMode" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="急诊标志" prop="emergencyFlag">
              <el-radio-group v-model="form.emergencyFlag" :disabled="isViewMode">
                <el-radio :value="0">否</el-radio>
                <el-radio :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="植入高值耗材标志" prop="implantFlag">
              <el-radio-group v-model="form.implantFlag" :disabled="isViewMode">
                <el-radio :value="0">否</el-radio>
                <el-radio :value="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手术室确认人" prop="operatingRoomConfirmUser">
              <el-input v-model="form.operatingRoomConfirmUser" placeholder="手术室确认人" :disabled="isViewMode" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="手术室确认时间" prop="operatingRoomConfirmTime">
          <el-date-picker
            v-model="form.operatingRoomConfirmTime"
            type="datetime"
            placeholder="选择手术室确认时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            :disabled="isViewMode"
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" :rows="2" :disabled="isViewMode" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">关 闭</el-button>
          <el-button type="primary" @click="submitForm" v-if="!isViewMode">确 定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="SurgeryManage">
import { getSurgeryPage, addSurgery, updateSurgery, deleteSurgery, getSurgeryDetail, updateSurgeryStatus, getEncounterListByPatientId } from '@/api/surgerymanage'
import { getPatientList } from '@/api/cardRenewal/api'
import { listUser } from '@/api/system/user'
import { listOperatingRoom } from '@/api/operatingroom'
import { deptTreeSelect } from '@/api/system/user'
import useUserStore from '@/store/modules/user'
import { useDict } from '@/utils/dict'

const { proxy } = getCurrentInstance()
const loading = ref(true)
const showSearch = ref(true)
const surgeryList = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  surgeryNo: undefined,
  surgeryName: undefined,
  patientName: undefined,
  statusEnum: undefined,
  surgeryTypeEnum: undefined,
  plannedTime: undefined
})
const open = ref(false)
const isEditMode = ref(false)
const isViewMode = ref(false)
const form = ref({
  id: undefined,
  patientId: undefined,
  encounterId: undefined,
  encounterNo: undefined,
  applyDoctorName: undefined,
  applyDoctorId: undefined,
  applyDeptName: undefined,
  applyDeptId: undefined,
  surgeryName: undefined,
  surgeryCode: undefined,
  surgeryTypeEnum: undefined,
  surgeryLevel: undefined,
  plannedTime: undefined,
  mainSurgeonId: undefined,
  anesthetistId: undefined,
  assistant1Id: undefined,
  assistant2Id: undefined,
  scrubNurseId: undefined,
  anesthesiaTypeEnum: undefined,
  bodySite: undefined,
  operatingRoomId: undefined,
  operatingRoomName: undefined,
  orgId: undefined,
  preoperativeDiagnosis: undefined,
  postoperativeDiagnosis: undefined,
  surgeryDescription: undefined,
  postoperativeAdvice: undefined,
  surgeryFee: undefined,
  anesthesiaFee: undefined,
  totalFee: undefined,
  incisionLevel: undefined,
  healingLevel: undefined,
  complications: undefined,
  remark: undefined,
  emergencyFlag: 0,
  implantFlag: 0,
  operatingRoomConfirmTime: undefined,
  operatingRoomConfirmUser: undefined
})
const surgeryRef = ref()
const total = ref(0)
const title = ref('')
const operatingRoomList = ref([])
const operatingRoomLoading = ref(false)

const { surgery_type, surgery_level, incision_level, anesthesia_type, surgery_status, surgical_site } = 
useDict('surgery_type', 'surgery_level', 'incision_level', 'anesthesia_type', 'surgery_status', 'surgical_site')

// 字典选项
const surgeryStatusOptions = ref([
  { value: 0, label: '待排期' },
  { value: 1, label: '已排期' },
  { value: 2, label: '手术中' },
  { value: 3, label: '已完成' },
  { value: 4, label: '已取消' },
  { value: 5, label: '暂停' }
])

const healingLevelOptions = ref([
  { value: 1, label: '甲级愈合' },
  { value: 2, label: '乙级愈合' },
  { value: 3, label: '丙级愈合' }
])

// 下拉列表数据
const patientList = ref([])
const encounterList = ref([])
const encounterLoading = ref(false)
const doctorList = ref([])
const nurseList = ref([])
const orgList = ref([])

const rules = ref({
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  surgeryName: [{ required: true, message: '请输入手术名称', trigger: 'blur' }],
  surgeryTypeEnum: [{ required: true, message: '请选择手术类型', trigger: 'change' }],
  surgeryLevel: [{ required: true, message: '请选择手术等级', trigger: 'change' }],
  plannedTime: [{ required: true, message: '请选择计划手术时间', trigger: 'change' }],
  mainSurgeonId: [{ required: true, message: '请选择主刀医生', trigger: 'change' }],
  anesthesiaTypeEnum: [{ required: true, message: '请选择麻醉方式', trigger: 'change' }],
  bodySite: [{ required: true, message: '请输入手术部位', trigger: 'blur' }]
})

// 监听费用变化自动计算总费用
watch([() => form.value.surgeryFee, () => form.value.anesthesiaFee], ([newSurgeryFee, newAnesthesiaFee]) => {
  const surgeryFee = Number(newSurgeryFee) || 0
  const anesthesiaFee = Number(newAnesthesiaFee) || 0
  form.value.totalFee = surgeryFee + anesthesiaFee
})

getPageList()

function getList() {
  loading.value = true
  const params = { ...queryParams.value }
  // 处理时间范围
  if (params.plannedTime && params.plannedTime.length === 2) {
    params.plannedTimeStart = params.plannedTime[0]
    params.plannedTimeEnd = params.plannedTime[1]
    delete params.plannedTime
  }
  getSurgeryPage(params).then((res) => {
    surgeryList.value = res.data.records
    total.value = res.data.total
  }).catch(error => {
    console.error('获取手术列表失败:', error)
    proxy.$modal.msgError('获取手术列表失败，请稍后重试')
    surgeryList.value = []
    total.value = 0
  }).finally(() => {
    loading.value = false
  })
}

function getPageList() {
  getList()
}

// 处理分页参数
function handlePagination(pagination) {
  queryParams.value.pageNo = pagination.page
  queryParams.value.pageSize = pagination.limit
  getList()
}

function handleQuery() {
  queryParams.value.pageNo = 1
  getList()
}

function resetQuery() {
proxy.resetForm('queryRef')
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    surgeryNo: undefined,
    surgeryName: undefined,
    patientName: undefined,
    statusEnum: undefined,
    surgeryTypeEnum: undefined,
    plannedTime: undefined
  }
  getList()
}

function handleAdd() {
  title.value = '新增手术'
  isEditMode.value = false  // 设置为新增模式
  isViewMode.value = false  // 确保不是查看模式
  reset()
  open.value = true

  loadPatientList()
  loadDoctorList()
  loadOperatingRoomList()
  loadNurseList()
  loadOrgList()
}

// 加载患者列表
function loadPatientList() {
  getPatientList({ pageNo: 1, pageSize: 1000 }).then(res => {
    if (res.code === 200) {
      patientList.value = res.data.records || []
    } else {
      proxy.$modal.msgError('获取患者列表失败')
    }
  }).catch(error => {
    console.error('加载患者列表失败:', error)
    proxy.$modal.msgError('获取患者列表失败')
    patientList.value = []
  })
}

// 处理患者变化 - 自动加载就诊列表
function handlePatientChange(patientId) {
  // 保存当前的encounterId（编辑模式下需要保留）
  const currentEncounterId = form.value.encounterId

  // 清空就诊列表
  encounterList.value = []

  if (!patientId) {
    form.value.encounterId = undefined
    return
  }

  // 加载该患者的就诊列表
  encounterLoading.value = true
  getEncounterListByPatientId(patientId).then(res => {
    if (res.code === 200) {
      encounterList.value = res.data || []
      if (encounterList.value.length === 0) {
        proxy.$message.warning('该患者暂无就诊记录，请先挂号或办理住院')
      }

      // 在编辑模式下，恢复之前的encounterId（如果存在于新的列表中）
      if (currentEncounterId && encounterList.value.some(item => item.id === currentEncounterId)) {
        form.value.encounterId = currentEncounterId
      } else {
        form.value.encounterId = undefined
      }
    } else {
      proxy.$modal.msgError(res.msg || '获取就诊列表失败')
      encounterList.value = []
      form.value.encounterId = undefined
    }
  }).catch(error => {
    console.error('加载就诊列表失败:', error)
    proxy.$modal.msgError('获取就诊列表失败')
    encounterList.value = []
    form.value.encounterId = undefined
  }).finally(() => {
    encounterLoading.value = false
  })
}

// 加载医生列表
function loadDoctorList() {
  listUser({ pageNo: 1, pageSize: 1000 }).then(res => {
    if (res.code === 200) {
      doctorList.value = res.data.records || []
    } else {
      proxy.$modal.msgError('获取医生列表失败')
    }
  }).catch(error => {
    console.error('加载医生列表失败:', error)
    proxy.$modal.msgError('获取医生列表失败')
    doctorList.value = []
  })
}

// 加载手术室列表
function loadOperatingRoomList() {
  operatingRoomLoading.value = true
  listOperatingRoom({ pageNo: 1, pageSize: 1000, statusEnum: 1 }).then(res => {
    if (res.code === 200) {
      operatingRoomList.value = res.data.records || []
    } else {
      proxy.$modal.msgError('获取手术室列表失败')
    }
  }).catch(error => {
    console.error('加载手术室列表失败:', error)
    proxy.$modal.msgError('获取手术室列表失败')
    operatingRoomList.value = []
  }).finally(() => {
    operatingRoomLoading.value = false
  })
}

// 加载护士列表
function loadNurseList() {
  listUser({ pageNo: 1, pageSize: 1000 }).then(res => {
    if (res.code === 200) {
      nurseList.value = res.data.records || []
    } else {
      proxy.$modal.msgError('获取护士列表失败')
    }
  }).catch(error => {
    console.error('加载护士列表失败:', error)
    proxy.$modal.msgError('获取护士列表失败')
    nurseList.value = []
  })
}

// 加载执行科室列表
function loadOrgList() {
  deptTreeSelect().then(res => {
    if (res.code === 200) {
      // API返回的是分页对象，数据在records中，且已经是树形结构
      const records = res.data?.records || res.data || []
      orgList.value = Array.isArray(records) ? records : []
      console.log('加载执行科室列表成功，数量:', orgList.value.length)
      console.log('执行科室数据:', orgList.value)
    } else {
      proxy.$modal.msgError('获取执行科室列表失败')
      orgList.value = []
    }
  }).catch(error => {
    console.error('加载执行科室列表失败:', error)
    proxy.$modal.msgError('获取执行科室列表失败')
    orgList.value = []
  })
}

// 处理手术室变化
function handleOperatingRoomChange(operatingRoomId) {
  if (!operatingRoomId) {
    form.value.operatingRoomName = undefined
    return
  }

  // 根据ID查找手术室名称
  const room = operatingRoomList.value.find(item => item.id === operatingRoomId)
  if (room) {
    form.value.operatingRoomName = room.name
  }
}

// 处理主刀医生变化 - 自动设置执行科室
function handleMainSurgeonChange(mainSurgeonId) {
  if (!mainSurgeonId) {
    // 如果清空主刀医生，不自动清空执行科室，保持用户手动选择
    return
  }

  // 从医生列表中找到对应的医生信息
  const selectedDoctor = doctorList.value.find(doctor => doctor.practitionerId === mainSurgeonId)
  if (selectedDoctor && selectedDoctor.orgId) {
    // 自动设置执行科室为该医生的所属科室
    form.value.orgId = selectedDoctor.orgId
    // 同时设置科室名称
    form.value.orgName = findOrgNameById(orgList.value, selectedDoctor.orgId)
  }
}

// 处理执行科室变化
function handleOrgChange(orgId) {
  if (!orgId) {
    form.value.orgName = undefined
    return
  }

  // 递归查找科室名称
  form.value.orgName = findOrgNameById(orgList.value, orgId)
}

// 递归查找科室名称
function findOrgNameById(orgList, orgId) {
  for (const org of orgList) {
    if (org.id === orgId) {
      return org.name
    }
    if (org.children && org.children.length > 0) {
      const found = findOrgNameById(org.children, orgId)
      if (found) {
        return found
      }
    }
  }
  return null
}

function handleEdit(row) {
  console.log('handleEdit被调用', row, 'statusEnum:', row.statusEnum, 'statusEnum类型:', typeof row.statusEnum)

  // 检查状态：只有状态为新开（0）时才允许编辑
  if (Number(row.statusEnum) !== 0) {
    proxy.$modal.msgWarning('当前状态不允许编辑手术，仅新开状态可编辑')
    return
  }

  title.value = '编辑手术'
  isEditMode.value = true
  isViewMode.value = false
  console.log('【编辑模式】设置完成 - isEditMode:', isEditMode.value, 'isViewMode:', isViewMode.value)
  reset()  // 先清空表单，避免残留数据

  // 加载必要的数据
  loadPatientList()
  loadDoctorList()
  loadOperatingRoomList()
  loadNurseList()
  loadOrgList()

  getSurgeryDetail(row.id).then(res => {
    if (res.code === 200) {
      const data = res.data

      console.log('获取的手术详情数据:', data) // 添加调试信息

      // 逐个字段赋值，确保所有数据都能正确显示
      form.value.id = data.id
      form.value.patientId = data.patientId
      form.value.encounterId = data.encounterId
      form.value.encounterNo = data.encounterNo
      form.value.applyDoctorId = data.applyDoctorId
      form.value.applyDoctorName = data.applyDoctorName
      form.value.applyDeptId = data.applyDeptId
      form.value.applyDeptName = data.applyDeptName
      form.value.surgeryName = data.surgeryName
      form.value.surgeryCode = data.surgeryCode
      form.value.surgeryTypeEnum = data.surgeryTypeEnum
      form.value.surgeryLevel = data.surgeryLevel
      form.value.plannedTime = data.plannedTime
      form.value.mainSurgeonId = data.mainSurgeonId
      form.value.anesthetistId = data.anesthetistId
      form.value.assistant1Id = data.assistant1Id
      form.value.assistant2Id = data.assistant2Id
      form.value.scrubNurseId = data.scrubNurseId
      form.value.anesthesiaTypeEnum = data.anesthesiaTypeEnum
      form.value.bodySite = data.bodySite
      form.value.operatingRoomId = data.operatingRoomId
      form.value.operatingRoomName = data.operatingRoomName
      form.value.orgId = data.orgId
      form.value.preoperativeDiagnosis = data.preoperativeDiagnosis
      form.value.postoperativeDiagnosis = data.postoperativeDiagnosis
      form.value.surgeryDescription = data.surgeryDescription
      form.value.postoperativeAdvice = data.postoperativeAdvice
      form.value.surgeryFee = data.surgeryFee
      form.value.anesthesiaFee = data.anesthesiaFee
      form.value.totalFee = data.totalFee
      form.value.incisionLevel = data.incisionLevel
      form.value.healingLevel = data.healingLevel
      form.value.complications = data.complications
      form.value.remark = data.remark
      form.value.statusEnum = data.statusEnum
      form.value.emergencyFlag = data.emergencyFlag || 0
      form.value.implantFlag = data.implantFlag || 0
      form.value.operatingRoomConfirmTime = data.operatingRoomConfirmTime
      form.value.operatingRoomConfirmUser = data.operatingRoomConfirmUser
      form.value.emergencyFlag = data.emergencyFlag || 0
      form.value.implantFlag = data.implantFlag || 0
      form.value.operatingRoomConfirmTime = data.operatingRoomConfirmTime
      form.value.operatingRoomConfirmUser = data.operatingRoomConfirmUser

      // 打印赋值后的表单数据
      console.log('赋值后的表单数据:', {
        preoperativeDiagnosis: form.value.preoperativeDiagnosis,
        postoperativeDiagnosis: form.value.postoperativeDiagnosis,
        surgeryDescription: form.value.surgeryDescription,
        postoperativeAdvice: form.value.postoperativeAdvice,
        surgeryFee: form.value.surgeryFee,
        anesthesiaFee: form.value.anesthesiaFee,
        totalFee: form.value.totalFee,
        incisionLevel: form.value.incisionLevel,
        healingLevel: form.value.healingLevel,
        complications: form.value.complications,
        remark: form.value.remark
      })

      // 如果选择了患者，加载就诊列表
      if (form.value.patientId) {
        handlePatientChange(form.value.patientId)
      }
      
      // 确保界面更新
      nextTick(() => {
        console.log('nextTick执行，表单值更新完成')
        console.log('【编辑模式】数据加载后 - isEditMode:', isEditMode.value, 'isViewMode:', isViewMode.value)
        // 清除表单验证错误
        if (surgeryRef.value) {
          surgeryRef.value.clearValidate()
        }
      })
    }
  }).catch(error => {
    console.error('获取手术信息失败:', error)
    proxy.$modal.msgError('获取手术信息失败')
    open.value = false  // 获取失败时关闭对话框
  })
  
  // 在发起请求后立即打开对话框
  open.value = true
  console.log('【编辑模式】对话框打开 - isEditMode:', isEditMode.value, 'isViewMode:', isViewMode.value)
}

function handleView(row) {
  title.value = '查看手术'
  isViewMode.value = true
  isEditMode.value = false
  reset()
  
  // 加载必要的数据
  loadPatientList()
  loadDoctorList()
  loadOperatingRoomList()
  loadNurseList()
  loadOrgList()
  
  getSurgeryDetail(row.id).then(res => {
    if (res.code === 200) {
      const data = res.data

      console.log('【查看模式】获取的手术详情数据:', data) // 添加调试信息

      // 逐个字段赋值，确保所有数据都能正确显示
      form.value.id = data.id
      form.value.patientId = data.patientId
      form.value.encounterId = data.encounterId
      form.value.encounterNo = data.encounterNo
      form.value.applyDoctorId = data.applyDoctorId
      form.value.applyDoctorName = data.applyDoctorName
      form.value.applyDeptId = data.applyDeptId
      form.value.applyDeptName = data.applyDeptName
      form.value.surgeryName = data.surgeryName
      form.value.surgeryCode = data.surgeryCode
      form.value.surgeryTypeEnum = data.surgeryTypeEnum
      form.value.surgeryLevel = data.surgeryLevel
      form.value.plannedTime = data.plannedTime
      form.value.mainSurgeonId = data.mainSurgeonId
      form.value.anesthetistId = data.anesthetistId
      form.value.assistant1Id = data.assistant1Id
      form.value.assistant2Id = data.assistant2Id
      form.value.scrubNurseId = data.scrubNurseId
      form.value.anesthesiaTypeEnum = data.anesthesiaTypeEnum
      form.value.bodySite = data.bodySite
      form.value.operatingRoomId = data.operatingRoomId
      form.value.operatingRoomName = data.operatingRoomName
      form.value.orgId = data.orgId
      form.value.preoperativeDiagnosis = data.preoperativeDiagnosis
      form.value.postoperativeDiagnosis = data.postoperativeDiagnosis
      form.value.surgeryDescription = data.surgeryDescription
      form.value.postoperativeAdvice = data.postoperativeAdvice
      form.value.surgeryFee = data.surgeryFee
      form.value.anesthesiaFee = data.anesthesiaFee
      form.value.totalFee = data.totalFee
      form.value.incisionLevel = data.incisionLevel
      form.value.healingLevel = data.healingLevel
      form.value.complications = data.complications
      form.value.remark = data.remark
      form.value.statusEnum = data.statusEnum
      form.value.emergencyFlag = data.emergencyFlag || 0
      form.value.implantFlag = data.implantFlag || 0
      form.value.operatingRoomConfirmTime = data.operatingRoomConfirmTime
      form.value.operatingRoomConfirmUser = data.operatingRoomConfirmUser
      form.value.emergencyFlag = data.emergencyFlag || 0
      form.value.implantFlag = data.implantFlag || 0
      form.value.operatingRoomConfirmTime = data.operatingRoomConfirmTime
      form.value.operatingRoomConfirmUser = data.operatingRoomConfirmUser

      // 打印赋值后的表单数据
      console.log('【查看模式】赋值后的表单数据:', {
        preoperativeDiagnosis: form.value.preoperativeDiagnosis,
        postoperativeDiagnosis: form.value.postoperativeDiagnosis,
        surgeryDescription: form.value.surgeryDescription,
        postoperativeAdvice: form.value.postoperativeAdvice,
        surgeryFee: form.value.surgeryFee,
        anesthesiaFee: form.value.anesthesiaFee,
        totalFee: form.value.totalFee,
        incisionLevel: form.value.incisionLevel,
        healingLevel: form.value.healingLevel,
        complications: form.value.complications,
        remark: form.value.remark
      })

      // 如果选择了患者，加载就诊列表
      if (form.value.patientId) {
        handlePatientChange(form.value.patientId)
      }
      
      // 确保界面更新
      nextTick(() => {
        console.log('【查看模式】nextTick执行，表单值更新完成')
        // 清除表单验证错误
        if (surgeryRef.value) {
          surgeryRef.value.clearValidate()
        }
      })
    }
  }).catch(error => {
    console.error('获取手术信息失败:', error)
    proxy.$modal.msgError('获取手术信息失败')
    open.value = false  // 获取失败时关闭对话框
  })

  // 在发起请求后立即打开对话框
  open.value = true
}

function cancel() {
  open.value = false
  // 重置编辑模式标记
  isEditMode.value = false
  isViewMode.value = false
  // 重置表单（无论新增还是编辑模式都重置）
  reset()
}

function reset() {
  // 逐个重置属性，保持响应式
  form.value.id = undefined
  form.value.patientId = undefined
  form.value.encounterId = undefined
  form.value.encounterNo = undefined
  form.value.applyDoctorId = undefined
  form.value.applyDoctorName = undefined
  form.value.applyDeptId = undefined
  form.value.applyDeptName = undefined
  form.value.surgeryName = undefined
  form.value.surgeryCode = undefined
  form.value.surgeryTypeEnum = undefined
  form.value.surgeryLevel = undefined
  form.value.plannedTime = undefined
  form.value.mainSurgeonId = undefined
  form.value.anesthetistId = undefined
  form.value.assistant1Id = undefined
  form.value.assistant2Id = undefined
  form.value.scrubNurseId = undefined
  form.value.anesthesiaTypeEnum = undefined
  form.value.bodySite = undefined
  form.value.operatingRoomId = undefined
  form.value.operatingRoomName = undefined
  form.value.orgId = undefined
  form.value.preoperativeDiagnosis = undefined
  form.value.postoperativeDiagnosis = undefined
  form.value.surgeryDescription = undefined
  form.value.postoperativeAdvice = undefined
  form.value.surgeryFee = undefined
  form.value.anesthesiaFee = undefined
  form.value.totalFee = undefined
  form.value.incisionLevel = undefined
  form.value.healingLevel = undefined
  form.value.complications = undefined
  form.value.remark = undefined
  form.value.emergencyFlag = 0
  form.value.implantFlag = 0
  form.value.operatingRoomConfirmTime = undefined
  form.value.operatingRoomConfirmUser = undefined

  if (surgeryRef.value) {
    surgeryRef.value.resetFields()
  }
}

function submitForm() {
  // 如果是查看模式，不允许提交
  if (isViewMode.value) {
    proxy.$modal.msgInfo('当前为查看模式，无法提交修改')
    return
  }
  
  proxy.$refs['surgeryRef'].validate((valid) => {
    if (valid) {
      // 打印提交的数据，方便调试
      console.log('提交的表单数据:', JSON.parse(JSON.stringify(form.value)))
      console.log('operatingRoomId:', form.value.operatingRoomId, 'operatingRoomName:', form.value.operatingRoomName)

      // 获取当前登录用户信息，用于设置申请医生和科室
      const userStore = useUserStore()
      const currentUser = userStore.user

      // 创建提交数据对象，包含所有必要字段
      const submitData = {
        ...form.value,
        // 确保申请医生和科室信息被提交
        applyDoctorId: form.value.applyDoctorId || currentUser?.practitionerId,
        applyDoctorName: form.value.applyDoctorName || currentUser?.nickName,
        applyDeptId: form.value.applyDeptId || currentUser?.orgId,
        applyDeptName: form.value.applyDeptName
      }

      console.log('提交的数据对象:', JSON.parse(JSON.stringify(submitData)))

      if (form.value.id == undefined) {
        // 新增手术
        addSurgery(submitData).then((res) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          isEditMode.value = false  // 重置编辑模式标记
          isViewMode.value = false  // 重置查看模式标记
          getPageList()
        }).catch(error => {
          console.error('新增手术失败:', error)
          console.error('错误详情:', error.response || error.data || error.message)
          // 显示红色 toast 提示
          proxy.$message.error('新增手术失败，请检查表单信息')
        })
      } else {
        // 修改手术
        updateSurgery(submitData).then((res) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          isEditMode.value = false  // 重置编辑模式标记
          isViewMode.value = false  // 重置查看模式标记
          getPageList()
        }).catch(error => {
          console.error('更新手术失败:', error)
          console.error('错误详情:', error.response || error.data || error.message)
          // 显示红色 toast 提示
          proxy.$message.error('更新手术失败，请检查表单信息')
        })
      }
    } else {
      // 表单校验失败 - 显示红色 toast 提示
      proxy.$message.error('请检查表单信息，标红字段为必填项')
    }
  })
}

function handleDelete(row) {
  // 检查状态
  if (row.statusEnum === 0) {
    // 新开状态 - 直接删除
    proxy.$modal.confirm('是否确认删除手术"' + row.surgeryName + '"?').then(() => {
      return deleteSurgery(row.id)
    }).then(() => {
      getPageList()
      proxy.$modal.msgSuccess('删除成功')
    }).catch(error => {
      console.error('删除手术失败:', error)
      proxy.$modal.msgError('删除失败')
    })
  } else if (row.statusEnum === 1) {
    // 已排期状态 - 更新为已取消
    proxy.$modal.confirm('是否确认取消手术"' + row.surgeryName + '"?').then(() => {
      return updateSurgeryStatus(row.id, 4) // 4 = 已取消
    }).then(() => {
      getPageList()
      proxy.$modal.msgSuccess('手术已取消')
    }).catch(error => {
      console.error('取消手术失败:', error)
      proxy.$modal.msgError('取消失败')
    })
  } else {
    // 其他状态 - 不允许操作
    proxy.$modal.msgWarning('当前状态不允许取消手术')
  }
}

// 排期：从新开变为已排期
function handleSchedule(row) {
  // 验证必要信息
  if (!row.operatingRoomId) {
    proxy.$modal.msgWarning('请先选择手术室后再排期')
    return
  }
  if (!row.plannedTime) {
    proxy.$modal.msgWarning('请先设置计划手术时间后再排期')
    return
  }
  
  proxy.$modal.confirm('是否确认排期手术"' + row.surgeryName + '"?').then(() => {
    return updateSurgeryStatus(row.id, 1) // 1 = 已排期
  }).then(() => {
    getPageList()
    proxy.$modal.msgSuccess('手术已排期')
  }).catch(error => {
    console.error('排期失败:', error)
    proxy.$modal.msgError('排期失败')
  })
}

// 开始：从已排期变为手术中
function handleStart(row) {
  proxy.$modal.confirm('是否确认开始手术"' + row.surgeryName + '"?').then(() => {
    return updateSurgeryStatus(row.id, 2) // 2 = 手术中
  }).then(() => {
    getPageList()
    proxy.$modal.msgSuccess('手术已开始')
  }).catch(error => {
    console.error('开始手术失败:', error)
    proxy.$modal.msgError('开始手术失败')
  })
}

// 完成：从手术中变为已完成
function handleComplete(row) {
  proxy.$modal.confirm('是否确认完成手术"' + row.surgeryName + '"?').then(() => {
    return updateSurgeryStatus(row.id, 3) // 3 = 已完成
  }).then(() => {
    getPageList()
    proxy.$modal.msgSuccess('手术已完成')
  }).catch(error => {
    console.error('完成手术失败:', error)
    proxy.$modal.msgError('完成手术失败')
  })
}

function selectEncounter() {
  // TODO: 实现选择就诊的功能
  proxy.$modal.msgInfo('请选择就诊记录')
}

// 获取就诊状态文本
function getEncounterStatusText(statusEnum) {
  const statusMap = {
    1: '已挂号',
    2: '进行中',
    3: '已完成',
    4: '已退号'
  }
  return statusMap[statusEnum] || '未知状态'
}

// 获取状态文本
function getStatusText(status) {
  const textMap = {
    0: '待排期',
    1: '已排期',
    2: '手术中',
    3: '已完成',
    4: '已取消',
    5: '暂停'
  }
  return textMap[status] || '未知'
}

function getStatusType(status) {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'primary',
    3: 'success',
    4: 'danger',
    5: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取表格行样式
function getRowClassName({ row }) {
  if (row.statusEnum === 4) return 'cancelled-row'
  if (row.statusEnum === 3) return 'completed-row'
  if (row.statusEnum === 2) return 'in-progress-row'
  if (row.statusEnum === 1) return 'scheduled-row'
  return ''
}

// 当前选中行（高亮）
const currentRow = ref(null)
function handleCurrentChange(row) {
  currentRow.value = row
}

// 时间格式化函数
function parseTime(time, pattern) {
  if (!time) return ''
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}
</script>

<style scoped>
/* 已取消行的样式 */
:deep(.cancelled-row) {
  background-color: #f5f5f5;
  color: #999;
}

:deep(.cancelled-row .el-button--danger) {
  display: none;
}

/* 已完成行的样式 */
:deep(.completed-row) {
  background-color: #f0f9ff;
}

/* 手术中行的样式 */
:deep(.in-progress-row) {
  background-color: #fff7ed;
}

/* 已排期行的样式 */
:deep(.scheduled-row) {
  background-color: #fefce8;
}

/* 表单提示样式 */
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}
</style>