<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_id"
            v-show="showSearch"
          >
            <el-select
              v-model="queryParams.exam_room_id"
              placeholder="请选择检查诊室"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in examRoomList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </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_ids"
            v-show="showSearch"
          >
            <el-select
              v-model="queryParams.equipment_ids"
              multiple
              placeholder="请选择检查设备"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </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)"
    >
      <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 }}
          {{ getAgeUnit(scope.row.patient_age_type) }}
        </template>
      </el-table-column>
      <el-table-column
        label="预约时间"
        width="180"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.date_time }} {{ scope.row.time_section }}
        </template>
      </el-table-column>
      <el-table-column
        label="检查部位"
        width="120"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.positions.map((r) => r.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((r) => r.name).join(", ") || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        label="申请医师"
        prop="request_doctor"
        width="100"
        align="center"
        show-overflow-tooltip
      />
      <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="操作"
        width="200"
        align="center"
        show-overflow-tooltip
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >
            查看
          </el-button>
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </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">
            <el-form-item label="患者姓名" prop="patient_name">
              <el-input
                v-model="form.patient_name"
                placeholder="请输入患者姓名"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="patient_sex">
              <el-select
                v-model="form.patient_sex"
                style="width: 100%"
                placeholder="请选择性别"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <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">
            <el-form-item label="年龄" prop="patient_age">
              <el-input-number
                v-model="form.patient_age"
                placeholder="请输入年龄"
                clearable
                :min="0"
                style="width: 100%"
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <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">
            <el-form-item label="病例号" prop="patient_id">
              <el-input
                v-model="form.patient_id"
                placeholder="请输入病例号"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查类型" prop="patient_type">
              <el-select
                v-model="form.patient_type"
                style="width: 100%"
                placeholder="请选择检查类型"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <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="12">
            <el-form-item label="门诊号" prop="outpatient_number">
              <el-input
                v-model="form.outpatient_number"
                placeholder="请输入门诊号"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="住院号" prop="hospitalization_number">
              <el-input
                v-model="form.hospitalization_number"
                placeholder="请输入住院号"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="病区号" prop="area_number">
              <el-input
                v-model="form.area_number"
                placeholder="请输入病区号"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="床位号" prop="bed_number">
              <el-input
                v-model="form.bed_number"
                placeholder="请输入床位号"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请医师" prop="request_doctor">
              <el-input
                v-model="form.request_doctor"
                placeholder="请输入申请医师"
                clearable
                :disabled="isEditMode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专家" prop="expert_doctor">
              <el-select
                v-model="form.expert_doctor"
                multiple
                style="width: 100%"
                placeholder="请选择专家"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in doctorList"
                  :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="equipments">
              <el-select
                v-model="form.equipments"
                multiple
                style="width: 100%"
                placeholder="请选择检查设备"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in equipmentList"
                  :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="body_text">
              <el-select
                v-model="form.body_text"
                multiple
                style="width: 100%"
                placeholder="请选择检查部位"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in body_textList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                  <span style="float: left">{{ item.label }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.category }}
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检查诊室" prop="exam_rooms">
              <el-select
                v-model="form.exam_rooms"
                style="width: 100%"
                placeholder="请选择检查诊室"
                @change="handleexam_roomChange"
                filterable
                clearable
                :disabled="isEditMode"
              >
                <el-option
                  v-for="item in examRoomList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义部位" prop="position_text">
              <el-input
                v-model="form.position_text"
                placeholder="请输入自定义部位"
                clearable
                :disabled="isEditMode"
              />
            </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="请选择预约日期"
                @change="handleDateChange"
                style="width: 100%"
                clearable
              />
            </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="slot in availableTimeSlots"
                  :key="slot.value"
                  :label="slot.label"
                  :value="slot.value"
                />
              </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,
  postReportCreate,
  postReportInfo,
  postReportEdit,
} from "@/api/cases/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 },
      ],
      //  检查设备
      equipmentList: [],
      //  检查诊室
      examRoomList: [],
      //  病例类型
      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 },
      ],

      templateTree: [],
      doctorList: [
        { label: "专家1", value: "1" },
        { label: "专家2", value: "2" },
      ],

      body_textList: [
        { label: "肝脏", value: "1", category: "腹部" },
        { label: "胆囊", value: "2", category: "腹部" },
        { label: "胰腺", value: "3", category: "腹部" },
        { label: "肾脏", value: "4", category: "腹部" },
        { label: "脾脏", value: "5", category: "腹部" },
        { label: "腹部血管", value: "6", category: "腹部" },
        { label: "子宫", value: "7", category: "子宫" },
        { label: "颈部血管", value: "8", category: "外周血管" },
        { label: "上肢血管", value: "9", category: "外周血管" },
        { label: "下肢血管", value: "10", category: "外周血管" },
        { label: "产科", value: "11", category: "产科" },
        { label: "甲状腺", value: "12", category: "甲状腺" },
        { label: "乳腺", value: "13", category: "乳腺" },
        { label: "睾丸", value: "14", category: "睾丸" },
        { label: "泌尿", value: "15", category: "泌尿" },
        { label: "心脏", value: "16", category: "心脏" },
        { label: "其它", value: "17", category: "其它" },
        { label: "眼科", value: "18", category: "眼科" },
      ],
      availableTimeSlots: [],
      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]);
            },
          },
        ],
      },
      // 查询参数
      timeType: "date_time",
      date: [],
      queryParams: {
        page: 1,
        size: 10,
        total: 0,
        patient_type: -1,
        exam_room_id: "",
        body_text: "",
        equipment_ids: [],
        reporter_name: "",
        reviewer_name: "",
        report_type: 0,
        patient_name: "",
        patient_id: "",
        negative: -1,
        create_time_start: "",
        create_time_end: "",
        review_time_start: "",
        review_time_end: "",
        date_time_start: "",
        date_time_end: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        patientName: [
          { required: true, message: "患者姓名不能为空", trigger: "blur" },
        ],
        patientRecordNumber: [
          { required: true, message: "病例号不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.resetQuery();
    this.initDataDictionaries();
  },
  methods: {
    // 初始化数据字典
    initDataDictionaries() {
      this.loadExamRooms();
      this.loadEquipments();
      this.loadTemplateTree();
    },
    // 检查诊室列表
    loadExamRooms() {
      postReportExamRoomList({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.examRoomList = response.data;
          }
        })
        .catch((error) => {
          console.error("加载检查诊室列表失败:", error);
        });
    },
    // 加载检查设备列表
    loadEquipments() {
      postReportEquipmentList({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.equipmentList = response.data;
          }
        })
        .catch((error) => {
          console.error("加载检查设备列表失败:", error);
        });
    },
    // 查询列表
    getList() {
      this.loading = true;
      postReportList(this.queryParams)
        .then((response) => {
          (this.caseList = [
            {
              id: 61141,
              patient_id: "病区号",
              patient_name: "患者姓名",
              patient_sex: 1,
              patient_age: 3,
              patient_age_type: 0,
              patient_number: "",
              number: "HJ2026052817270301",
              outpatient_number: "门诊号",
              request_doctor: "申请医师",
              hospitalization_number: "住院号",
              area_number: "病区号",
              bed_number: "床位号",
              patient_type: 0,
              patient_phone: "",
              comment: "",
              position_text: "自定义部位",
              print: 0,
              negative: 1,
              status: 1,
              status_comment: "",
              reporter_id: 688,
              reviewer_id: 0,
              review_time: "",
              create_time: "2026-05-28 17:27:03",
              date_time: "2026-05-28",
              time_section: "08:00-08:10",
              reporter_name: "会诊专家测试01",
              reviewer_name: "",
              positions: [
                {
                  level1: {
                    template_id: 1,
                    name: "腹部",
                  },
                  level2: {
                    template_id: 2,
                    name: "肝脏",
                  },
                },
              ],
              exam_rooms: [
                {
                  id: 6,
                  name: "我的诊室",
                },
              ],
            },
          ]),
            (this.queryParams.total = response.data.total);
          console.log("病例库", response.data);
          this.loading = false;
        })
        .catch(() => {
          this.caseList = [];
          this.queryParams.total = 0;
          this.loading = false;
        });
    },
    // 获取年龄单位
    getAgeUnit(type) {
      const unit = this.patientAgeTypeList.find((i) => i.value == type);
      return unit ? unit.label : "";
    },

    // 加载检查部位模板树
    loadTemplateTree() {
      postReportTemplateTree({})
        .then((response) => {
          if (response.code === 200 && response.data) {
            this.templateTree = response.data;
            this.buildBodyTextList(response.data);
          }
        })
        .catch((error) => {
          console.error("加载检查部位模板树失败:", error);
        });
    },
    // 构建检查部位列表
    buildBodyTextList(treeData) {
      const flatList = [];
      const flatten = (items, parentName = "") => {
        items.forEach((item) => {
          if (item.children && item.children.length > 0) {
            flatten(item.children, item.name);
          } else {
            flatList.push({
              label: item.name,
              value: item.id.toString(),
              category: parentName || item.level1?.name || "",
              level1: item.level1,
              level2: item.level2,
            });
          }
        });
      };
      flatten(treeData);
      this.body_textList = flatList;
    },
    cancel() {
      this.open = false;
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.buildTimeRangeParams();
      this.getList();
    },
    // 构建时间范围参数
    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];
      }
    },
    // 重置按钮操作
    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();
    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      const today = new Date().toISOString().split("T")[0];
      this.form = {
        gender: this.patientSexList[0].value,
        patient_type: this.patientTypeList[0].value,
        ageUnit: this.patientAgeTypeList[0].value,
        date_time: today,
      };
      this.open = true;
      this.title = "新增病例";
      this.isEditMode = false;
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      // postReportInfo({ report_id: row.id }).then((response) => {
      this.form = {
        id: 61141,
        patient_id: "病区号",
        patient_name: "患者姓名",
        patient_sex: 1,
        patient_age: 3,
        patient_age_type: 0,
        patient_number: "",
        number: "HJ2026052817270301",
        outpatient_number: "门诊号",
        request_doctor: "申请医师",
        hospitalization_number: "住院号",
        area_number: "病区号",
        bed_number: "床位号",
        patient_type: 0,
        patient_phone: "",
        comment: "",
        position_text: "自定义部位",
        extend_json: "",
        consultation_id: 0,
        off_consultation_id: 0,
        print: 0,
        negative: 1,
        status: 1,
        status_comment: "",
        group_id: 23,
        hospital_id: 23,
        p_code: "37",
        c_code: "3702",
        a_code: "370202",
        reporter_id: 688,
        reviewer_id: 0,
        del_flag: 0,
        review_time: "",
        date_time: "2026-05-28",
        time_section: "08:00-08:10",
        pstkey: null,
        hmac: "",
        create_time: "2026-05-28 17:27:03",
        update_time: "2026-05-28 17:27:03",
        positions: [
          {
            level1: {
              template_id: 1,
              name: "腹部",
            },
            level2: {
              template_id: 2,
              name: "肝脏",
            },
          },
        ],
        equipments: [
          {
            id: 25,
            name: "测试B超检测设备",
          },
        ],
        exam_rooms: [
          {
            id: 6,
            name: "我的诊室",
          },
        ],
        text_comment: "",
        text_conclusion: "",
        attachment: [],
        reporter_name: "会诊专家测试01",
        reporter_signature: "",
        reporter_sign_hash: "",
        reviewer_name: "",
        reviewer_signature: "",
        reviewer_sign_hash: "",
        experts: [
          {
            expert_id: 10,
            expert_name: "测试01",
            user_comment: "",
            confirm: 0,
            signature: "",
            sign_hash: "",
            comment_time: "2026-05-28 17:27:03",
          },
        ],
      };
      this.open = true;
      this.title = "修改病例";
      this.isEditMode = true;
      // });
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const formData = this.buildCaseFormData();
          if (this.form.id != undefined) {
            // 修改病例
            postReportEdit(formData)
              .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(formData)
              .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("新增失败");
              });
          }
        }
      });
    },
    // 构建病例表单数据
    buildCaseFormData() {
      const form = { ...this.form };
      // 转换字段名以匹配API要求
      if (form.patientName !== undefined) form.patient_name = form.patientName;
      if (form.gender !== undefined) form.patient_sex = parseInt(form.gender);
      if (form.age !== undefined) form.patient_age = parseInt(form.age);
      if (form.ageUnit !== undefined)
        form.patient_age_type = parseInt(form.ageUnit);
      if (form.patientRecordNumber !== undefined)
        form.patient_id = form.patientRecordNumber;
      if (form.checkType !== undefined)
        form.patient_type = parseInt(form.checkType);
      if (form.outpatient_number !== undefined)
        form.outpatient_number = form.outpatient_number;
      if (form.inpatientNumber !== undefined)
        form.hospitalization_number = form.inpatientNumber;
      if (form.wardNumber !== undefined) form.area_number = form.wardNumber;
      if (form.bedNumber !== undefined) form.bed_number = form.bedNumber;
      if (form.applyDoctor !== undefined)
        form.request_doctor = form.applyDoctor;
      if (form.checkRoom !== undefined)
        form.exam_room_id = parseInt(form.checkRoom);
      if (form.customPart !== undefined) form.position_text = form.customPart;
      if (form.date_time !== undefined) form.date_time = form.date_time;
      if (form.time_section !== undefined)
        form.time_section = form.time_section;
      return form;
    },
    // 选择检查室后，根据日期和检查室获取可用时间槽
    handleexam_roomChange(roomId) {
      this.form.time_section = "";
      if (roomId && this.form.date_time)
        this.fetchTimeSlots(roomId, this.form.date_time);
      else this.availableTimeSlots = [];
    },
    handleDateChange(date) {
      this.form.time_section = "";
      if (this.form.exam_room && date)
        this.fetchTimeSlots(this.form.exam_room, date);
      else this.availableTimeSlots = [];
    },
    async fetchTimeSlots(roomId) {
      const mockData = {
        1: [
          { label: "13:30-14:00", value: "13:30-14:00" },
          { label: "14:00-14:30", value: "14:00-14:30" },
          { label: "14:30-15:00", value: "14:30-15:00" },
          { label: "15:00-15:30", value: "15:00-15:30" },
        ],
        2: [
          { label: "09:00-09:30", value: "09:00-09:30" },
          { label: "09:30-10:00", value: "09:30-10:00" },
          { label: "10:00-10:30", value: "10:00-10:30" },
          { label: "10:30-11:00", value: "10:30-11:00" },
        ],
      };
      this.availableTimeSlots = mockData[roomId] || [];
    },
    getTimeSlots(roomId) {
      const mockData = {
        1: [
          { label: "13:30-14:00", value: "13:30-14:00" },
          { label: "14:00-14:30", value: "14:00-14:30" },
          { label: "14:30-15:00", value: "14:30-15:00" },
          { label: "15:00-15:30", value: "15:00-15:30" },
        ],
        2: [
          { label: "09:00-09:30", value: "09:00-09:30" },
          { label: "09:30-10:00", value: "09:30-10:00" },
          { label: "10:00-10:30", value: "10:00-10:30" },
          { label: "10:30-11:00", value: "10:30-11:00" },
        ],
      };
      return mockData[roomId] || [];
    },
    // 选择预约时间后，更新预约时间
    handletime_sectionChange(row) {
      const updateData = {
        id: row.id,
        date_time: row.date_time,
        time_section: row.time_section,
      };
      updateCase(updateData)
        .then((response) => {
          if (response.code === 200) {
            this.$modal.msgSuccess("预约时间修改成功");
            this.getList();
          } else {
            this.$modal.msgError(response.msg || "修改失败");
          }
        })
        .catch(() => {
          this.$modal.msgError("修改失败");
        });
    },
    // 查看按钮操作
    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>