<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" label-width="90px">
      <el-row>
        <el-col :span="6">
          <el-form-item>
            <el-radio-group v-model="timeType">
              <el-radio label="create_time">创建时间</el-radio>
              <el-radio label="review_time">审核时间</el-radio>
              <el-radio label="date_time">预约时间</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="date"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="datePickerOptions"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="检查类型"
            prop="patient_type"
            v-show="showSearch"
          >
            <el-select
              v-model="queryParams.patient_type"
              placeholder="请选择检查类型"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in patientTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检查诊室" prop="exam_room" v-show="showSearch">
            <el-select
              v-model="queryParams.exam_room"
              placeholder="请选择检查诊室"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in examRoomsList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检查部位" prop="body_text" v-show="showSearch">
            <el-input
              v-model="queryParams.body_text"
              placeholder="请输入检查部位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检查设备" prop="equipment" v-show="showSearch">
            <el-select
              v-model="queryParams.equipment"
              placeholder="请选择检查设备"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in equipmentsList"
                :key="item.value"
                :label="item.name"
                :value="item.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="诊断医师"
            prop="reporter_name"
            v-show="showSearch"
          >
            <el-input
              v-model="queryParams.reporter_name"
              placeholder="请输入诊断医师"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="审核医生"
            prop="reviewer_name"
            v-show="showSearch"
          >
            <el-input
              v-model="queryParams.reviewer_name"
              placeholder="请输入审核医生"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="病例类型" prop="report_type">
            <el-select
              v-model="queryParams.report_type"
              placeholder="请选择病例类型"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in reportTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="患者姓名"
            prop="patient_name"
            v-show="showSearch"
          >
            <el-input
              v-model="queryParams.patient_name"
              placeholder="请输入患者姓名"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="病例号" prop="patient_id" v-show="showSearch">
            <el-input
              v-model="queryParams.patient_id"
              placeholder="请输入病例号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="检查结果" prop="negative" v-show="showSearch">
            <el-select
              v-model="queryParams.negative"
              placeholder="请选择检查结果"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in negativeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleQuery"
            >
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">
          新增
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>
    <el-table
      v-loading="loading"
      :data="caseList"
      border
      height="calc(100vh - 300px)"
      @row-dblclick="handleView"
    >
      <el-table-column
        label="检查号"
        prop="id"
        width="80"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="患者姓名"
        prop="patient_name"
        width="100"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            desensitize(
              scope.row.patient_name,
              1,
              0,
              scope.row.patient_name.length
            )
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="病例号"
        prop="patient_id"
        width="110"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="性别"
        width="70"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            patientSexList.find((i) => i.value == scope.row.patient_sex)
              .label || "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="年龄"
        width="80"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.patient_age }}
          {{
            patientAgeTypeList.find(
              (i) => i.value == scope.row.patient_age_type
            ).label || "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="预约时间"
        width="200"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handleTimeSectionUpdate(scope.row)">
            {{ scope.row.date_time }} {{ scope.row.time_section }}
            <i class="el-icon-edit el-icon--right"></i>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="检查部位"
        width="120"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.positions.map((item) => item.level2.name).join("|") }}
        </template>
      </el-table-column>
      <el-table-column
        label="检查类型"
        width="90"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            patientTypeList.find((i) => i.value == scope.row.patient_type)
              .label || "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="检查结果"
        width="90"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{
            negativeList.find((i) => i.value == scope.row.negative).label || "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="检查诊室"
        width="120"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.exam_rooms.map((item) => item.name).join(", ") || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="诊断医师"
        prop="reporter_name"
        width="100"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="审核医生"
        prop="reviewer_name"
        width="100"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="报告状态"
        width="90"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ statusList.find((i) => i.value == scope.row.status).label || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="打印次数"
        prop="print"
        width="80"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="创建时间"
        prop="create_time"
        width="160"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="审核时间"
        prop="review_time"
        width="160"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="门诊号"
        prop="outpatient_number"
        width="100"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="住院号"
        prop="hospitalization_number"
        width="100"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="病区号"
        prop="area_number"
        width="80"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="床位号"
        prop="bed_number"
        width="80"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="申请医师"
        prop="request_doctor"
        width="100"
        align="center"
        show-overflow-tooltip
      />
    </el-table>
    <pagination
      v-show="queryParams.total > 0"
      :total="queryParams.total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />
    <!-- 添加对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="6" v-if="!isEditMode">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input
                v-model="form.patient_name"
                placeholder="请输入患者姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6" v-if="!isEditMode">
            <el-form-item label="性别" prop="patient_sex">
              <el-select
                v-model="form.patient_sex"
                style="width: 100%"
                placeholder="请选择性别"
                filterable
                clearable
              >
                <el-option
                  v-for="item in patientSexList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="!isEditMode">
            <el-form-item label="年龄" prop="patient_age">
              <el-input-number
                v-model="form.patient_age"
                placeholder="请输入年龄"
                clearable
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" v-if="!isEditMode">
            <el-form-item label="" prop="patient_age_type" label-width="0">
              <el-select
                v-model="form.patient_age_type"
                style="width: 100%"
                placeholder="请选择年龄单位"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in patientAgeTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="病例号" prop="patient_id">
              <el-input
                v-model="form.patient_id"
                placeholder="请输入病例号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="检查类型" prop="patient_type">
              <el-select
                v-model="form.patient_type"
                style="width: 100%"
                placeholder="请选择检查类型"
                filterable
                clearable
              >
                <el-option
                  v-for="item in patientTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  v-show="item.value != -1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="门诊号" prop="outpatient_number">
              <el-input
                v-model="form.outpatient_number"
                placeholder="请输入门诊号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="住院号" prop="hospitalization_number">
              <el-input
                v-model="form.hospitalization_number"
                placeholder="请输入住院号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="病区号" prop="area_number">
              <el-input
                v-model="form.area_number"
                placeholder="请输入病区号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="床位号" prop="bed_number">
              <el-input
                v-model="form.bed_number"
                placeholder="请输入床位号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="申请医师" prop="request_doctor">
              <el-input
                v-model="form.request_doctor"
                placeholder="请输入申请医师"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="专家" prop="expert_ids">
              <el-select
                v-model="form.expert_ids"
                multiple
                style="width: 100%"
                placeholder="请选择专家"
                filterable
                clearable
              >
                <el-option
                  v-for="item in expertIdsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.username }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="检查设备" prop="equipments">
              <el-select
                v-model="form.equipments"
                multiple
                style="width: 100%"
                placeholder="请选择检查设备"
                filterable
                clearable
              >
                <el-option
                  v-for="item in equipmentsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="检查部位" prop="templates">
              <el-select
                v-model="form.templates"
                multiple
                style="width: 100%"
                placeholder="请选择检查部位"
                filterable
                clearable
              >
                <el-option-group
                  v-for="group in templatesList"
                  :key="group.id"
                  :label="group.name"
                >
                  <el-option
                    v-for="item in group.child"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-option-group>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="检查诊室" prop="exam_rooms">
              <el-select
                v-model="form.exam_rooms"
                style="width: 100%"
                placeholder="请选择检查诊室"
                @change="handleExamRoomsChange"
                filterable
                clearable
                multiple
              >
                <el-option
                  v-for="item in examRoomsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isEditMode">
            <el-form-item label="自定义部位" prop="position_text">
              <el-input
                v-model="form.position_text"
                placeholder="请输入自定义部位"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约日期" prop="date_time">
              <el-date-picker
                v-model="form.date_time"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择预约日期"
                style="width: 100%"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="time_section">
              <el-select
                v-model="form.time_section"
                placeholder="请选择预约时间"
                style="width: 100%"
                filterable
                clearable
              >
                <el-option label="自动" value="auto" />
                <el-option
                  v-for="item in timeSectionList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  postReportList,
  postReportExamRoomList,
  postReportTemplateTree,
  postReportEquipmentList,
  postReportTimeSections,
  postReportCreate,
  postReportInfo,
  postReportTimeSectionEdit,
} from "@/api/cases/index.js";
import { searchUsers } from "@/api/contacts/index.js";
export default {
  name: "Case",
  data() {
    // 获取今天日期
    const today = new Date().toISOString().split("T")[0];
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 显示搜索条件
      showSearch: false,
      // 表格数据
      caseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否为编辑模式
      isEditMode: false,
      // 字典
      //  性别
      patientSexList: [
        // { label: "所有", value: "-1" },
        { label: "未知", value: 0 },
        { label: "男", value: 1 },
        { label: "女", value: 2 },
      ],
      //  年龄单位
      patientAgeTypeList: [
        { label: "岁", value: 0 },
        { label: "月", value: 1 },
        { label: "日", value: 2 },
        { label: "时", value: 3 },
        { label: "分", value: 4 },
        { label: "秒", value: 5 },
      ],
      //  检查类型
      patientTypeList: [
        { label: "全部", value: -1 },
        { label: "门诊", value: 0 },
        { label: "急诊", value: 1 },
        { label: "住院", value: 2 },
      ],
      // 专家
      expertIdsList: [],
      //  检查设备
      equipmentsList: [],
      //  检查部位
      templatesList: [],
      //  检查诊室
      examRoomsList: [],
      // 预约时间
      timeSectionList: [],
      //  病例类型
      reportTypeList: [
        { label: "本院报告", value: 1 },
        { label: "我参与的会诊", value: 2 },
        { label: "我审核的", value: 3 },
      ],
      //  检查结果
      negativeList: [
        { label: "全部", value: -1 },
        { label: "阳性", value: 0 },
        { label: "阴性", value: 1 },
      ],
      statusList: [
        { label: "新建", value: 1 },
        { label: "暂存", value: 5 },
        { label: "已提交", value: 10 },
        { label: "驳回", value: 15 },
        { label: "已完成", value: 20 },
      ],
      // 查询参数
      timeType: "date_time",
      date: [],
      datePickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick: (picker) => {
              const end = new Date();
              const start = new Date();
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "昨天",
            onClick: (picker) => {
              const end = new Date();
              end.setTime(end.getTime() - 3600 * 1000 * 24);
              const start = new Date(end);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本周",
            onClick: (picker) => {
              const end = new Date();
              const start = new Date();
              const day = start.getDay();
              start.setDate(start.getDate() - day + (day === 0 ? -6 : 1));
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "本月",
            onClick: (picker) => {
              const end = new Date();
              const start = new Date(
                new Date().getFullYear(),
                new Date().getMonth(),
                1
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上月",
            onClick: (picker) => {
              const end = new Date(
                new Date().getFullYear(),
                new Date().getMonth(),
                0
              );
              const start = new Date(
                new Date().getFullYear(),
                new Date().getMonth() - 1,
                1
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "今年",
            onClick: (picker) => {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0, 1);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      queryParams: {
        page: 1,
        size: 10,
        total: 0,
        create_time_start: "",
        create_time_end: "",
        review_time_start: "",
        review_time_end: "",
        date_time_start: "",
        date_time_end: "",
        patient_type: -1,
        exam_room: "",
        body_text: "",
        equipment: "",
        reporter_name: "",
        reviewer_name: "",
        report_type: 1,
        patient_name: "",
        patient_id: "",
        negative: -1,
      },
      // 表单参数
      form: {
        // 患者姓名*
        patient_name: "",
        // 性别*
        patient_sex: "",
        // 年龄*
        patient_age: "",
        // 年龄类型*
        patient_age_type: "",
        // 病例号*
        patient_id: "",
        // 检查类型*
        patient_type: "",
        // 门诊号
        outpatient_number: "",
        // 住院号
        hospitalization_number: "",
        // 病区号
        area_number: "",
        // 床位号
        bed_number: "",
        // 申请医生
        request_doctor: "",
        // 专家
        expert_ids: [],
        // 检查设备
        equipments: [],
        // 检查部位
        templates: [],
        // 检查诊室
        exam_rooms: [],
        // 自定义部位
        position_text: "",
        // 预约日期
        date_time: "",
        // 预约时间
        time_section: "",
        // 备注
        comment: "",
        // 患者电话
        patient_phone: "",
        // 会诊ID
        consultation_id: 0,
        // 离线会诊ID
        off_consultation_id: 0,
      },
      // 表单校验
      rules: {
        patient_name: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "患者姓名长度必须在2到50个字符之间",
            trigger: "blur",
          },
        ],
        patient_age: [
          { required: true, message: "年龄不能为空", trigger: "change" },
        ],
        patient_age_type: [
          { required: true, message: "年龄类型不能为空", trigger: "change" },
        ],
        patient_sex: [
          { required: true, message: "性别不能为空", trigger: "change" },
        ],
        patient_id: [
          { required: true, message: "病例号不能为空", trigger: "blur" },
          {
            min: 0,
            max: 50,
            message: "病例号长度必须在0到50个字符之间",
            trigger: "blur",
          },
        ],
        patient_type: [
          { required: true, message: "检查类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.resetQuery();
    this.initDataDictionaries();
  },
  methods: {
    // 初始化数据字典
    initDataDictionaries() {
      this.loadExpertIdsList();
      this.loadExamRooms();
      this.loadEquipments();
      this.loadTemplateTree();
    },
    // 加载专家列表
    loadExpertIdsList() {
      searchUsers({
        role_id: 1,
        size: 99999,
      })
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.expertIdsList = response.data.list;
          }
        })
        .catch((error) => {
          console.error("加载专家列表失败:", error);
        });
    },
    // 加载检查设备列表
    loadEquipments() {
      postReportEquipmentList({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.equipmentsList = response.data;
          }
        })
        .catch((error) => {
          console.error("加载检查设备列表失败:", error);
        });
    },
    // 加载检查部位
    loadTemplateTree() {
      postReportTemplateTree({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.templatesList = response.data;
          }
        })
        .catch((error) => {
          console.error("加载检查部位模板树失败:", error);
        });
    },
    // 检查诊室列表
    loadExamRooms() {
      postReportExamRoomList({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.examRoomsList = response.data;
          }
        })
        .catch((error) => {
          console.error("加载检查诊室列表失败:", error);
        });
    },
    // 选择检查室后，根据日期和检查室获取可用时间槽
    handleExamRoomsChange(exam_rooms_id) {
      this.form.time_section = "";
      if (this.form.date_time) this.fetchTimeSlots(exam_rooms_id[0]);
      else this.timeSectionList = [];
    },
    async fetchTimeSlots(exam_rooms_id) {
      postReportTimeSections({ exam_room_id: exam_rooms_id }).then(
        (response) => {
          this.timeSectionList = response.data || [];
        }
      );
    },
    // 构建时间范围参数
    buildTimeRangeParams() {
      if (this.date && Array.isArray(this.date) && this.date.length === 2) {
        // 先清除之前的时间范围参数
        const timeTypes = ["create_time", "review_time", "date_time"];
        timeTypes.forEach((type) => {
          delete this.queryParams[`${type}_start`];
          s;
          delete this.queryParams[`${type}_end`];
        });
        // 根据当前 timeType 设置对应的时间范围参数
        this.queryParams[`${this.timeType}_start`] = this.date[0];
        this.queryParams[`${this.timeType}_end`] = this.date[1];
      }
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.buildTimeRangeParams();
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      const today = new Date().toISOString().split("T")[0];
      this.timeType = "date_time";
      this.date = [today, today];
      this.queryParams.patient_type = this.patientTypeList[0].value;
      // this.queryParams.report_type = this.reportTypeList[0].value;
      this.handleQuery();
    },
    // 查询列表
    getList() {
      this.loading = true;
      postReportList(this.queryParams)
        .then((response) => {
          this.caseList = response.data?.list || [];
          this.queryParams.total = response.data.total;
          console.log("病例库", response.data);
          this.loading = false;
        })
        .catch(() => {
          this.caseList = [];
          this.queryParams.total = 0;
          this.loading = false;
        });
    },
    cancel() {
      this.open = false;
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      const today = new Date().toISOString().split("T")[0];
      this.form = {
        patient_sex: this.patientSexList[0].value,
        patient_type: this.patientTypeList[1].value,
        patient_age_type: this.patientAgeTypeList[0].value,
        date_time: today,
      };
      this.open = true;
      this.title = "新增病例";
      this.isEditMode = false;
    },
    // 修改预约时间按钮操作
    handleTimeSectionUpdate(row) {
      this.reset();
      postReportInfo({ report_id: row.id }).then((response) => {
        this.fetchTimeSlots(response.data.exam_rooms[0].id);
        this.form = response.data || {};
        this.open = true;
        this.title = "修改预约时间";
        this.isEditMode = true;
      });
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            // 修改病例
            postReportTimeSectionEdit({
              date_time: this.form.date_time,
              report_id: this.form.id,
              time_section: this.form.time_section,
            })
              .then((response) => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("预约时间修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.$modal.msgError(response.msg || "预约时间修改成功失败");
                }
              })
              .catch(() => {
                this.$modal.msgError("预约时间修改成功失败");
              });
          } else {
            // 新增病例
            postReportCreate(this.form)
              .then((response) => {
                if (response.code === 200) {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  if (response.data && response.data.id) {
                    this.handleView(response.data);
                  } else {
                    this.getList();
                  }
                } else {
                  this.$modal.msgError(response.msg || "新增失败");
                }
              })
              .catch(() => {
                this.$modal.msgError("新增失败");
              });
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    // 查看按钮操作
    handleView(row) {
      // 先获取病例详情
      postReportInfo({ id: row.id })
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.$router.push({
              name: "PatientDetail",
              params: {
                id: response.data.id,
                patientName: response.data.patient_name,
              },
            });
          } else {
            this.$modal.msgError("获取病例详情失败");
          }
        })
        .catch(() => {
          // 如果接口失败，使用传入的 row 数据
          this.$router.push({
            name: "PatientDetail",
            params: {
              id: row.id,
              patientName: row.patient_name || row.patientName,
            },
          });
        });
    },
  },
};
</script>