<template>
  <div style="width: 100%; height: 100%; display: flex; flex-direction: column">
    <!-- 西药处方按钮区域 -->
    <div
      style="
        margin-bottom: 10px;
        border-bottom: 1px solid #e4e7ed;
        padding-bottom: 10px;
        flex-shrink: 0;
      "
    >
      <el-button type="primary" @click="handleAddWesternPrescription">
        +西药方
      </el-button>
    </div>

    <!-- 可滚动的内容区域 -->
    <div
      class="prescription-scroll-container"
      style="
        flex: 1;
        overflow-y: auto;
        overflow-x: auto;
        max-height: calc(100vh - 300px);
        width: 100%;
      "
    >
      <!-- 循环显示所有西药方 -->
      <div
        v-for="(prescription, pIndex) in westernPrescriptions"
        :key="prescription.id"
        style="
          margin-bottom: 20px;
          border: 1px solid #e4e7ed;
          border-radius: 8px;
          padding: 10px;
          min-width: fit-content;
        "
      >
        <!-- 西药方标题栏 -->
        <div
          class="prescription-header"
          style="
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #f5f7fa;
            padding: 10px 12px;
            border-radius: 4px;
            min-height: 40px;
            width: 100%;
            box-sizing: border-box;
            position: relative;
          "
        >
          <span
            style="font-weight: 600; font-size: 14px; color: #409eff; flex: 0 0 auto"
            >{{ prescription.name }}</span
          >
          <el-button
            type="danger"
            size="small"
            @click="handleClosePrescription(prescription.id)"
            style="flex: 0 0 auto; margin-left: 10px"
          >
            删除
          </el-button>
        </div>

        <!-- 西药方操作区 -->
        <div
          style="
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
          "
        >
          <el-button
            type="primary"
            @click="handleAddPrescription(prescription.id)"
            :disabled="false"
          >
            新增
          </el-button>
          <el-button
            type="primary"
            @click="handleSaveBatch(prescription.id)"
            :disabled="false"
          >
            保存
          </el-button>
          <el-button
            type="primary"
            @click="handleSave(prescription.id)"
            :disabled="false"
          >
            签发
          </el-button>
          <el-button
            type="warning"
            plain
            @click="handleSingOut(prescription.id)"
            :disabled="false"
          >
            撤回
          </el-button>
          <el-button
            type="primary"
            plain
            @click="proxy.$refs.orderFroupRef.handleOpen()"
            :disabled="false"
          >
            组套
          </el-button>
          <el-button
            type="primary"
            plain
            :disabled="false"
            @click="proxy.$refs.prescriptionHistoryRef.handleOpen()"
          >
            历史
          </el-button>
          <el-button
            type="default"
            @click="combination(prescription.id)"
            :disabled="false"
          >
            组合
          </el-button>
          <el-button type="default" @click="split(prescription.id)" :disabled="false">
            拆组
          </el-button>
          <el-button
            type="danger"
            plain
            @click="handleDelete(prescription.id)"
            :disabled="false"
          >
            删除
          </el-button>
          <el-button type="primary" @click="refresh(prescription.id)" :disabled="false">
            刷新
          </el-button>
          <span class="descriptions-item-label"> 诊断： </span>
          <el-select
            v-model="prescription.conditionDefinitionId"
            placeholder="诊断"
            style="width: 180px"
            @change="
              handleDiagnosisChange(prescription.conditionDefinitionId, prescription.id)
            "
          >
            <el-option
              v-for="item in diagnosisList"
              :key="item.conditionId"
              :label="item.name"
              :value="item.definitionId"
            />
          </el-select>
          <span class="descriptions-item-label"> 费用性质： </span>
          <el-select
            v-model="prescription.accountId"
            placeholder="费用性质"
            style="width: 180px"
            @change="
              (value) => {
                accountId = value;
              }
            "
          >
            <el-option
              v-for="item in contractList"
              :key="item.accountId"
              :label="item.contractName"
              :value="item.accountId"
            />
          </el-select>
          <span class="descriptions-item-label">
            合计金额：{{ getPrescriptionTotalAmount(prescription.id) }}元
          </span>
        </div>
        <el-table
          max-height="400"
          :ref="'prescriptionRef' + pIndex"
          :data="allPrescriptionsData[prescription.id] || []"
          row-key="uniqueKey"
          border
          @cell-click="
            (row, column, cell, event) =>
              clickRow(row, column, cell, event, prescription.id)
          "
          @row-dblclick="(row, event) => clickRowDb(row, event, prescription.id)"
          v-loading="loading"
          :expand-row-keys="prescription.expandOrder || []"
          style="width: 100%; min-width: 100%"
        >
          <el-table-column type="expand" width="1" style="width: 0">
            <template #default="scope">
              <el-form
                :model="scope.row"
                :rules="rowRules"
                :ref="'formRef_' + prescription.id + '_' + scope.$index"
              >
                <div
                  class="expend_div"
                  style="padding: 16px; background: #f8f9fa; border-radius: 8px"
                >
                  <template v-if="scope.row.adviceType == 1">
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        margin-bottom: 16px;
                        gap: 16px;
                      "
                    >
                      <span class="medicine-title">
                        {{
                          scope.row.adviceName +
                          " " +
                          scope.row.volume +
                          " [" +
                          Number(scope.row.unitPrice).toFixed(2) +
                          " 元" +
                          "/" +
                          scope.row.unitCode_dictText +
                          "]"
                        }}
                      </span>

                      <!-- <el-form-item prop="conditionDefinitionId">
                    <el-select
                      v-model="scope.row.conditionDefinitionId"
                      style="width: 180px; margin: 0 20px"
                      placeholder="诊断"
                    >
                      <el-option
                        v-for="item in diagnosisList"
                        :key="item.conditionId"
                        :label="item.name"
                        :value="item.definitionId"
                        @click="handleDiagnosisChange(item, scope.row)"
                      />
                    </el-select>
                  </el-form-item> -->
                      <el-form-item prop="lotNumber" label="药房：">
                        <el-select
                          v-model="scope.row.inventoryId"
                          style="width: 330px; margin-right: 20px"
                          placeholder="药房"
                        >
                          <el-option
                            v-for="item in scope.row.stockList"
                            :key="item.inventoryId"
                            :value="item.inventoryId"
                            :label="item.locationName"
                            @click="handleNumberClick(item, scope.$index, scope.row)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="执行次数："
                        prop="executeNum"
                        class="required-field"
                        data-prop="executeNum"
                        v-if="scope.row.injectFlag == 1"
                      >
                        <el-input-number
                          :min="1"
                          v-model="scope.row.executeNum"
                          controls-position="right"
                          :controls="false"
                          :ref="
                            (el) => {
                              if (!inputRefs[scope.$index]) inputRefs[scope.$index] = {};
                              inputRefs[scope.$index].executeNum = el;
                            }
                          "
                          @keyup.enter.prevent="
                            handleEnter(
                              'executeNum',
                              scope.row,
                              scope.$index,
                              prescription.id
                            )
                          "
                          style="width: 70px; margin-right: 20px"
                        />
                      </el-form-item>
                      <span class="medicine-info"> 诊断：{{ diagnosisName }} </span>
                      <el-form-item
                        label="皮试："
                        prop="skinTestFlag"
                        style="margin: 0; margin-right: 20px"
                      >
                        <el-checkbox
                          v-model="scope.row.skinTestFlag"
                          :true-value="1"
                          :false-value="0"
                        >
                          是
                        </el-checkbox>
                      </el-form-item>
                      <span class="medicine-info">
                        注射药品：{{ scope.row.injectFlag_enumText }}
                      </span>
                      <span class="total-amount">
                        总金额：{{
                          scope.row.totalPrice
                            ? Number(scope.row.totalPrice).toFixed(2) + " 元"
                            : "0.00 元"
                        }}
                      </span>
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        flex-wrap: wrap;
                      "
                    >
                      <div class="form-group">
                        <!-- 单次剂量 -->
                        <el-form-item
                          label="单次用量："
                          prop="doseQuantity"
                          class="required-field"
                          data-prop="doseQuantity"
                        >
                          <el-input-number
                            :min="0"
                            v-model="scope.row.doseQuantity"
                            controls-position="right"
                            :controls="false"
                            style="width: 70px; margin-right: 20px"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].doseQuantity = el;
                              }
                            "
                            @input="convertValues(scope.row, scope.$index)"
                            @keyup.enter.prevent="
                              handleEnter(
                                'doseQuantity',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                          />
                        </el-form-item>
                        <!-- 剂量单位 -->
                        <el-select
                          v-model="scope.row.unitCode"
                          style="width: 70px; margin-right: 20px"
                          placeholder=" "
                        >
                          <template
                            v-for="item in scope.row.unitCodeList"
                            :key="item.value"
                          >
                            <el-option
                              v-if="item.type == unitMap['minUnit']"
                              :value="item.value"
                              :label="item.label"
                            />
                          </template>
                        </el-select>
                        <span>=</span>
                        <!-- 单次剂量 -->
                        <el-form-item prop="dose" class="required-field" data-prop="dose">
                          <el-input-number
                            v-model="scope.row.dose"
                            controls-position="right"
                            :controls="false"
                            style="width: 70px; margin: 0 20px"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].dose = el;
                              }
                            "
                            @input="convertDoseValues(scope.row, scope.$index)"
                            @keyup.enter.prevent="
                              handleEnter(
                                'dose',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                          />
                        </el-form-item>
                        <!-- 全部单位 -->
                        <el-select
                          v-model="scope.row.doseUnitCode"
                          style="width: 70px"
                          placeholder=" "
                          @change="convertValues(scope.row, scope.$index)"
                        >
                          <el-option
                            v-for="item in scope.row.unitCodeList"
                            :value="item.value"
                            :label="item.label"
                            :key="item.value"
                          />
                        </el-select>
                      </div>
                      <div class="form-group">
                        <el-form-item
                          label="给药途径："
                          prop="methodCode"
                          class="required-field"
                          data-prop="methodCode"
                        >
                          <el-select
                            v-model="scope.row.methodCode"
                            placeholder="给药途径"
                            clearable
                            filterable
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].methodCode = el;
                              }
                            "
                            @keyup.enter.prevent="
                              () => {
                                inputRefs[scope.$index]?.methodCode?.blur();
                              }
                            "
                            @visible-change="
                              (value) => {
                                if (!value) {
                                  handleEnter('methodCode', scope.row, scope.$index);
                                }
                              }
                            "
                          >
                            <el-option
                              v-for="dict in method_code"
                              @click="() => (scope.row.methodCode_dictText = dict.label)"
                              @keyup="handleEnter('methodCode', scope.row, scope.$index)"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                          </el-select>
                        </el-form-item>
                        <el-form-item
                          label="用药频次："
                          prop="rateCode"
                          class="required-field"
                          data-prop="rateCode"
                        >
                          <el-select
                            v-model="scope.row.rateCode"
                            placeholder="频次"
                            style="width: 120px"
                            filterable
                            @keyup.enter.prevent="
                              () => {
                                inputRefs[scope.$index]?.rateCode?.blur();
                              }
                            "
                            @change="calculateTotalAmount(scope.row, scope.$index)"
                            @visible-change="
                              (value) => {
                                if (!value) {
                                  handleEnter('rateCode', scope.row, scope.$index);
                                }
                                // inputRefs.rateCode.blur();
                              }
                            "
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].rateCode = el;
                              }
                            "
                          >
                            <el-option
                              v-for="dict in rate_code"
                              @click="() => (scope.row.rateCode_dictText = dict.label)"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                          </el-select>
                        </el-form-item>
                        <el-form-item
                          label="备注："
                          prop="remarks"
                          style="margin: 0; margin-right: 20px"
                        >
                          <el-input
                            v-model="scope.row.remarks"
                            placeholder="请输入备注"
                            maxlength="100"
                            show-word-limit
                            style="width: 200px"
                          />
                        </el-form-item>
                      </div>
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        flex-wrap: wrap;
                        margin-top: 10px;
                      "
                    >
                      <div class="form-group">
                        <el-form-item
                          label="用药天数："
                          prop="dispensePerDuration"
                          class="required-field"
                          data-prop="dispensePerDuration"
                        >
                          <el-input-number
                            v-model="scope.row.dispensePerDuration"
                            style="width: 80px"
                            :min="1"
                            controls-position="right"
                            :controls="false"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].dispensePerDuration = el;
                              }
                            "
                            @keyup.enter.prevent="
                              handleEnter('dispensePerDuration', scope.row, scope.$index)
                            "
                            @input="calculateTotalAmount(scope.row, scope.$index)"
                          >
                            <template #suffix>天</template>
                          </el-input-number>
                        </el-form-item>

                        <el-form-item
                          label="总量："
                          prop="quantity"
                          class="required-field"
                          data-prop="quantity"
                        >
                          <el-input-number
                            v-model="scope.row.quantity"
                            style="width: 70px"
                            controls-position="right"
                            :controls="false"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].quantity = el;
                              }
                            "
                            @keyup.enter.prevent="
                              handleEnter(
                                'quantity',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                            @input="calculateTotalPrice(scope.row, scope.$index)"
                          />
                        </el-form-item>
                        <el-select
                          v-model="scope.row.unitCode"
                          style="width: 70px; margin-right: 20px"
                          placeholder=" "
                          @change="calculateTotalAmount(scope.row, scope.$index)"
                        >
                          <template
                            v-for="item in scope.row.unitCodeList"
                            :key="item.value"
                          >
                            <el-option
                              v-if="checkUnit(item, scope.row)"
                              :value="item.value"
                              :label="item.label"
                              @click="
                                () => {
                                  if (item.type == unitMap['minUnit']) {
                                    scope.row.unitPrice = scope.row.minUnitPrice;
                                  } else {
                                    scope.row.unitPrice = scope.row.unitTempPrice;
                                  }
                                  scope.row.unitCode_dictText = item.label;
                                }
                              "
                            />
                          </template>
                        </el-select>
                      </div>
                      <el-button
                        type="primary"
                        @click="handleSaveSign(scope.row, scope.$index, prescription.id)"
                      >
                        确定
                      </el-button>
                    </div>
                  </template>
                  <template v-else-if="scope.row.adviceType == 2">
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        margin-bottom: 16px;
                        gap: 16px;
                      "
                    >
                      <span class="medicine-title">
                        {{
                          scope.row.adviceName +
                          " " +
                          scope.row.volume +
                          " [" +
                          Number(scope.row.unitPrice).toFixed(2) +
                          " 元" +
                          "/" +
                          scope.row.unitCode_dictText +
                          "]"
                        }}
                      </span>

                      <!-- <el-form-item prop="conditionDefinitionId">
                    <el-select
                      v-model="scope.row.conditionDefinitionId"
                      style="width: 180px; margin: 0 20px"
                      placeholder="诊断"
                    >
                      <el-option
                        v-for="item in diagnosisList"
                        :key="item.conditionId"
                        :label="item.name"
                        :value="item.definitionId"
                        @click="handleDiagnosisChange(item, scope.row)"
                      />
                    </el-select>
                  </el-form-item> -->
                      <el-form-item prop="lotNumber" label="药房：">
                        <el-select
                          v-model="scope.row.inventoryId"
                          style="width: 400px; margin-right: 20px"
                          placeholder="药房"
                        >
                          <el-option
                            v-for="item in scope.row.stockList"
                            :key="item.inventoryId"
                            :value="item.inventoryId"
                            :label="item.locationName"
                            @click="handleNumberClick(item, scope.$index, scope.row)"
                          />
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        label="执行次数："
                        prop="executeNum"
                        class="required-field"
                        data-prop="executeNum"
                        v-if="scope.row.injectFlag == 1"
                      >
                        <el-input-number
                          :min="1"
                          v-model="scope.row.executeNum"
                          controls-position="right"
                          :controls="false"
                          :ref="
                            (el) => {
                              if (!inputRefs[scope.$index]) inputRefs[scope.$index] = {};
                              inputRefs[scope.$index].executeNum = el;
                            }
                          "
                          @keyup.enter.prevent="
                            handleEnter(
                              'executeNum',
                              scope.row,
                              scope.$index,
                              prescription.id
                            )
                          "
                          style="width: 70px; margin-right: 20px"
                        />
                      </el-form-item>
                      <span class="medicine-info"> 诊断：{{ diagnosisName }} </span>
                      <el-form-item
                        label="皮试："
                        prop="skinTestFlag"
                        style="margin: 0; margin-right: 20px"
                      >
                        <el-checkbox
                          v-model="scope.row.skinTestFlag"
                          :true-value="1"
                          :false-value="0"
                        >
                          是
                        </el-checkbox>
                      </el-form-item>
                      <span class="medicine-info">
                        注射药品：{{ scope.row.injectFlag_enumText }}
                      </span>
                      <span class="total-amount">
                        总金额：{{
                          scope.row.totalPrice ? scope.row.totalPrice + " 元" : "0.00 元"
                        }}
                      </span>
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        flex-wrap: wrap;
                      "
                    >
                      <div class="form-group">
                        <!-- 单次剂量 -->
                        <el-form-item
                          label="单次用量："
                          prop="doseQuantity"
                          class="required-field"
                          data-prop="doseQuantity"
                        >
                          <el-input-number
                            :min="0"
                            v-model="scope.row.doseQuantity"
                            controls-position="right"
                            :controls="false"
                            style="width: 70px; margin-right: 20px"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].doseQuantity = el;
                              }
                            "
                            @input="convertValues(scope.row, scope.$index)"
                            @keyup.enter.prevent="
                              handleEnter(
                                'doseQuantity',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                          />
                        </el-form-item>
                        <!-- 剂量单位 -->
                        <el-select
                          v-model="scope.row.unitCode"
                          style="width: 70px; margin-right: 20px"
                          placeholder=" "
                        >
                          <template
                            v-for="item in scope.row.unitCodeList"
                            :key="item.value"
                          >
                            <el-option
                              v-if="
                                scope.row.unitCodeList.length == 3
                                  ? item.type == unitMap['minUnit']
                                  : item.type == unitMap['unit']
                              "
                              :value="item.value"
                              :label="item.label"
                            />
                          </template>
                        </el-select>
                        <span>=</span>
                        <!-- 单次剂量 -->
                        <el-form-item prop="dose" class="required-field" data-prop="dose">
                          <el-input-number
                            v-model="scope.row.dose"
                            controls-position="right"
                            :controls="false"
                            style="width: 70px; margin: 0 20px"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].dose = el;
                              }
                            "
                            @input="convertDoseValues(scope.row, scope.$index)"
                            @keyup.enter.prevent="
                              handleEnter(
                                'dose',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                          />
                        </el-form-item>
                        <!-- 全部单位 -->
                        <el-select
                          v-model="scope.row.doseUnitCode"
                          style="width: 70px"
                          placeholder=" "
                          @change="convertValues(scope.row, scope.$index)"
                        >
                          <el-option
                            v-for="item in scope.row.unitCodeList"
                            :value="item.value"
                            :label="item.label"
                            :key="item.value"
                          />
                        </el-select>
                      </div>
                      <div class="form-group">
                        <el-form-item
                          label="给药途径："
                          prop="methodCode"
                          class="required-field"
                          data-prop="methodCode"
                        >
                          <el-select
                            v-model="scope.row.methodCode"
                            placeholder="给药途径"
                            clearable
                            filterable
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].methodCode = el;
                              }
                            "
                            @keyup.enter.prevent="
                              () => {
                                inputRefs[scope.$index]?.methodCode?.blur();
                              }
                            "
                            @visible-change="
                              (value) => {
                                if (!value) {
                                  handleEnter('methodCode', scope.row, scope.$index);
                                }
                              }
                            "
                          >
                            <el-option
                              v-for="dict in method_code"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                          </el-select>
                        </el-form-item>
                        <el-form-item
                          label="用药频次："
                          prop="rateCode"
                          class="required-field"
                          data-prop="rateCode"
                        >
                          <el-select
                            v-model="scope.row.rateCode"
                            placeholder="频次"
                            style="width: 120px"
                            filterable
                            @keyup.enter.prevent="
                              () => {
                                inputRefs[scope.$index]?.rateCode?.blur();
                              }
                            "
                            @change="calculateTotalAmount(scope.row, scope.$index)"
                            @visible-change="
                              (value) => {
                                if (!value) {
                                  handleEnter('rateCode', scope.row, scope.$index);
                                }
                              }
                            "
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].rateCode = el;
                              }
                            "
                          >
                            <el-option
                              v-for="dict in rate_code"
                              :key="dict.value"
                              :label="dict.label"
                              :value="dict.value"
                            />
                          </el-select>
                        </el-form-item>
                        <el-form-item
                          label="备注："
                          prop="remarks"
                          style="margin: 0; margin-right: 20px"
                        >
                          <el-input
                            v-model="scope.row.remarks"
                            placeholder="请输入备注"
                            maxlength="100"
                            show-word-limit
                            style="width: 200px"
                          />
                        </el-form-item>
                      </div>
                    </div>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        gap: 12px;
                        flex-wrap: wrap;
                        margin-top: 10px;
                      "
                    >
                      <div class="form-group">
                        <el-form-item
                          label="用药天数："
                          prop="dispensePerDuration"
                          class="required-field"
                          data-prop="dispensePerDuration"
                        >
                          <el-input-number
                            v-model="scope.row.dispensePerDuration"
                            style="width: 80px"
                            :min="1"
                            controls-position="right"
                            :controls="false"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].dispensePerDuration = el;
                              }
                            "
                            @keyup.enter.prevent="
                              handleEnter('dispensePerDuration', scope.row, scope.$index)
                            "
                            @input="calculateTotalAmount(scope.row, scope.$index)"
                          >
                            <template #suffix>天</template>
                          </el-input-number>
                        </el-form-item>

                        <el-form-item
                          label="总量："
                          prop="quantity"
                          class="required-field"
                          data-prop="quantity"
                        >
                          <el-input-number
                            v-model="scope.row.quantity"
                            style="width: 70px"
                            controls-position="right"
                            :controls="false"
                            :ref="
                              (el) => {
                                if (!inputRefs[scope.$index])
                                  inputRefs[scope.$index] = {};
                                inputRefs[scope.$index].quantity = el;
                              }
                            "
                            @keyup.enter.prevent="
                              handleEnter(
                                'quantity',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                            @input="calculateTotalPrice(scope.row, scope.$index)"
                          />
                        </el-form-item>
                        <el-select
                          v-model="scope.row.unitCode"
                          style="width: 70px; margin-right: 20px"
                          placeholder=" "
                          @change="calculateTotalAmount(scope.row, scope.$index)"
                        >
                          <template
                            v-for="item in scope.row.unitCodeList"
                            :key="item.value"
                          >
                            <el-option
                              v-if="item.type != unitMap['dose']"
                              :value="item.value"
                              :label="item.label"
                              @click="
                                () => {
                                  if (item.type == unitMap['minUnit']) {
                                    scope.row.unitPrice = scope.row.minUnitPrice;
                                  } else {
                                    scope.row.unitPrice = scope.row.unitTempPrice;
                                  }
                                  scope.row.unitCode_dictText = item.label;
                                }
                              "
                            />
                          </template>
                        </el-select>
                      </div>
                      <el-button
                        type="primary"
                        @click="handleSaveSign(scope.row, scope.$index, prescription.id)"
                      >
                        确定
                      </el-button>
                    </div>
                  </template>
                  <template v-else>
                    <div
                      style="
                        display: flex;
                        align-items: center;
                        margin-bottom: 16px;
                        gap: 16px;
                      "
                    >
                      <span style="font-size: 16px; font-weight: 600">
                        {{ scope.row.adviceName }}
                        {{
                          scope.row.unitPrice
                            ? Number(scope.row.unitPrice).toFixed(2) + "/次"
                            : "-" + "元"
                        }}
                      </span>
                      <div class="form-group">
                        <el-form-item
                          label="执行次数："
                          prop="quantity"
                          class="required-field"
                          data-prop="quantity"
                        >
                          <el-input-number
                            placeholder="执行次数"
                            style="width: 100px; margin: 0 20px"
                            v-model="scope.row.quantity"
                            controls-position="right"
                            :controls="false"
                            @keyup.enter.prevent="
                              handleEnter(
                                'quantity',
                                scope.row,
                                scope.$index,
                                prescription.id
                              )
                            "
                            @input="calculateTotalPrice(scope.row, scope.$index)"
                          />
                        </el-form-item>
                        <el-form-item
                          label="执行科室："
                          prop="orgId"
                          class="required-field"
                          data-prop="orgId"
                        >
                          <el-tree-select
                            clearable
                            v-model="scope.row.orgId"
                            style="width: 200px"
                            :data="organization"
                            :props="{ value: 'id', label: 'name', children: 'children' }"
                            value-key="id"
                            check-strictly
                            default-expand-all
                            @change="
                              (value) => handleOrgChange(value, scope.$index, scope.row)
                            "
                            placeholder="请选择执行科室"
                          />
                        </el-form-item>
                        <el-form-item
                          label="备注："
                          prop="remarks"
                          style="margin: 0; margin-right: 20px"
                        >
                          <el-input
                            v-model="scope.row.remarks"
                            placeholder="请输入备注"
                            maxlength="100"
                            show-word-limit
                            style="width: 200px"
                          />
                        </el-form-item>
                        <span class="total-amount">
                          总金额：
                          {{
                            scope.row.totalPrice
                              ? Number(scope.row.totalPrice).toFixed(2) + " 元"
                              : "0.00 元"
                          }}
                        </span>
                        <span style="font-size: 16px; font-weight: 600">
                          <!-- 金额: {{ scope.row.priceList[0].price }} -->
                        </span>
                      </div>
                      <el-button
                        type="primary"
                        @click="handleSaveSign(scope.row, scope.$index, prescription.id)"
                      >
                        确定
                      </el-button>
                    </div>
                  </template>
                </div>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column label="" align="center" prop="groupId" width="60">
            <template #header>
              <el-checkbox
                :model-value="getCheckAllState(prescription.id)"
                @change="
                  (value) => {
                    handleCheckAllChange(value, prescription.id);
                  }
                "
              />
            </template>
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.check"
                @dblclick.stop=""
                placeholder=""
                @change="
                  (value) =>
                    handleCheckBoxChange(value, scope.$index, scope.row, prescription.id)
                "
              />
            </template>
          </el-table-column>
          <el-table-column label="组" align="center" width="60">
            <template #default="scope">
              <div v-if="groupMarkers[scope.$index] === '┏'">┏</div>
              <div v-if="groupMarkers[scope.$index] === '┗'">┗</div>
              <div v-if="groupMarkers[scope.$index] === '┃'">┃</div>
              <!-- <div v-if="groupMarkers[scope.$index] === 'all'">┏</div> -->
              <!-- <div v-if="groupMarkers[scope.$index] === 'all'">┗</div> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="序号" align="center" width="60" prop="sortNumber"> </el-table-column> -->
          <!-- 医嘱类型列 -->
          <el-table-column label="医嘱类型" align="center" width="120">
            <template #default="scope">
              <template v-if="scope.row.isEdit">
                <el-select
                  v-model="scope.row.adviceType"
                  :ref="'adviceTypeRef_' + prescription.id + '_' + scope.$index"
                  placeholder="请选择"
                  style="width: 100%"
                  @change="handleAdviceTypeChange(scope.row, scope.$index)"
                >
                  <!-- 直接使用drord_doctor_type字典，已包含拆分后的西药(1)和中成药(2) -->
                  <el-option
                    v-for="dict in getSortedAdviceTypeList()"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
              <!-- 非编辑模式下，使用getAdviceTypeText函数确保显示正确的文本 -->
              <span v-else>{{ getAdviceTypeText(scope.row.adviceType) }}</span>
            </template>
          </el-table-column>
          <!-- 项目列 -->
          <el-table-column label="项目" align="center" prop="productName" width="280">
            <template #default="scope">
              <template v-if="getRowDisabled(scope.row)">
                <el-popover
                  :popper-style="{ padding: '0' }"
                  placement="bottom-start"
                  :visible="scope.row.showPopover"
                  :width="1200"
                >
                  <adviceBaseList
                    ref="adviceTableRef"
                    :popoverVisible="scope.row.showPopover"
                    :adviceQueryParams="adviceQueryParams"
                    :patientInfo="props.patientInfo"
                    @selectAdviceBase="
                      (row) => {
                        selectAdviceBase(scope.row.uniqueKey, row);
                      }
                    "
                  />
                  <template #reference>
                    <el-input
                      :ref="'adviceRef_' + prescription.id + '_' + scope.$index"
                      v-model="scope.row.adviceName"
                      placeholder="请选择项目"
                      @input="handleChange"
                      @click="handleFocus(scope.row, scope.$index)"
                      @blur="handleBlur(scope.row)"
                      @keyup.enter.stop="handleFocus(scope.row, scope.$index)"
                      @keydown="handleInputKeyDown(scope.row, $event)"
                      style="width: 100%"
                    />
                  </template>
                </el-popover>
              </template>
              <span v-else>{{ scope.row.adviceName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="" width="90">
            <template #default="scope">
              <el-tag v-if="scope.row.chargeStatus == 5" type="info">
                {{ scope.row.chargeStatus_enumText }}
              </el-tag>
              <el-tag v-else-if="scope.row.statusEnum == 2" type="success">已签发</el-tag>
              <el-tag
                v-else-if="!scope.row.requestId && scope.row.statusEnum == 1"
                type="warning"
              >
                待保存
              </el-tag>
              <el-tag
                v-else-if="
                  scope.row.statusEnum == 1 && scope.row.requestId && !scope.row.isSaved
                "
                type="warning"
              >
                待保存
              </el-tag>
              <el-tag
                v-else-if="scope.row.statusEnum == 1 && scope.row.isSaved"
                type="primary"
                >待签发</el-tag
              >
              <el-tag v-else type="info">{{ scope.row.chargeStatus_enumText }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="单次剂量" align="center" prop="">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{
                  scope.row.dose
                    ? scope.row.dose + " " + scope.row.doseUnitCode_dictText
                    : ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="总量" align="center" prop="">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{
                  scope.row.quantity
                    ? scope.row.quantity + " " + scope.row.unitCode_dictText
                    : ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="总金额"
            align="right"
            prop=""
            header-align="center"
            width="100"
          >
            <template #default="scope">
              <span v-if="!scope.row.isEdit" style="text-align: right">
                {{
                  scope.row.totalPrice
                    ? Number(scope.row.totalPrice).toFixed(2) + " 元"
                    : "-"
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="药房/科室" align="center" prop="" width="200">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{ scope.row.positionName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="频次/用法" align="center" prop="" width="180">
            <template #default="scope">
              <span
                v-if="!scope.row.isEdit && scope.row.adviceType == 1"
                style="text-align: right"
              >
                {{
                  scope.row.rateCode_dictText
                    ? scope.row.rateCode_dictText +
                      " " +
                      scope.row.dispensePerDuration +
                      "天" +
                      " " +
                      scope.row.methodCode_dictText
                    : ""
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="注射药品" align="center" prop="" width="80">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{ scope.row.injectFlag_enumText || "-" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="皮试" align="center" prop="" width="80">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{ scope.row.skinTestFlag_enumText || "-" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remarks" width="150">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{ scope.row.remarks || "-" }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="诊断" align="center" prop="diagnosisName" width="150">
            <template #default="scope">
              <span v-if="!scope.row.isEdit">
                {{ scope.row.diagnosisName || scope.row.conditionDefinitionName }}
              </span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" align="center" width="100" fixed="right">
        <template #default="scope">
          <el-icon @click="up(scope.row)"><Upload /></el-icon>
          <el-icon @click="down(scope.row)"><Download /></el-icon>
        </template>
      </el-table-column> -->
        </el-table>
      </div>
      <!-- End of v-for loop -->
    </div>
    <!-- End of scrollable content area -->

    <OrderGroupDrawer
      ref="orderFroupRef"
      :diagnosis="diagnosisInfo"
      :organizationId="props.patientInfo.orgId"
      @useOrderGroup="handleSaveGroup"
    />
    <PrescriptionHistory
      ref="prescriptionHistoryRef"
      :diagnosis="diagnosisInfo"
      :patientInfo="props.patientInfo"
      @userPrescriptionHistory="handleSaveHistory"
    />
    <OrderBindInfo ref="orderBindInfoRef" @submit="handleOrderBindInfo" />
  </div>
  <!-- 打印机选择对话框 -->
  <!-- <el-dialog
    v-model="isPrinterDialogVisible"
    title="选择打印机"
    width="400px"
    :before-close="cancelPrinter"
  >
    <div class="printer-dialog-content">
      <el-form label-position="top">
        <el-form-item label="可用打印机">
          <el-select v-model="selectedPrinter" placeholder="请选择打印机" style="width: 100%">
            <el-option
              v-for="printer in printerList"
              :key="printer.name"
              :label="printer.name"
              :value="printer.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelPrinter">取消</el-button>
        <el-button type="primary" @click="confirmPrinter">确定</el-button>
      </span>
    </template>
  </el-dialog> -->
</template>

<script setup>
import {
  getDiagnosisDefinitionList,
  savePrescription,
  getEncounterDiagnosis,
  getPrescriptionList,
  getOrgTree,
  savePrescriptionSign,
  singOut,
  saveEmr,
  getEmrDetail,
  updateGroupId,
  getContract,
  getAdviceBaseInfo,
  getBindDevice,
} from '../api';
import adviceBaseList from '../adviceBaseList.vue';
import { computed, getCurrentInstance, nextTick, watch, unref, reactive } from 'vue';
import { calculateQuantityByDays, formatNumber } from '@/utils/his';
import OrderGroupDrawer from './orderGroupDrawer';
import PrescriptionHistory from './prescriptionHistory';
import OrderBindInfo from './orderBindInfo';
import Decimal from 'decimal.js';
import useUserStore from '@/store/modules/user';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import { advicePrint } from '@/api/public';
// import printUtils, {
//   PRINT_TEMPLATE,
//   getPrinterList,
//   getCachedPrinter,
//   savePrinterToCache,
// } from '@/utils/printUtils';

const emit = defineEmits(['selectDiagnosis']);
const total = ref(0);
const queryParams = ref({});
const prescriptionList = ref([]);
const form = ref({
  prescriptionList: prescriptionList.value,
});
const adviceQueryParams = ref({
  searchKey: '',
  adviceType: '',
  categoryCode: '' // 用于筛选西药(2)和中成药(1)
});
const rowIndex = ref(-1);
const groupIndex = ref(1);
const diagnosisList = ref([]);
const nextId = ref(1);
const unitCodeList = ref([]);
const adviceTableRef = ref([]);
const organization = ref([]);
const conditionDefinitionId = ref('');
const encounterDiagnosisId = ref('');
const diagnosisName = ref('');
const diagnosisInfo = ref({});
const loading = ref(false);
const userStore = useUserStore();
const rowRules = ref({
  conditionDefinitionId: [{ required: true, message: '请选择诊断', trigger: 'change' }],
  dose: [{ required: true, message: '请输入单次剂量', trigger: 'change' }],
  doseQuantity: [{ required: true, message: '请输入单次剂量', trigger: 'change' }],
  quantity: [{ required: true, message: '请输入数量', trigger: 'change' }],
  dispensePerDuration: [{ required: true, message: '请输入用药天数', trigger: 'change' }],
  executeNum: [{ required: true, message: '请输入执行次数', trigger: 'change' }],
  rateCode: [{ required: true, message: '请选择频次', trigger: 'change' }],
  methodCode: [{ required: true, message: '请选择给药途径', trigger: 'change' }],
  orgId: [{ required: true, message: '请选择执行科室', trigger: 'change' }],
});
const unitMap = ref({
  dose: 'dose',
  minUnit: 'minUnit',
  unit: 'unit',
});
const buttonDisabled = computed(() => {
  return !props.patientInfo;
});
const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
  },
  activeTab: {
    type: String,
  },
});
const isAdding = ref(false);
const isSaving = ref(false);
const prescriptionRef = ref();
const expandOrder = ref([]); //目前的展开行
const stockList = ref([]);
const contractList = ref([]);
const conditionId = ref('');
const accountId = ref('');
const checkAll = ref(false);
const bindMethod = ref({});
const { proxy } = getCurrentInstance();
const inputRefs = ref({}); // 存储输入框实例，格式: { rowIndex: { fieldName: el } }
const requiredProps = ref([]); // 存储必填项 prop 顺序
const totalAmount = ref(0);
const groupMarkers = ref([]); // 存储分组标记，用于显示层级关系
const { method_code, unit_code, rate_code, distribution_category_code, drord_doctor_type } = proxy.useDict(
  'method_code',
  'unit_code',
  'rate_code',
  'distribution_category_code',
  'drord_doctor_type'
);

// 删除硬编码的adviceTypeList，直接使用drord_doctor_type字典
const adviceTypeList = ref([
  {
    label: '西药',
    value: 1,
  },
  {
    label: '中成药',
    value: 2,
  },

  {
    label: '耗材',
    value: 3,
  },
  {
    label: '诊疗',
    value: 4,
  },
  {
    label: '全部',
    value: '',
  },
]);

// 西药处方管理相关变量
const westernPrescriptions = ref([]); // 西药处方列表
const currentPrescriptionId = ref(null); // 当前活跃的处方ID
const prescriptionCounter = ref(0); // 处方计数器
const allPrescriptionsData = ref({}); // 存储所有处方的数据，格式: { prescriptionId: [...prescriptionList] }
const allPrescriptionCheckStates = ref({}); // 存储每个处方的选中状态，格式: { prescriptionId: { checkedIndexes: [], checkAll: false } }
onMounted(() => {
  document.addEventListener('keydown', escKeyListener);
  // 初始化时自动创建第一个西药处方
  if (westernPrescriptions.value.length === 0) {
    handleAddWesternPrescription();
  }
});

onBeforeUnmount(() => {
  document.removeEventListener('keydown', escKeyListener);
});
watch(
  () => expandOrder.value,
  (newValue) => {
    if (newValue.length > 0) {
      // 使用 setTimeout 延迟执行，等待表格展开动画完成和表单渲染
      setTimeout(() => {
        // 需要查找所有处方中的索引，因为 expandOrder 可能来自任何一个处方
        let foundIndex = -1;
        let foundPrescriptionId = null;

        // 遍历所有处方找到对应的行
        for (const prescription of westernPrescriptions.value) {
          const prescriptionData = allPrescriptionsData.value[prescription.id] || [];
          const index = prescriptionData.findIndex((row) => row.uniqueKey === newValue[0]);
          if (index !== -1) {
            foundIndex = index;
            foundPrescriptionId = prescription.id;
            break;
          }
        }

        if (foundIndex === -1) {
          console.warn('找不到对应的行数据, uniqueKey:', newValue[0]);
          requiredProps.value = [];
          return;
        }

        const formRefName = 'formRef_' + foundPrescriptionId + '_' + foundIndex;
        let formRef = proxy.$refs[formRefName];

        // 如果 formRef 是数组，取第一个元素
        if (Array.isArray(formRef)) {
          formRef = formRef[0];
        }

        console.log('查找表单引用:', formRefName, '是否找到:', !!formRef);

        if (formRef && formRef.$el) {
          const items = formRef.$el.querySelectorAll('[data-prop]');
          requiredProps.value = Array.from(items).map((item) => item.dataset.prop);
          console.log(requiredProps.value, 'requiredProps.value');
        } else {
          // 表单可能还在渲染中，这是正常的，不输出错误
          console.log('表单正在渲染中，等待下次更新...');
          requiredProps.value = [];
        }
      }, 100); // 延迟 100ms，等待表格展开动画完成
    } else {
      requiredProps.value = {};
    }
  }
);
watch(
  () => prescriptionList.value,
  (newVlaue) => {
    if (newVlaue && newVlaue.length > 0) {
      handleTotalAmount();
    }
  },
  { immediate: true }
);
// 获取排序后的医嘱类型列表（drord_doctor_type字典已包含拆分后的西药1和中成药2）
function getSortedAdviceTypeList() {
  if (!drord_doctor_type.value || !Array.isArray(drord_doctor_type.value)) {
    return [];
  }

  // 按照字典排序显示（优先使用dictSort，如果没有则使用value排序）
  // 同时确保value是数字类型，与adviceType匹配
  return [...drord_doctor_type.value].sort((a, b) => {
    // 优先使用dictSort排序
    if (a.dictSort !== undefined && b.dictSort !== undefined) {
      return (a.dictSort || 0) - (b.dictSort || 0);
    }
    // 如果没有dictSort，使用value排序
    const valueA = Number(a.value) || 0;
    const valueB = Number(b.value) || 0;
    return valueA - valueB;
  }).map(item => ({
    ...item,
    value: Number(item.value) // 确保value是数字类型，与adviceType匹配
  }));
}

// 获取医嘱类别显示文本
function getAdviceTypeText(adviceType) {
  // 如果adviceType为空或未定义，返回空字符串
  if (adviceType === undefined || adviceType === null || adviceType === '') {
    return '';
  }

  // 使用drord_doctor_type字典（已包含西药1、中成药2、诊疗3、耗材4、全部5）
  if (drord_doctor_type.value && Array.isArray(drord_doctor_type.value) && drord_doctor_type.value.length > 0) {
    // 转换为数字进行比较
    const adviceTypeNum = Number(adviceType);

    // 尝试匹配字典项
    let dictItem = drord_doctor_type.value.find(item => {
      // 先尝试数字匹配
      const itemValue = Number(item.value);
      if (!isNaN(itemValue) && itemValue === adviceTypeNum) {
        return true;
      }
      // 再尝试字符串匹配
      return String(item.value) === String(adviceType);
    });

    // 如果找到匹配项，返回标签
    if (dictItem && dictItem.label) {
      return dictItem.label;
    }
  }

  // 如果字典未加载或未找到匹配项，返回空字符串
  // 注意：这里不返回数字，避免显示数字
  return '';
}

// 处理医嘱类型变化
function handleAdviceTypeChange(row, index) {
  // 根据选择的医嘱类型设置categoryCode筛选条件
  // drord_doctor_type: 1=西药, 2=中成药, 3=诊疗, 4=耗材, 5=全部
  if (row.adviceType == 1) {
    // 西药：categoryCode = 2
    adviceQueryParams.value.categoryCode = '2';
    adviceQueryParams.value.adviceType = 1; // 药品类型
  } else if (row.adviceType == 2) {
    // 中成药：categoryCode = 1
    adviceQueryParams.value.categoryCode = '1';
    adviceQueryParams.value.adviceType = 1; // 药品类型
  } else if (row.adviceType == 3) {
    // 诊疗：adviceType = 3
    adviceQueryParams.value.categoryCode = '';
    adviceQueryParams.value.adviceType = 3; // 诊疗类型
  } else if (row.adviceType == 4) {
    // 耗材：adviceType = 2（后端接口中耗材的adviceType是2）
    adviceQueryParams.value.categoryCode = '';
    adviceQueryParams.value.adviceType = 2; // 耗材类型
  } else {
    // 全部(5)或其他：清除筛选
    adviceQueryParams.value.categoryCode = '';
    adviceQueryParams.value.adviceType = '';
  }
}
function handleTotalAmount() {
  totalAmount.value = prescriptionList.value.reduce((accumulator, currentRow) => {
    if (currentRow.chargeStatus != 8) {
      return new Decimal(accumulator).add(currentRow.totalPrice || 0);
    } else {
      // 跳过已退费项目，保持累加结果不变
      return accumulator;
    }
  }, new Decimal(0));
}
getList();
function getList() {
  getDiagnosisDefinitionList(queryParams.value).then((res) => {
    total.value = res.data.total;
  });
}
function refresh(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  getListInfo(false);
}
function getListInfo(addNewRow) {
  isAdding.value = false;
  getPrescriptionList(props.patientInfo.encounterId).then((res) => {
    // 调试日志：显示后端返回的原始数据
    console.log('[getListInfo] 后端返回的原始数据:', res.data.map(item => ({
      adviceName: JSON.parse(item.contentJson)?.adviceName,
      requestId: item.requestId,
      statusEnum: item.statusEnum,
      contentJson_isSaved: JSON.parse(item.contentJson)?.isSaved
    })));
    prescriptionList.value = res.data.map((item) => {
      const parsedContent = JSON.parse(item.contentJson);
      // 确保 skinTestFlag 是数字类型（1 或 0）
      const skinTestFlag = parsedContent?.skinTestFlag !== undefined && parsedContent?.skinTestFlag !== null
        ? (typeof parsedContent.skinTestFlag === 'number' ? parsedContent.skinTestFlag : (parsedContent.skinTestFlag ? 1 : 0))
        : (item.skinTestFlag !== undefined && item.skinTestFlag !== null
          ? (typeof item.skinTestFlag === 'number' ? item.skinTestFlag : (item.skinTestFlag ? 1 : 0))
          : 0);
      // 从后端获取数据时，将后端的耗材类型（2）转换为前端显示的耗材类型（4）
      // 后端接口中：1=药品, 2=耗材, 3=诊疗
      // 前端显示中：1=西药, 2=中成药, 3=诊疗, 4=耗材
      let displayAdviceType = parsedContent.adviceType !== undefined ? Number(parsedContent.adviceType) : (item.adviceType !== undefined ? Number(item.adviceType) : undefined);
      if (displayAdviceType === 2 && (parsedContent.deviceId || parsedContent.deviceName || item.deviceId || item.deviceName)) {
        // 如果是耗材（adviceType=2 且有deviceId或deviceName），转换为前端显示的4
        displayAdviceType = 4;
      }
      // 确保adviceName优先从parsedContent中获取，避免被item中的空值覆盖
      // 对于中成药类型，特别确保adviceName正确设置
      const adviceName = parsedContent?.adviceName || item?.adviceName || '';

      // 根据后端返回的状态设置 isSaved 标识
      // statusEnum == 1 且有 requestId 且后端有 isSaved 字段，则使用后端的值
      // 否则默认为 false（待保存）
      const isSaved = item.statusEnum === 1 && item.requestId
        ? (parsedContent?.isSaved !== undefined ? parsedContent.isSaved : false)
        : (item.statusEnum === 2 ? true : false);

      return {
        ...item,
        ...parsedContent,
        // 确保 adviceType 是数字类型，以便正确显示文本
        adviceType: displayAdviceType,
        doseQuantity: parsedContent?.doseQuantity,
        doseUnitCode_dictText: parsedContent?.doseUnitCode_dictText,
        skinTestFlag: skinTestFlag, // 确保皮试字段是数字类型
        skinTestFlag_enumText: skinTestFlag == 1 ? '是' : '否', // 更新显示文本
        adviceName: parsedContent?.adviceName || item.adviceName,
        rateCode_dictText: parsedContent?.rateCode_dictText || item.rateCode_dictText,
        methodCode_dictText: parsedContent?.methodCode_dictText || item.methodCode_dictText,
        dispensePerDuration: parsedContent?.dispensePerDuration || item.dispensePerDuration,
        adviceName: adviceName, // 确保 adviceName 正确设置
        isSaved: isSaved, // 设置 isSaved 标识
        statusEnum: item.statusEnum, // 关键修复：确保使用后端返回的 statusEnum，不被 parsedContent 覆盖
        requestId: item.requestId, // 确保 requestId 不被覆盖
      };
    });

    // 调试日志：显示所有医嘱的状态
    console.log('[getListInfo] 刷新后的医嘱列表:', prescriptionList.value.map(item => ({
      adviceName: item.adviceName,
      requestId: item.requestId,
      statusEnum: item.statusEnum,
      isSaved: item.isSaved,
      显示状态: item.statusEnum === 2 ? '已签发' : (item.statusEnum === 1 && item.isSaved ? '待签发' : '待保存')
    })));

    groupMarkers.value = getGroupMarkers(prescriptionList.value); // 更新标记

    // 按处方ID分组数据
    const prescriptionGroups = {};
    const prescriptionInfoMap = {}; // 存储处方信息（处方号等）

    prescriptionList.value.forEach(item => {
      const prescriptionId = item.prescriptionId || 'default';
      if (!prescriptionGroups[prescriptionId]) {
        prescriptionGroups[prescriptionId] = [];
      }
      prescriptionGroups[prescriptionId].push(item);

      // 记录处方号
      if (item.prescriptionNo && !prescriptionInfoMap[prescriptionId]) {
        prescriptionInfoMap[prescriptionId] = {
          prescriptionNo: item.prescriptionNo
        };
      }
    });

    // 更新 allPrescriptionsData
    allPrescriptionsData.value = prescriptionGroups;

    // 更新西药处方列表 - 保持原有顺序，只更新数据
    const existingPrescriptionIds = Object.keys(prescriptionGroups);
    if (existingPrescriptionIds.length > 0 && existingPrescriptionIds[0] !== 'default') {
      // 保存当前处方的ID，用于后续恢复
      const savedCurrentPrescriptionId = currentPrescriptionId.value;

      // 遍历前端已有的处方列表，保持原有顺序，只更新数据
      const updatedPrescriptions = [];
      const processedBackendIds = new Set(); // 记录已处理的后端ID

      // 1. 首先处理前端已有的处方（保持原有顺序）
      westernPrescriptions.value.forEach((prescription, index) => {
        const info = prescriptionInfoMap[prescription.id] || {};

        // 检查这个前端处方是否有对应的后端数据
        if (existingPrescriptionIds.includes(prescription.id)) {
          // 如果后端有这个ID的数据，说明处方已保存，更新数据但保持顺序和名称
          processedBackendIds.add(prescription.id);
          updatedPrescriptions.push({
            ...prescription,
            prescriptionNo: info.prescriptionNo || prescription.prescriptionNo || '',
            // 保持原有名称，不要改变
            name: prescription.name || `西药方${index + 1}`
          });
        } else {
          // 如果后端没有这个ID的数据，可能是前端创建的临时处方，保持原样
          updatedPrescriptions.push(prescription);
        }
      });

      // 2. 处理后端有但前端没有的处方（可能是新保存的处方，需要映射到前端）
      existingPrescriptionIds.forEach((prescriptionId) => {
        if (!processedBackendIds.has(prescriptionId)) {
          const info = prescriptionInfoMap[prescriptionId] || {};
          // 这是新保存的处方，查找是否有对应的前端临时处方
          // 通过查找最近保存的数据来确定
          const prescriptionData = prescriptionGroups[prescriptionId] || [];
          if (prescriptionData.length > 0) {
            // 尝试找到对应的前端处方（通过数据匹配）
            // 如果找不到，就在末尾添加
            const newPrescription = {
              id: prescriptionId,
              name: `西药方${updatedPrescriptions.length + 1}`,
              prescriptionNo: info.prescriptionNo || '',
              conditionDefinitionId: conditionDefinitionId.value,
              accountId: accountId.value,
              expandOrder: []
            };
            updatedPrescriptions.push(newPrescription);
          }
        }
      });

      // 3. 更新处方列表，保持原有顺序
      westernPrescriptions.value = updatedPrescriptions;

      // 4. 恢复当前活跃处方
      if (savedCurrentPrescriptionId && existingPrescriptionIds.includes(savedCurrentPrescriptionId)) {
        currentPrescriptionId.value = savedCurrentPrescriptionId;
      } else if (updatedPrescriptions.length > 0) {
        // 如果当前处方不存在，选择第一个已保存的处方
        const firstSavedPrescription = updatedPrescriptions.find(p => existingPrescriptionIds.includes(p.id));
        if (firstSavedPrescription) {
          currentPrescriptionId.value = firstSavedPrescription.id;
        } else {
          currentPrescriptionId.value = updatedPrescriptions[0].id;
        }
      }

      // 5. 加载当前处方的数据
      prescriptionList.value = [...(allPrescriptionsData.value[currentPrescriptionId.value] || [])];

      // 6. 更新处方计数器
      prescriptionCounter.value = Math.max(prescriptionCounter.value, westernPrescriptions.value.length);
    }

    if (props.activeTab == 'prescription' && addNewRow) {
      handleAddPrescription();
    }
  });
  getContract({ encounterId: props.patientInfo.encounterId }).then((res) => {
    contractList.value = res.data;
  });
  accountId.value = props.patientInfo.accountId;
}

function getDiagnosisInfo() {
  if (!props.patientInfo || !props.patientInfo.encounterId) {
    console.warn('患者信息不完整，无法获取诊断信息');
    return Promise.resolve({ data: [] });
  }

  return getEncounterDiagnosis(props.patientInfo.encounterId).then((res) => {
    console.log('getDiagnosisInfo - API返回结果:', res);
    const diagnosisData = res.data || res || [];
    diagnosisList.value = Array.isArray(diagnosisData) ? diagnosisData : [];
    console.log('getDiagnosisInfo - 诊断列表已更新:', diagnosisList.value);

    let diagnosisInfo = diagnosisList.value.filter((item) => {
      return item.maindiseFlag == 1;
    });
    if (diagnosisInfo.length > 0) {
      diagnosisInfo.value = diagnosisInfo[0];
      conditionDefinitionId.value = diagnosisInfo[0].definitionId;
      conditionId.value = diagnosisInfo[0].conditionId;
      encounterDiagnosisId.value = diagnosisInfo[0].encounterDiagnosisId;
      diagnosisName.value = diagnosisInfo[0].name;
      console.log('getDiagnosisInfo - 已设置主诊断:', diagnosisInfo[0]);
    } else if (diagnosisList.value.length > 0) {
      // 如果没有主诊断，使用第一个诊断
      conditionDefinitionId.value = diagnosisList.value[0].definitionId;
      conditionId.value = diagnosisList.value[0].conditionId;
      encounterDiagnosisId.value = diagnosisList.value[0].encounterDiagnosisId;
      diagnosisName.value = diagnosisList.value[0].name;
      console.log('getDiagnosisInfo - 已设置第一个诊断:', diagnosisList.value[0]);
    }
    return res;
  }).catch((error) => {
    console.error('获取诊断信息失败:', error);
    diagnosisList.value = [];
    return { data: [] };
  });
}

function getRowDisabled(row) {
  return row.isEdit;
}

// 新增医嘱
function handleAddPrescription(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  if (diagnosisList.value.length == 0) {
    proxy.$modal.msgWarning('请先保存诊断后再开立医嘱');
    return;
  }
  if (isAdding.value) {
    proxy.$modal.msgWarning('请先保存当前医嘱');
    return;
  }

  // 检查当前处方的药品数量（西药和中成药）
  const currentPrescriptionData = allPrescriptionsData.value[prescriptionId || currentPrescriptionId.value] || [];
  const medicineCount = currentPrescriptionData.filter(item => item.adviceType == 1 || item.adviceType == 2).length;
  if (medicineCount >= 5) {
    proxy.$modal.msgWarning('每张处方单最多只能开5个药品，请新建处方单');
    return;
  }

  isAdding.value = true;
  // 重置查询参数
  adviceQueryParams.value = {
    searchKey: '',
    adviceType: '',
    categoryCode: ''
  };

  // 在数组最前方添加一行，让新增行显示在最上边
  prescriptionList.value.unshift({
    uniqueKey: nextId.value++,
    showPopover: false,
    check: false,
    isEdit: true,
    statusEnum: 1,
    isSaved: false, // 新增医嘱默认为未保存状态
    prescriptionId: prescriptionId || currentPrescriptionId.value, // 添加当前处方ID
  });

  // 更新对应处方的数据
  if (prescriptionId) {
    allPrescriptionsData.value[prescriptionId] = [...prescriptionList.value];
  }

  groupMarkers.value = getGroupMarkers(prescriptionList.value);
  nextTick(() => {
    const adviceRefName = 'adviceRef_' + (prescriptionId || currentPrescriptionId.value) + '_0';
    const adviceRef = proxy.$refs[adviceRefName];
    if (adviceRef && adviceRef.focus) {
      adviceRef.focus();
    }
  });
}

/**
 * 点击行赋值
 */
function clickRow(row, column, cell, event, prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  emit('selectDiagnosis', row);
}

function checkUnit(item, row) {
  if (item.type == 'dose') {
    return false;
  } else if (row.partAttributeEnum == '2' && item.type == 'minUnit') {
    return false;
  } else {
    return true;
  }
}

// 行双击打开编辑块，仅待发送的可编辑
function clickRowDb(row, event, prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  if (row.statusEnum == 1) {
    row.isEdit = true;
    const index = prescriptionList.value.findIndex((item) => item.uniqueKey === row.uniqueKey);
    prescriptionList.value[index] = row;
    // 确保只有当前行展开，先清空数组再添加当前行的uniqueKey
    updateExpandOrder([row.uniqueKey]);
  }
}

function up(index, row) {}

function down(index, row) {}

function handleDiagnosisChange(definitionId, prescriptionId) {
  // 查找对应的诊断信息
  const diagnosis = diagnosisList.value.find(item => item.definitionId === definitionId);
  if (!diagnosis) {
    return;
  }

  // 更新全局诊断信息
  diagnosisName.value = diagnosis.name;
  conditionId.value = diagnosis.conditionId;
  conditionDefinitionId.value = diagnosis.definitionId;
  encounterDiagnosisId.value = diagnosis.encounterDiagnosisId;

  // 如果指定了处方ID，更新该处方的诊断信息
  if (prescriptionId) {
    const prescription = westernPrescriptions.value.find(p => p.id === prescriptionId);
    if (prescription) {
      prescription.conditionDefinitionId = definitionId;
    }
  }
}

function handleFocus(row, index) {
  rowIndex.value = index;
  row.showPopover = true;
  // 确保查询参数与当前行类型一致
  let categoryCode = '';
  let adviceType = row.adviceType || '';

  // 根据医嘱类型设置筛选条件
  // drord_doctor_type: 1=西药, 2=中成药, 3=诊疗, 4=耗材, 5=全部
  if (row.adviceType == 1) {
    // 西药
    categoryCode = '2';
    adviceType = 1; // 药品类型
  } else if (row.adviceType == 2) {
    // 中成药
    categoryCode = '1';
    adviceType = 1; // 药品类型
  } else if (row.adviceType == 3) {
    // 诊疗：adviceType = 3
    categoryCode = '';
    adviceType = 3; // 诊疗类型
  } else if (row.adviceType == 4) {
    // 耗材：adviceType = 2（后端接口中耗材的adviceType是2）
    categoryCode = '';
    adviceType = 2; // 耗材类型
  } else {
    // 全部(5)或其他：显示所有类型
    categoryCode = '';
    adviceType = '';
  }

  adviceQueryParams.value = {
    adviceType: adviceType,
    categoryCode: categoryCode,
    searchKey: adviceQueryParams.value.searchKey || ''
  };
}

function handleBlur(row) {
   setTimeout(() => {
    row.showPopover = false;
  }, 200);
}

function handleChange(value) {
  adviceQueryParams.value.searchKey = value;
}

/**
 * 处理皮试字段变化
 */
function handleSkinTestChange(row, index) {
  // 确保 skinTestFlag 是数字类型（1 或 0）
  if (row.skinTestFlag !== undefined && row.skinTestFlag !== null) {
    row.skinTestFlag = typeof row.skinTestFlag === 'number'
      ? row.skinTestFlag
      : (row.skinTestFlag ? 1 : 0);
  } else {
    row.skinTestFlag = 0;
  }
  // 更新显示文本
  row.skinTestFlag_enumText = row.skinTestFlag == 1 ? '是' : '否';
}

/**
 * 选择药品回调
 */
function selectAdviceBase(key, row) {
  // 通过 uniqueKey 查找对应的处方和索引
  let targetPrescriptionId = null;
  let targetIndex = -1;
  let targetRow = null;

  // 1. 首先在当前处方的prescriptionList中查找
  const currentIndex = prescriptionList.value.findIndex((item) => item.uniqueKey === key);
  if (currentIndex !== -1) {
    // 在当前处方中找到匹配的行
    targetPrescriptionId = currentPrescriptionId.value;
    targetIndex = currentIndex;
    targetRow = prescriptionList.value[currentIndex];
  } else {
    // 2. 如果当前处方中找不到，遍历所有处方找到对应的行
    for (const prescription of westernPrescriptions.value) {
      const prescriptionData = allPrescriptionsData.value[prescription.id] || [];
      const index = prescriptionData.findIndex((item) => item.uniqueKey === key);
      if (index !== -1) {
        targetPrescriptionId = prescription.id;
        targetIndex = index;
        targetRow = prescriptionData[index];
        break;
      }
    }
  }

  if (targetIndex === -1) {
    console.error('找不到对应的行数据, uniqueKey:', key);
    return;
  }

  // 如果选择的是西药或中成药，检查是否会超过5个药品限制
  if (row.adviceType == 1 || row.adviceType == 2) {
    const currentPrescriptionData = allPrescriptionsData.value[targetPrescriptionId] || [];
    const medicineCount = currentPrescriptionData.filter(item =>
      item.uniqueKey !== key && (item.adviceType == 1 || item.adviceType == 2)
    ).length;

    if (medicineCount >= 5) {
      proxy.$modal.msgWarning('每张处方单最多只能开5个药品，请新建处方单');
      // 关闭弹窗并清除该行
      prescriptionList.value[targetIndex].showPopover = false;
      return;
    }
  }

  // 切换到目标处方
  if (targetPrescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(targetPrescriptionId);
  }

  // 立即关闭当前弹窗
  prescriptionList.value[targetIndex].showPopover = false;
  if (row.adviceType == 3) {
    getActivityBindDevice({ activityId: row.adviceDefinitionId }).then((res) => {
      if (res.data.activityBindDeviceInfos?.length > 0) {
        ElMessageBox.confirm('该诊疗项目已绑定所需耗材，点击确定将自动添加到医嘱列表', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          closeOnClickModal: false,
          closeOnPressEscape: false,
        }).then(() => {
          handleSaveGroup(res.data.activityBindDeviceInfos);
        });
      }
    });
  }
  getOrgList();
  unitCodeList.value = [];
  unitCodeList.value.push({ value: row.unitCode, label: row.unitCode_dictText, type: 'unit' });
  // if (row.doseUnitCode != row.minUnitCode) {
  unitCodeList.value.push({
    value: row.doseUnitCode,
    label: row.doseUnitCode_dictText,
    type: 'dose',
  });
  // }
  if (
    (row.partAttributeEnum == 1 || row.partAttributeEnum == 3) &&
    row.minUnitCode != row.unitCode
  ) {
    unitCodeList.value.push({
      value: row.minUnitCode,
      label: row.minUnitCode_dictText,
      type: 'minUnit',
    });
  }
  if (row.adviceType == 2 && row.minUnitCode != row.unitCode) {
    unitCodeList.value.push({
      value: row.minUnitCode,
      label: row.minUnitCode_dictText,
      type: 'minUnit',
    });
  }
  // 保存当前已选择的医嘱类型
  const currentAdviceType = prescriptionList.value[targetIndex].adviceType;

  // 如果医嘱类型是"全部"（5）或未选择，根据药品的categoryCode自动判断
  // drord_doctor_type: 1=西药, 2=中成药, 3=诊疗, 4=耗材, 5=全部
  let finalAdviceType = currentAdviceType;

  // 判断是否是耗材（从耗材目录接口返回的数据，adviceType=2表示耗材）
  const isConsumablesFromDevice = row.adviceType == 2 && (row.deviceId || row.deviceName);

  // 优先判断：如果用户已选择耗材类型（4），直接使用
  if (currentAdviceType !== undefined && currentAdviceType !== null && currentAdviceType !== '' && Number(currentAdviceType) === 4) {
    // 用户已选择耗材类型，直接使用
    finalAdviceType = 4;
  } else if (isConsumablesFromDevice) {
    // 如果是耗材（从耗材目录接口来的数据），设置为4（前端显示的耗材类型）
    finalAdviceType = 4;
  } else if (currentAdviceType !== undefined && currentAdviceType !== null && currentAdviceType !== '' && Number(currentAdviceType) !== 5) {
    // 用户已选择其他医嘱类型（且不是"全部"），保留用户的选择，确保是数字类型
    finalAdviceType = Number(currentAdviceType);
  } else if (Number(row.adviceType) === 1) {
    // 药品类型（adviceType=1），需要根据categoryCode判断是西药还是中成药
    // categoryCode = '1' 表示中成药，categoryCode = '2' 表示西药
    if (row.categoryCode == '1') {
      finalAdviceType = 2; // 中成药
    } else if (row.categoryCode == '2') {
      finalAdviceType = 1; // 西药
    } else {
      // 如果没有categoryCode，使用项目默认的类型
      finalAdviceType = Number(row.adviceType);
    }
  } else if (Number(row.adviceType) === 2) {
    // 如果 row.adviceType == 2，可能是中成药（药品）或耗材
    // 优先判断是否是耗材：有 deviceId 或 deviceName
    if (row.deviceId || row.deviceName) {
      finalAdviceType = 4; // 耗材
    } else {
      // 没有 deviceId 或 deviceName，可能是中成药（药品）
      // 根据 categoryCode 判断
if (row.categoryCode == '1') {
        finalAdviceType = 2; // 中成药
      } else {
        // 默认认为是中成药
        finalAdviceType = 2;
      }
    }
  } else {
    // 使用项目默认的类型，确保是数字类型
    finalAdviceType = Number(row.adviceType);
  }

  // 确保 skinTestFlag 是数字类型（1 或 0），如果未定义则默认为 0
  let skinTestFlag = row.skinTestFlag !== undefined && row.skinTestFlag !== null
    ? (typeof row.skinTestFlag === 'number' ? row.skinTestFlag : (row.skinTestFlag ? 1 : 0))
    : 0;

  prescriptionList.value[targetIndex] = {
    ...prescriptionList.value[targetIndex],
    ...JSON.parse(JSON.stringify(row)),
    adviceType: finalAdviceType, // 确保是数字类型
    skinTestFlag: skinTestFlag, // 确保皮试字段是数字类型
  };

  // 确保字典已加载后更新显示
  nextTick(() => {
    // 如果字典已加载，强制更新视图以确保显示正确的文本
    if (drord_doctor_type.value && drord_doctor_type.value.length > 0) {
      // 触发响应式更新
      const currentRow = prescriptionList.value[targetIndex];
      prescriptionList.value[targetIndex] = {
        ...currentRow
      };
    }
  });
  prescriptionList.value[targetIndex].orgId = undefined;
  prescriptionList.value[targetIndex].dose = undefined;
  prescriptionList.value[targetIndex].unitCodeList = unitCodeList.value;
  // prescriptionList.value[targetIndex].doseUnitCode =
  //   row.minUnitCode != row.unitCode ? row.minUnitCode : row.unitCode;
  // prescriptionList.value[targetIndex].minUnitCode = JSON.parse(JSON.stringify(row.doseUnitCode));
  prescriptionList.value[targetIndex].doseUnitCode = row.doseUnitCode;
  prescriptionList.value[targetIndex].minUnitCode = row.minUnitCode;
  prescriptionList.value[targetIndex].unitCode =
    row.partAttributeEnum == 1 ? row.minUnitCode : row.unitCode;
  prescriptionList.value[targetIndex].categoryEnum = row.categoryCode;
  // prescriptionList.value[targetIndex].doseUnitCode_dictText = row.minUnitCode_dictText;
  prescriptionList.value[targetIndex].definitionId = JSON.parse(
    JSON.stringify(row)
  ).chargeItemDefinitionId;

  // 库存列表 + 价格列表拼成批次号的下拉框
  // 判断是否是耗材（从耗材目录接口返回的数据）
  const isConsumables = (row.adviceType == 2 && (row.deviceId || row.deviceName)) || finalAdviceType == 4;

  if (row.adviceType != 3 && !isConsumables) {
    // 药品类型（西药、中成药）需要检查库存
    if (row.inventoryList && row.inventoryList.length == 0) {
      updateExpandOrder([]);
      proxy.$modal.msgWarning('该项目无库存');
      return;
    }
    stockList.value = row.inventoryList.map((item, index) => {
      return { ...item, ...row.priceList[index] };
    });
    prescriptionList.value[targetIndex].stockList = stockList.value;
    // 获取默认批次号的库存，如果没有让医生重新选
    let stock = stockList.value.filter((item) => {
      return item.lotNumber == row.defaultLotNumber;
    })[0];
    if (stock != {} && stock != undefined) {
      if (stock.quantity <= 0) {
        stock = stockList.value.filter((item) => {
          return item.quantity > 0 && item.locationId == row.positionId;
        })[0];
        if (stock == {} || stock == undefined) {
          proxy.$modal.msgWarning('该项目库存不足，请选择其它库房');
          return;
        }
        // proxy.$modal.msgWarning('该项目库存不足，请选择其它库房');
        // return;
      }
      prescriptionList.value[targetIndex].lotNumber = stock.lotNumber;
      prescriptionList.value[targetIndex].inventoryId = stock.inventoryId;
      prescriptionList.value[targetIndex].locationId = stock.locationId;
      prescriptionList.value[targetIndex].unitPrice = stock.price;
      prescriptionList.value[targetIndex].unitTempPrice = stock.price;
      prescriptionList.value[targetIndex].minUnitPrice = new Decimal(stock.price)
        .div(row.partPercent)
        .toFixed(2);
      prescriptionList.value[targetIndex].positionName = stock.locationName;
    }
  } else if (isConsumables) {
    // 耗材类型：设置价格和位置信息
    const price = row.price || row.retailPrice || (row.priceList && row.priceList.length > 0 ? row.priceList[0].price : 0);
    prescriptionList.value[targetIndex].unitPrice = price;
    prescriptionList.value[targetIndex].unitTempPrice = price;
    prescriptionList.value[targetIndex].minUnitPrice = price;
    prescriptionList.value[targetIndex].positionId = row.locationId;
    prescriptionList.value[targetIndex].positionName = row.locationId_dictText || row.positionName || '';
    // 耗材可能没有库存列表，设置为空数组
    prescriptionList.value[targetIndex].stockList = [];
    prescriptionList.value[targetIndex].inventoryList = [];
  } else {
    // 诊疗类型：执行科室默认逻辑：优先使用诊疗项目维护的所属科室，如果没有则使用开单科室
    const defaultOrgId = row.positionId || props.patientInfo.orgId;
    prescriptionList.value[targetIndex].orgId = defaultOrgId;
    prescriptionList.value[targetIndex].unitPrice = row.priceList && row.priceList.length > 0 ? row.priceList[0].price : 0;
  }

  // 检查是否是皮试药品，如果是则弹出确认提示
  // 只对药品类型（西药和中成药）进行皮试提示
  // 使用原始 row 中的 skinTestFlag 来判断，因为这是药品基础信息中的皮试标志
  const isSkinTestDrug = row.skinTestFlag !== undefined && row.skinTestFlag !== null
    ? (typeof row.skinTestFlag === 'number' ? row.skinTestFlag == 1 : (row.skinTestFlag ? true : false))
    : false;

  if ((row.adviceType == 1 || row.adviceType == 2) && isSkinTestDrug) {
    ElMessageBox.confirm(
      `药品：${row.adviceName}需要做皮试，是否做皮试？`,
      '提示',
      {
        confirmButtonText: '是(Y)',
        cancelButtonText: '否(N)',
        type: 'info',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        distinguishCancelAndClose: true,
      }
    )
      .then(() => {
        // 用户点击"是"，自动勾选皮试字段
        prescriptionList.value[targetIndex].skinTestFlag = 1;
        prescriptionList.value[targetIndex].skinTestFlag_enumText = '是';
        // 展开订单并继续后续流程
        expandOrderAndFocus(key, row);
      })
      .catch((action) => {
        // 用户点击"否"或关闭，不勾选皮试字段
        prescriptionList.value[targetIndex].skinTestFlag = 0;
        prescriptionList.value[targetIndex].skinTestFlag_enumText = '否';
        // 展开订单并继续后续流程
        expandOrderAndFocus(key, row);
      });
  } else {
    // 不是皮试药品，直接展开订单
    expandOrderAndFocus(key, row);
  }

  // 同步数据到对应的处方
  if (targetPrescriptionId) {
    allPrescriptionsData.value[targetPrescriptionId] = [...prescriptionList.value];
  }
}

/**
 * 展开订单并聚焦输入框
 */
function expandOrderAndFocus(key, row) {
  // 确保只有当前行展开
  updateExpandOrder([key]);

  nextTick(() => {
    // 找到当前行的索引
    const index = prescriptionList.value.findIndex(item => item.uniqueKey === key);

    // 判断是否是耗材（adviceType == 4 或从耗材目录来的数据）
    const isConsumables = row.adviceType == 4 || (row.adviceType == 2 && (row.deviceId || row.deviceName));

    if (row.adviceType == 1 || row.adviceType == 2) {
      // 药品类型（西药、中成药）
      if (row.injectFlag == 1) {
        inputRefs.value[index]?.['executeNum']?.focus();
      } else {
        inputRefs.value[index]?.['doseQuantity']?.focus();
      }
    } else if (isConsumables) {
      // 耗材类型：类似诊疗，聚焦执行次数输入框
      inputRefs.value[index]?.['quantity']?.focus();
    } else {
      // 诊疗类型
      inputRefs.value[index]?.['quantity']?.focus();
    }
  });
}

function getOrgList() {
  getOrgTree().then((res) => {
    organization.value = res.data.records;
  });
}

function handleDelete(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  let selectRow = groupIndexList.value.map((index) => prescriptionList.value[index]);
  if (selectRow.length == 0) {
    proxy.$modal.msgWarning('请选择要删除的医嘱');
    return;
  }
  let deleteList = [];
  let sum = 0; // 未保存总数量
  for (let i = prescriptionList.value.length - 1; i >= 0; i--) {
    let deleteItem = prescriptionList.value[i];
    let index = selectRows.findIndex((item) => item.uniqueKey === deleteItem.uniqueKey);
    // 通过requestId判断是否已保存，如果选中项未保存 直接从数组中移除，如果已保存，调接口删除
    if (index != -1 && deleteItem.statusEnum == 1 && !deleteItem.requestId) {
      prescriptionList.value.splice(i, 1);
      sum++;
    } else if (index != -1 && deleteItem.statusEnum == 1 && deleteItem.requestId) {
      deleteList.push({
        requestId: deleteItem.requestId,
        dbOpType: '3',
        adviceType: deleteItem.adviceType,
      });
    }
  }
  handleEmrTreatment();
  updateExpandOrder([]);
  isAdding.value = false;
  adviceQueryParams.value.adviceType = undefined;
  adviceQueryParams.value.categoryCode = undefined;
  if (sum == selectRow.length) {
    proxy.$modal.msgSuccess('删除成功');
    return;
  }
  if (deleteList.length > 0) {
    savePrescription({ adviceSaveList: deleteList }).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('删除成功');
        getListInfo(false);
      }
    });
  } else {
    proxy.$modal.msgWarning('所选医嘱不可删除，请先撤回后再删除');
    return;
  }
}

// 选择药房/耗材房处理
function handleNumberClick(item, index, row) {
  row.unitPrice = item.price;
  row.lotNumber = item.lotNumber;
  row.locationId = item.locationId;
  row.positionId = item.locationId;
  row.positionName = item.locationName;
}

// 选择执行科室处理
function handleOrgChange(value, index, row) {
  row.positionId = value;
}

/**
 * 签发处方
 */
function handleSave(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  // 验证费用性质是否已选择
  if (!accountId.value) {
    proxy.$modal.msgWarning('请先选择费用性质');
    return;
  }

  if (expandOrder.value.length > 0) {
    proxy.$modal.msgWarning('请先保存当前医嘱');
    return;
  }
  if (prescriptionList.value[0]?.isEdit && !prescriptionList.value[0].adviceType) {
    prescriptionList.value.shift();
    isAdding.value = false;
    updateExpandOrder([]);
  }
  let saveList = prescriptionList.value.filter((item) => {
    return item.statusEnum == 1;
  });

  let validList = saveList.filter((item) => {
    return !item.isSaved;
  });
  if (validList.length > 0) {
    proxy.$modal.msgWarning('存在未保存的医嘱，请先点击保存按钮后再执行签发');
    return;
  }

  // 只签发已保存的医嘱
  saveList = saveList.filter((item) => item.isSaved);
  if (saveList.length == 0) {
    proxy.$modal.msgWarning('当前无可签发处方');
    return;
  }
  if (!validateGroups(saveList)) {
    return;
  }
  // let itemName = '';
  // saveList.forEach((item) => {
  //   if (item.injectFlag == 1 && item.groupId == undefined) {
  //     itemName = itemName ? itemName + ', ' : '';
  //     itemName += item.adviceName;
  //   }
  // });
  // if (itemName != '') {
  //   proxy.$modal.msgWarning(itemName + '为输液项目，请进行分组');
  //   return;
  // }
  // saveList.forEach((item) => {
  //   item.patientId = props.patientInfo.patientId;
  //   item.encounterId = props.patientInfo.encounterId;
  //   item.accountId = props.patientInfo.accountId;
  //   item.dbOpType = '1';
  // });
  // 此处签发处方和单行保存处方传参相同，后台已经将传参存为JSON字符串，此处直接转换为JSON即可
  loading.value = true;
  let list = saveList.map((item) => {
    const parsedContent = JSON.parse(item.contentJson);
    // 保存时，将前端的耗材类型（4）转换为后端需要的类型（2）
    // 后端接口中：1=药品, 2=耗材, 3=诊疗
    // 前端显示中：1=西药, 2=中成药, 3=诊疗, 4=耗材
    const saveAdviceType = item.adviceType == 4 ? 2 : item.adviceType;
    return {
      ...item,
      adviceType: saveAdviceType,
      dbOpType: item.requestId ? '2' : '1',
    };
  });
  savePrescriptionSign({
    organizationId: props.patientInfo.orgId,
    adviceSaveList: list,
  })
    .then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('签发成功');
        getListInfo(false);
        nextId.value = 1;
      }
    })
    .finally(() => {
      loading.value = false;
    });
  // 长春大学要求
  if (userStore.fixmedinsCode == 'H22010200672') {
    handleEmrTreatment();
  }
}

// 把开过的处方加到病历的处理中
function handleEmrTreatment() {
  // 病历处理字符串拼接
  let treatment = '';
  let treatmentIndex = 1;
  // 病历辅助检查字符串拼接
  let auxiliaryExamination = '';
  let auxiliaryExaminationIndex = 1;

  prescriptionList.value.forEach((item, index) => {
    if (item.chargeStatus != 8) {
      if (item.adviceType == 1) {
        // 药品处方
        treatment += '处方[' + (index + 1) + ']' + '  ';
        treatment += item.adviceName + '  ' + item.volume + '  ';
        treatment +=
          '用法：' +
          item.dose +
          item.doseUnitCode_dictText +
          '  ' +
          item.rateCode_dictText +
          '  ' +
          item.methodCode_dictText +
          '；  ';
        treatmentIndex++;
      } else if (item.adviceType == 2) {
        // 诊疗项目
        treatment += '诊疗[' + (index + 1) + ']' + '  ';
        treatment += item.adviceName + '  ';
        if (item.quantity) {
          treatment += '数量：' + item.quantity + item.unitCode_dictText + '  ';
        }
        treatment += '频次：' + item.rateCode_dictText + '  ';
        if (item.methodCode_dictText) {
          treatment += '方式：' + item.methodCode_dictText + '  ';
        }
        treatment += '；  ';
      } else if (item.adviceType == 3) {
        // 检查项目
        auxiliaryExamination += '[' + (index + 1) + ']' + '  ';
        auxiliaryExamination += item.adviceName + '；  ';
        auxiliaryExaminationIndex++;
      }
    }
  });
  getEmrDetail(props.patientInfo.encounterId).then((res) => {
    saveEmr({
      patientId: props.patientInfo.patientId,
      encounterId: props.patientInfo.encounterId,
      contextJson: {
        ...JSON.parse(res.data.contextJson),
        treatment: treatment,
      },
    });
  });
}

function stockFormat(partPercent, unitList, quantity) {
  let unitCode = unitList.find((item) => {
    return item.type == 'unit';
  })?.label;
  let minUnitCode = unitList.find((item) => {
    return item.type == 'minUnit';
  })?.label;

  let a = quantity % partPercent;
  let b = Math.floor(quantity / partPercent);
  if (a == 0) {
    return b + ' ' + unitCode;
  }
  return b + ' ' + unitCode + ' ' + a + ' ' + minUnitCode;
}

// 处理自动带出的诊疗或者耗材
function handleOrderBindInfo(bindIdInfo) {
  const adviceDefinitionIds = bindIdInfo.map((row) => row.orderDefinitionId);
  getAdviceBaseInfo({ adviceDefinitionIdParamList: adviceDefinitionIds.join(',') }).then((res) => {
    const list = res.data.records.map((item) => {
      const info = bindIdInfo.find((k) => k.orderDefinitionId == item.adviceDefinitionId);
      return {
        ...item,
        quantity: info.quantity,
        unitCode: info.unitCode,
      };
    });

    list?.forEach((item) => {
      rowIndex.value = prescriptionList.value.length;
      setValue(item);

      // 创建新的处方项目
      const newRow = {
        ...prescriptionList.value[rowIndex.value],
        uniqueKey: nextId.value++,
        patientId: props.patientInfo.patientId,
        encounterId: props.patientInfo.encounterId,
        accountId: accountId.value,
        quantity: item.quantity,
        methodCode: item.methodCode,
        rateCode: item.rateCode,
        dispensePerDuration: item.dispensePerDuration,
        dose: item.dose,
        doseQuantity: item.doseQuantity,
        executeNum: 1,
        unitCode: item.unitCode,
        unitCode_dictText: item.unitCodeName || '',
        statusEnum: 1,
        dbOpType: prescriptionList.value[rowIndex.value].requestId ? '2' : '1',
        conditionId: conditionId.value,
        conditionDefinitionId: conditionDefinitionId.value,
        encounterDiagnosisId: encounterDiagnosisId.value,
      };

      // 计算价格和总量
      const unitInfo = unitCodeList.value.find((k) => k.value == item.unitCode);
      if (unitInfo && unitInfo.type == 'minUnit') {
        newRow.price = newRow.minUnitPrice;
        newRow.totalPrice = (item.quantity * newRow.minUnitPrice).toFixed(6);
        newRow.minUnitQuantity = item.quantity;
      } else {
        newRow.price = newRow.unitPrice;
        newRow.totalPrice = (item.quantity * newRow.unitPrice).toFixed(6);
        newRow.minUnitQuantity = item.quantity * item.partPercent;
      }

      newRow.contentJson = JSON.stringify(newRow);
      prescriptionList.value[rowIndex.value] = newRow;
    });
  });
}
// 单行处方保存
function handleSaveSign(row, index, prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  const targetPrescriptionId = prescriptionId || currentPrescriptionId.value;
  if (targetPrescriptionId && targetPrescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(targetPrescriptionId);
  }

  // 验证费用性质是否已选择
  if (!accountId.value) {
    proxy.$modal.msgWarning('请先选择费用性质');
    return;
  }

  // 重新查找索引，确保使用当前处方列表中的正确索引
  const actualIndex = prescriptionList.value.findIndex(item => item.uniqueKey === row.uniqueKey);
  if (actualIndex === -1) {
    console.error('找不到对应的行数据, uniqueKey:', row.uniqueKey);
    proxy.$modal.msgError('数据同步失败，请重试');
    return;
  }

  const formRefName = 'formRef_' + targetPrescriptionId + '_' + actualIndex;
  let formRef = proxy.$refs[formRefName];

  console.log('handleSaveSign - 查找表单引用:', formRefName, '是否找到:', !!formRef, '类型:', typeof formRef, 'formRef:', formRef);

  // 如果 formRef 是数组，取第一个元素
  if (Array.isArray(formRef)) {
    formRef = formRef[0];
    console.log('formRef 是数组，取第一个元素:', formRef);
  }

  if (!formRef) {
    console.error('找不到表单引用:', formRefName);
    proxy.$modal.msgError('表单验证失败，请重试');
    return;
  }

  // 检查 validate 方法是否存在
  if (typeof formRef.validate !== 'function') {
    console.error('表单引用没有 validate 方法:', formRefName, 'formRef keys:', Object.keys(formRef));
    proxy.$modal.msgError('表单验证方法不可用，请重试');
    return;
  }

  formRef.validate((valid) => {
    if (valid) {
      if (row.adviceType != 2) {
        // 1:用法绑东西 2:诊疗绑东西
        let typeCode = row.adviceType == 1 ? '1' : '2';
        // 用法字典值/诊疗定义id
        let itemNo = row.adviceType == 1 ? row.methodCode : row.adviceDefinitionId;
        getBindDevice({ typeCode: typeCode, itemNo: itemNo }).then((res) => {
          if (res.data.length == 0) {
            return;
          }
          // 是否需要打开弹窗
          let openBindDialog = localStorage.getItem('doctor' + userStore.id);
          if (!JSON.parse(openBindDialog)) {
            proxy.$refs['orderBindInfoRef'].open(res.data);
          } else {
            // 如果弹窗不提示带出的项目，自动带出
            // 如果有未签发的项目，并且当前的项目没有带出过绑定项目，则自动带出
            if (!bindMethod.value[itemNo]) {
              handleOrderBindInfo(res.data);
              bindMethod.value[itemNo] = true;
            }
          }
        });
      }
      row.isEdit = false;
      isAdding.value = false;
      updateExpandOrder([]);
      row.contentJson = undefined;
      row.patientId = props.patientInfo.patientId;
      row.encounterId = props.patientInfo.encounterId;
      row.accountId = accountId.value;
      if (row.adviceType == 1 || row.adviceType == 2) {
        row.minUnitQuantity =
          row.minUnitCode == row.unitCode ? row.quantity : row.quantity * row.partPercent;
      } else {
        row.minUnitQuantity = row.quantity;
      }
      row.conditionId = conditionId.value;
      // 处理总量为小单位情况，需要把单价也保存成小单位的
      if (row.unitCodeList.find((item) => item.value == row.unitCode).type == 'unit') {
        if (row.adviceType != 3) {
          row.unitPrice = row.unitTempPrice;
        }
      } else {
        row.unitCode_dictText = row.unitCodeList.find(
          (item) => item.value == row.minUnitCode
        ).label;
        row.unitPrice = row.minUnitPrice;
      }
      row.conditionDefinitionId = conditionDefinitionId.value;
      row.encounterDiagnosisId = encounterDiagnosisId.value;
      row.diagnosisName = diagnosisName.value;
      // 确保 skinTestFlag 是数字类型（1 或 0）
      if (row.skinTestFlag !== undefined && row.skinTestFlag !== null) {
        row.skinTestFlag = typeof row.skinTestFlag === 'number'
          ? row.skinTestFlag
          : (row.skinTestFlag ? 1 : 0);
      } else {
        row.skinTestFlag = 0;
      }
      row.skinTestFlag_enumText = row.skinTestFlag == 1 ? '是' : '否';
      if (row.injectFlag == 1) {
        row.sortNumber = row.sortNumber ? row.sortNumber : prescriptionList.value.length;
      }
      // 保存时，将前端的耗材类型（4）转换为后端需要的类型（2）
      // 后端接口中：1=药品, 2=耗材, 3=诊疗
      // 前端显示中：1=西药, 2=中成药, 3=诊疗, 4=耗材
      const saveAdviceType = row.adviceType == 4 ? 2 : row.adviceType;
      // 创建一个新的对象进行序列化，避免循环引用
      const rowToSave = {
        ...row,
        adviceType: saveAdviceType,
        isSaved: false, // 确定后为待保存状态
        contentJson: undefined // 确保 contentJson不被序列化
      };
      // 对中成药类型（2）特别处理，确保adviceName被正确保存
      if (row.adviceType == 2) {
        rowToSave.adviceName = row.adviceName; // 确保adviceName被显式设置
      }
      row.contentJson = JSON.stringify(rowToSave);
      // 恢复原始的adviceType供前端显示使用
      row.adviceType = row.adviceType;

      // 确认操作应该只保存为待保存状态，不设置 isSaved 标识
      // 这样用户点击保存按钮时才会变为待签发状态
      row.dbOpType = row.requestId ? '2' : '1';
      row.isSaved = false; // 确定后为待保存状态
      savePrescription({ adviceSaveList: [row] }).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('保存成功');
          getListInfo(true);
          nextId.value = 1;
        }
      });
    }
  });
}

function handleSaveBatch(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  // 确保使用对应处方的数据
  const targetPrescriptionId = prescriptionId || currentPrescriptionId.value;
  if (!targetPrescriptionId) {
    proxy.$modal.msgWarning('请先创建处方');
    return;
  }

  // 从对应处方的数据中获取列表，而不是使用全局的 prescriptionList
  const currentPrescriptionData = allPrescriptionsData.value[targetPrescriptionId] || [];

  // 验证费用性质是否已选择
  const prescription = westernPrescriptions.value.find(p => p.id === targetPrescriptionId);
  if (!prescription || !prescription.accountId) {
    proxy.$modal.msgWarning('请先选择费用性质');
    return;
  }

  // 获取对应处方的展开状态
  const prescriptionExpandOrder = prescription.expandOrder || [];
  if (prescriptionExpandOrder.length > 0) {
    proxy.$modal.msgWarning('请先点击确定确认当前医嘱');
    return;
  }

  // 处理空行
  if (currentPrescriptionData.length > 0 && currentPrescriptionData[0].isEdit && !currentPrescriptionData[0].adviceType) {
    currentPrescriptionData.shift();
    isAdding.value = false;
    // 更新存储的数据
    allPrescriptionsData.value[targetPrescriptionId] = [...currentPrescriptionData];
    // 如果当前显示的就是这个处方，同步到 prescriptionList
    if (currentPrescriptionId.value === targetPrescriptionId) {
      prescriptionList.value = [...currentPrescriptionData];
    }
  }

  // 使用对应处方的数据来过滤和保存
  let saveList = currentPrescriptionData
    .filter((item) => {
      // 确保只保存属于当前处方的数据
      return item.statusEnum == 1 && !item.isSaved && (item.prescriptionId === targetPrescriptionId || !item.prescriptionId);
    })
    .map((item) => {
      // 为每个医嘱项设置minUnitQuantity值，避免后端null值异常
      if (item.adviceType == 1 || item.adviceType == 2) {
        item.minUnitQuantity = item.minUnitCode == item.unitCode ? item.quantity : item.quantity * item.partPercent;
      } else {
        item.minUnitQuantity = item.quantity;
      }

      // 将前端的耗材类型（4）转换为后端需要的类型（2）
      const saveAdviceType = item.adviceType == 4 ? 2 : item.adviceType;

      // 创建要序列化的对象
      const itemToSave = {
        ...item,
        adviceType: saveAdviceType,
        isSaved: true, // 保存后设置为待签发状态
        prescriptionId: prescriptionId || currentPrescriptionId.value, // 添加当前处方ID标识
        contentJson: undefined // 避免循环引用
      };

      // 序列化到 contentJson
      const contentJson = JSON.stringify(itemToSave);

      return {
        ...item,
        dbOpType: item.requestId ? '2' : '1',
        isSaved: true,
        prescriptionId: prescriptionId || currentPrescriptionId.value, // 添加当前处方ID标识
        contentJson: contentJson // 使用新的 contentJson
      };
    });
  if (saveList.length == 0) {
    proxy.$modal.msgWarning('当前没有可保存医嘱');
    return;
  }
  savePrescription({ adviceSaveList: saveList }).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('保存成功');
          // 保存成功后，更新当前处方的数据
          currentPrescriptionData.forEach(item => {
            if (saveList.find(saved => saved.uniqueKey === item.uniqueKey)) {
              item.isSaved = true;
            }
          });
          // 更新存储的数据
          allPrescriptionsData.value[targetPrescriptionId] = [...currentPrescriptionData];
          // 如果当前显示的就是这个处方，同步到 prescriptionList
          if (currentPrescriptionId.value === targetPrescriptionId) {
            prescriptionList.value = [...currentPrescriptionData];
          }
          getListInfo(false);
          nextId.value = 1;
        }
      });
}

function setValue(row) {
  unitCodeList.value = [];
  unitCodeList.value.push({ value: row.unitCode, label: row.unitCode_dictText, type: 'unit' });
  unitCodeList.value.push({
    value: row.doseUnitCode,
    label: row.doseUnitCode_dictText,
    type: 'dose',
  });

  unitCodeList.value.push({
    value: row.minUnitCode,
    label: row.minUnitCode_dictText,
    type: 'minUnit',
  });
  if (row.adviceType == 2 && row.minUnitCode != row.unitCode) {
    unitCodeList.value.push({
      value: row.minUnitCode,
      label: row.minUnitCode_dictText,
      type: 'minUnit',
    });
  }
  // 确保 skinTestFlag 是数字类型（1 或 0），如果未定义则默认为 0
  const skinTestFlag = row.skinTestFlag !== undefined && row.skinTestFlag !== null
    ? (typeof row.skinTestFlag === 'number' ? row.skinTestFlag : (row.skinTestFlag ? 1 : 0))
    : 0;

  prescriptionList.value[targetIndex] = {
    ...prescriptionList.value[targetIndex],
    ...JSON.parse(JSON.stringify(row)),
    // 确保adviceType为数字类型，避免类型不匹配导致的显示问题
    adviceType: Number(row.adviceType),
    skinTestFlag: skinTestFlag, // 确保皮试字段是数字类型
    skinTestFlag_enumText: skinTestFlag == 1 ? '是' : '否', // 更新显示文本
  };
  prescriptionList.value[targetIndex].orgId = undefined;
  prescriptionList.value[targetIndex].dose = undefined;
  prescriptionList.value[targetIndex].unitCodeList = unitCodeList.value;
  // prescriptionList.value[targetIndex].doseUnitCode =
  //   row.minUnitCode != row.unitCode ? row.minUnitCode : row.unitCode;
  // prescriptionList.value[targetIndex].minUnitCode = JSON.parse(JSON.stringify(row.doseUnitCode));
  prescriptionList.value[targetIndex].doseUnitCode = row.doseUnitCode;
  prescriptionList.value[targetIndex].minUnitCode = row.minUnitCode;
  prescriptionList.value[targetIndex].categoryEnum = row.categoryCode;
  prescriptionList.value[targetIndex].unitCode =
    row.partAttributeEnum == 1 ? row.minUnitCode : row.unitCode;
  // prescriptionList.value[targetIndex].doseUnitCode_dictText = row.minUnitCode_dictText;
  prescriptionList.value[targetIndex].definitionId = JSON.parse(
    JSON.stringify(row)
  ).chargeItemDefinitionId;

  // 库存列表 + 价格列表拼成批次号的下拉框
  if (row.adviceType != 3) {
    if (row.inventoryList && row.inventoryList.length == 0) {
      // updateExpandOrder([]);
      proxy.$modal.msgWarning('该项目无库存');
      return;
    }
    stockList.value = row.inventoryList.map((item, index) => {
      return { ...item, ...row.priceList[index] };
    });
    prescriptionList.value[targetIndex].stockList = stockList.value;
    // 获取默认批次号的库存，如果没有让医生重新选
    let stock = stockList.value.filter((item) => {
      return item.lotNumber == row.defaultLotNumber;
    })[0];
    if (stock != {} && stock != undefined) {
      if (stock.quantity <= 0) {
        stock = stockList.value.filter((item) => {
          return item.quantity > 0 && item.locationId == row.positionId;
        })[0];
        if (stock == {} || stock == undefined) {
          proxy.$modal.msgWarning(row.adviceName + '库存不足，请选择其它库房');
          return;
        }
      }
      prescriptionList.value[targetIndex].lotNumber = stock.lotNumber;
      prescriptionList.value[targetIndex].inventoryId = stock.inventoryId;
      prescriptionList.value[targetIndex].locationId = stock.locationId;
      prescriptionList.value[targetIndex].unitPrice = stock.price;
      prescriptionList.value[targetIndex].positionName = stock.locationName;
      prescriptionList.value[targetIndex].minUnitPrice = new Decimal(stock.price)
        .div(row.partPercent)
        .toFixed(6);
      prescriptionList.value[rowIndex.value].positionName = stock.locationName;
    }
  } else {
  // 执行科室默认逻辑：优先使用诊疗项目维护的所属科室，如果没有则使用开单科室
  const defaultOrgId = row.positionId || props.patientInfo.orgId;
  prescriptionList.value[targetIndex].orgId = defaultOrgId;
  prescriptionList.value[targetIndex].unitPrice = row.priceList[0].price;
}
}

// 选择组套
function handleSaveGroup(orderGroupList) {
  orderGroupList.forEach((item) => {
    rowIndex.value = prescriptionList.value.length;
    setValue(item.orderDetailInfos);

    prescriptionList.value[targetIndex] = {
      ...prescriptionList.value[targetIndex],
      // ...orderGroupValue,
      uniqueKey: nextId.value++,
      patientId: props.patientInfo.patientId,
      encounterId: props.patientInfo.encounterId,
      accountId: accountId.value,
      quantity: item.quantity,
      totalPrice: item.quantity * prescriptionList.value[targetIndex].unitPrice,
      unitCode: item.unitCode,
      unitCode_dictText: item.unitCodeName ? item.unitCodeName : '',
      statusEnum: 1,
      isSaved: false, // 组套保存默认为未保存状态
      dbOpType: prescriptionList.value[targetIndex].requestId ? '2' : '1',
      minUnitQuantity:
        unitCodeList.value.find((k) => k.value == item.unitCode).type == 'minUnit'
          ? item.quantity
          : item.quantity * item.orderDetailInfos.partPercent,
      conditionId: conditionId.value,
      conditionDefinitionId: conditionDefinitionId.value,
      encounterDiagnosisId: encounterDiagnosisId.value,
    };
    prescriptionList.value[targetIndex].contentJson = JSON.stringify(
      prescriptionList.value[targetIndex]
    );
  });
  console.log(prescriptionList.value);
  // });
  // savePrescription({ adviceSaveList: saveList }).then((res) => {
  //   if (res.code === 200) {
  //     proxy.$modal.msgSuccess('保存成功');
  //     getListInfo(true);
  //     nextId.value == 1;
  //   }
  // });
}

// 历史医嘱复用
function handleSaveHistory(value) {
  let saveRow = {
    ...value,
    patientId: props.patientInfo.patientId,
    encounterId: props.patientInfo.encounterId,
    accountId: accountId.value,
    uniqueKey: undefined,
    dbOpType: value.requestId ? '2' : '1',
    minUnitQuantity: value.quantity * value.partPercent,
    conditionId: conditionId.value,
    conditionDefinitionId: conditionDefinitionId.value,
    encounterDiagnosisId: encounterDiagnosisId.value,
    contentJson: JSON.stringify(value),
  };
  savePrescription({ adviceSaveList: [saveRow] }).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess('保存成功');
      getListInfo(true);
      nextId.value == 1;
    }
  });
}

// 处理回车事件
const handleEnter = (currentProp, row, rowIndex, prescriptionId) => {
  // 如果传入了处方ID，先切换到该处方
  const targetPrescriptionId = prescriptionId || currentPrescriptionId.value;
  if (targetPrescriptionId && targetPrescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(targetPrescriptionId);
  }

  // 重新查找索引，确保使用当前处方列表中的正确索引
  const actualIndex = prescriptionList.value.findIndex(item => item.uniqueKey === row.uniqueKey);
  if (actualIndex === -1) {
    console.error('找不到对应的行数据, uniqueKey:', row.uniqueKey);
    return;
  }

  const formRefName = 'formRef_' + targetPrescriptionId + '_' + actualIndex;
  let formRef = proxy.$refs[formRefName];

  // 如果 formRef 是数组，取第一个元素
  if (Array.isArray(formRef)) {
    formRef = formRef[0];
  }

  if (!formRef || typeof formRef.validateField !== 'function') {
    console.log('handleEnter - 找不到表单引用或方法:', formRefName, 'formRef:', formRef);
    return;
  }

  formRef.validateField(currentProp, (valid) => {
    if (valid) {
      const index = requiredProps.value.indexOf(currentProp);
      if (index === -1) return;
      // 跳转下一个或提交
      const nextIndex = index + 1;
      if (nextIndex < requiredProps.value.length) {
        setTimeout(() => {
          const nextProp = requiredProps.value[nextIndex];
          // 确保只聚焦当前行的输入框
          inputRefs.value[actualIndex]?.[nextProp]?.focus();
        }, 100);
      } else {
        handleSaveSign(row, actualIndex, targetPrescriptionId);
      }
    }
  });
};

function escKeyListener(e) {
  if (e.key === 'Escape') {
    if (isAdding.value == true) {
      let index;
      if (expandOrder.value.length > 0) {
        index = prescriptionList.value.findIndex((item) => item.uniqueKey == expandOrder.value[0]);
      }
      if (index == 0) {
        updateExpandOrder([]);
      }
      prescriptionList.value.shift();
      isAdding.value = false;
      getGroupMarkers(); // 删除行会出现组号混乱的情况，所以这里重新更新标记
    }
  }
}

// 签退
function handleSingOut(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  let requestIdList = prescriptionList.value
    .filter((item) => {
      return item.statusEnum == 2;
    })
    .map((item) => {
      return item.requestId;
    });
  if (requestIdList.length == 0) {
    proxy.$modal.msgWarning('请选择已签发医嘱撤回');
    return;
  }
  singOut(requestIdList).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess('操作成功');
      getListInfo(false);
    }
  });
  prescriptionRef.value.clearSelection();
}

function handleGroupId(paramList) {
  updateGroupId(paramList);
}

// 组合
function combination(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  console.log(groupIndexList.value);

  if (groupIndexList.value.length <= 1) {
    proxy.$modal.msgWarning('至少选择两项');
    return;
  }
  // 相同分组用法需要相同
  let uniqueValues = new Set();
  // 相同分组诊断需要相同
  let uniqDiagnosis = new Set();
  // 相同状态
  let statusEnum = new Set();
  let status = false;
  selectRows.forEach((item) => {
    if (item.statusEnum == 2) {
      status = true;
    }
    uniqueValues.add(item.methodCode);
    uniqDiagnosis.add(item.diagnosisName);
    statusEnum.add(item.statusEnumf);
  });
  // 校验是否有已签发的医嘱
  if (status) {
    proxy.$modal.msgWarning('已签发医嘱不允许分组');
    return;
  }
  if (uniqueValues.size != 1) {
    proxy.$modal.msgWarning('同一分组药品用法必须相同');
    return;
  }
  if (uniqDiagnosis.size != 1) {
    proxy.$modal.msgWarning('同一分组诊断必须相同');
    return;
  }
  if (statusEnum.size != 1) {
    proxy.$modal.msgWarning('不同状态医嘱无法组合');
    return;
  }
  // 获取当前时间戳拼接组号做唯一组号
  let timestamp = Date.now().toString();
  let updateList = [];

  selectRows.forEach((item) => {
    // 直接更新表格数据中的groupId
    const index = prescriptionList.value.findIndex((row) => row.uniqueKey === item.uniqueKey);
    if (index !== -1) {
      prescriptionList.value[index].groupId = timestamp + groupIndex.value;
    }
    updateList.push({
      requestId: item.requestId,
      groupId: timestamp + groupIndex.value,
    });
  });
  if (selectRows[0].statusEnum == 1 && selectRows[0].requestId) {
    // 更新组号
    handleGroupId({ groupList: updateList });
  }
  prescriptionRef.value.clearSelection();
  getGroupMarkers(); // 更新标记
}

// 拆组
function split(prescriptionId) {
  // 如果传入了处方ID，先切换到该处方
  if (prescriptionId && prescriptionId !== currentPrescriptionId.value) {
    switchToActivePrescription(prescriptionId);
  }

  if (groupIndexList.value.length < 1) {
    proxy.$modal.msgWarning('至少选择一项');
    return;
  }
  // 校验是否包含已签发的医嘱
  if (selectRows.some((row) => row.statusEnum === 2)) {
    proxy.$modal.msgWarning('已签发医嘱不允许拆组');
    return;
  }
  if (selectRows.length === 0) {
    proxy.$modal.msgWarning('请选择已分组的医嘱');
    return;
  }

  // 构建最终要更新的列表
  let updateList = [];
  selectRows.forEach((item) => {
    // 直接更新表格数据中的groupId
    const index = prescriptionList.value.findIndex((row) => row.uniqueKey === item.uniqueKey);
    if (index !== -1) {
      prescriptionList.value[index].groupId = undefined;
    }
    updateList.push({
      requestId: item.requestId,
      groupId: null,
    });
  });
  if (selectRows[0].statusEnum == 1 && selectRows[0].requestId) {
    // 更新组号
    handleGroupId({ groupList: updateList });
  }
  prescriptionRef.value.clearSelection();
  // 更新分组标记
  getGroupMarkers();
  proxy.$modal.msgSuccess('拆组成功');
}
// 分组标记处理
function getGroupMarkers() {
  // 初始化所有行的 groupIcon 为 null
  prescriptionList.value.forEach((item) => {
    item.groupIcon = null;
  });

  // 创建一个映射来存储每个 groupId 对应的行索引
  const groupMap = {};

  // 遍历处方列表，按 groupId 分组（忽略无 groupId 的项）
  prescriptionList.value.forEach((item, index) => {
    if (!item.groupId) {
      return;
    }

    if (!groupMap[item.groupId]) {
      groupMap[item.groupId] = [];
    }
    groupMap[item.groupId].push(index);
  });

  // 为每个组设置 groupIcon
  Object.values(groupMap).forEach((indices) => {
    // 只有当组内元素大于1个时才需要显示分组标记
    if (indices.length > 1) {
      indices.forEach((index, i) => {
        if (i === 0) {
          // 第一行
          prescriptionList.value[index].groupIcon = '┏';
        } else if (i === indices.length - 1) {
          // 最后一行
          prescriptionList.value[index].groupIcon = '┗';
        } else {
          // 中间行
          prescriptionList.value[index].groupIcon = '┃';
        }
      });
    }
  });
}

// 计算总价
function calculateTotalPrice(row, index) {
  nextTick(() => {
    if (row.adviceType == 3) {
      row.totalPrice = (row.unitPrice * row.quantity).toFixed(6);
    } else {
      if (row.unitCode == row.minUnitCode) {
        row.totalPrice = (row.minUnitPrice * row.quantity).toFixed(6);
      } else {
        row.totalPrice = (row.unitPrice * row.quantity).toFixed(6);
      }
    }
  });
}

// 单位切换时 自动计算对应单位的总量
function convertValues(row, index) {
  nextTick(() => {
    let code = row.unitCodeList.filter((item) => {
      return item.value == row.doseUnitCode;
    })[0];

    if (!code) {
      console.warn('convertValues: 找不到对应的单位代码');
      return;
    }

    switch (code.type) {
      case 'dose':
        row.dose = row.doseQuantity * row.unitConversionRatio;
        break;
      case 'minUnit':
        row.dose = row.doseQuantity;
        break;
      case 'unit':
        row.dose = row.doseQuantity / row.partPercent;
        break;
    }
  });
  // calculateTotalAmount(row, index);
}

// 单次剂量数量改变时自动计算总量
function convertDoseValues(row, index) {
  nextTick(() => {
    let code = row.unitCodeList.filter((item) => {
      return item.value == row.doseUnitCode;
    })[0];

    if (!code) {
      console.warn('convertDoseValues: 找不到对应的单位代码');
      return;
    }

    switch (code.type) {
      case 'dose':
        row.doseQuantity = row.dose / row.unitConversionRatio;
        break;
      case 'minUnit':
        row.doseQuantity = row.dose;
        break;
      case 'unit':
        row.doseQuantity = row.dose * row.partPercent;
        break;
    }
  });
  // calculateTotalAmount(row, index);
}

// 总量计算,仅适用只有两种单位的情况
function calculateTotalAmount(row, index) {
  nextTick(() => {
    // 项目为西药或中成药时
    if (row.adviceType != 1 && row.adviceType != 2) {
      return;
    }

    // 情况1: 根据用药天数和频次计算
    if (row.rateCode && row.dispensePerDuration) {
      const count = calculateQuantityByDays(row.rateCode, row.dispensePerDuration);
      if (!count) return;

      let quantity;
      if (row.unitCode == row.minUnitCode) {
        quantity = calculateQuantityBySplitType(row.partAttributeEnum, row.doseQuantity, count);
        row.quantity = quantity;
        row.totalPrice = (quantity * row.minUnitPrice).toFixed(2);
      } else {
        quantity = calculateQuantity(
          row.partAttributeEnum,
          row.doseQuantity,
          count,
          row.partPercent
        );
        row.quantity = quantity;
        row.totalPrice = (quantity * row.unitPrice).toFixed(2);
      }
      return;
    }

    // 情况2: 中成药兼容旧逻辑
    if (row.adviceType == 2) {
      if (row.partPercent == 1) {
        row.totalPrice = row.quantity * row.unitPrice;
      } else {
        const unitInfo = row.unitCodeList?.find((k) => k.value == row.unitCode);
        if (unitInfo) {
          if (unitInfo.type == 'unit') {
            row.totalPrice = row.quantity * row.unitPrice;
          } else {
            row.totalPrice = (row.quantity * row.minUnitPrice).toFixed(2);
          }
        }
      }
      return;
    }

    // 情况3: 医生先填总量
    if (row.quantity) {
      if (row.unitCode == row.minUnitCode) {
        prescriptionList.value[index].totalPrice = (row.quantity * row.minUnitPrice).toFixed(6);
      } else {
        prescriptionList.value[index].totalPrice = (row.quantity * row.unitPrice).toFixed(6);
      }
    }
  });
}


/**
 * 根据门诊拆分类型计算总药量
 *
 * @param type 门诊拆分类型
 * @param dose 单次剂量 最小单位
 * @param count 用药频次和用药天数计算出的总数
 */
function calculateQuantityBySplitType(type, dose, count) {
  switch (type) {
    case 1: // 门诊按最小单位每次量向上取整
      return Math.ceil(dose) * count;
    case 2: // 门诊按包装单位不可拆分
      return Math.ceil(dose * count);
    case 3: // 门诊按最小单位总量向上取整
      return Math.ceil(dose * count);
    case 4: // 门诊按包装单位每次量向上取整
      return Math.ceil(dose) * count;
  }
}

/**
 * 根据门诊拆分类型计算总药量
 *
 * @param type 门诊拆分类型
 * @param dose 单次剂量 最小单位
 * @param count 用药频次和用药天数计算出的总数
 */
function calculateQuantity(type, dose, count, partPercent) {
  switch (type) {
    case 1: // 门诊按最小单位每次量向上取整
      return Math.ceil(dose / partPercent) * count;
    case 2: // 门诊按包装单位不可拆分
      return Math.ceil(dose * count);
    case 3: // 门诊按最小单位总量向上取整
      return Math.ceil((dose / partPercent) * count);
    case 4: // 门诊按包装单位每次量向上取整
      return Math.ceil(dose) * count;
  }
}

// 处方列表按照组号排序，后端已经将未签发的显示在上边，此处只处理未签发的处方
function sortPrescriptionList() {
  prescriptionList.value.sort((a, b) => {
    if (a.statusEnum == 1 && b.statusEnum == 1) {
      // 如果 a 和 b 都有 groupId，则按 groupId 升序排列
      if (a.groupId !== undefined && b.groupId !== undefined) {
        return a.groupId - b.groupId;
      }
      // 如果 a 有 groupId 而 b 没有，则 a 排在前面
      else if (a.groupId !== undefined && b.groupId === undefined) {
        return -1;
      }
      // 如果 a 没有 groupId 而 b 有，则 b 排在前面
      else if (a.groupId === undefined && b.groupId !== undefined) {
        return 1;
      }
      // 如果 a 和 b 都没有 groupId，则保持原顺序
      else {
        return 0;
      }
    }
  });
}

// 获取全部选中行
// function getSelectRows() {
//   return prescriptionList.value.filter((item) => item.check);
// }

// 获取指定处方的全选状态
function getCheckAllState(prescriptionId) {
  const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];
  if (prescriptionData.length === 0) return false;
  return prescriptionData.every(item => item.check === true);
}

// 处理处方的全选/取消全选
function handleCheckAllChange(value, prescriptionId) {
  const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];
  // 更新该处方所有行的选中状态
  prescriptionData.forEach((item) => {
    item.check = value;
  });
  // 更新存储的数据
  allPrescriptionsData.value[prescriptionId] = [...prescriptionData];
  // 如果当前显示的就是这个处方，同步到 prescriptionList
  if (currentPrescriptionId.value === prescriptionId) {
    prescriptionList.value = [...prescriptionData];
  }
}

// 处理行checkbox选中
function handleCheckBoxChange(value, index, row, prescriptionId) {
  // 获取对应处方的数据
  const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];

  // 选中将当前行索引记录下来，取消将当前行索引删除
  if (value) {
    if (!groupIndexList.value.includes(index)) {
      groupIndexList.value.push(index);
    }
  } else {
    const indexPos = groupIndexList.value.indexOf(index);
    if (indexPos > -1) {
      groupIndexList.value.splice(indexPos, 1);
    }
  }

  // 如果选中或取消行有组号，将全部相同组号的行全部选中，并记录或删除这些行的索引
  if (row.groupId) {
    // 获取组号相同行（在当前处方内）
    let sameGroupIdList = prescriptionData.filter((item) => {
      return item.groupId == row.groupId;
    });
    // 如果只有一个组号的情况不做处理
    if (sameGroupIdList.length == 1) {
      return;
    } else {
      sameGroupIdList.forEach((item) => {
        // 排除掉当前选中行
        if (row.uniqueKey != item.uniqueKey) {
          // 同步选中状态
          let currentIndex = prescriptionData.findIndex((k) => k.uniqueKey == item.uniqueKey);
          if (currentIndex !== -1) {
            prescriptionData[currentIndex].check = value;
            if (value) {
              if (!groupIndexList.value.includes(currentIndex)) {
                groupIndexList.value.push(currentIndex);
              }
            } else {
              const indexPos = groupIndexList.value.indexOf(currentIndex);
              if (indexPos > -1) {
                groupIndexList.value.splice(indexPos, 1);
              }
            }
          }
        }
      });
      // 更新存储的数据
      allPrescriptionsData.value[prescriptionId] = [...prescriptionData];
      // 如果当前显示的就是这个处方，同步到 prescriptionList
      if (currentPrescriptionId.value === prescriptionId) {
        prescriptionList.value = [...prescriptionData];
      }
    }
  }
}

// 校验每个组号数量是否大于5和对应分组金额是否大于500
function validateGroups(saveList) {
  // 获取到全部组号和对应的金额
  const groups = saveList
    .filter((item) => item.groupId != null && item.groupId !== '') // 过滤掉 groupId 为空或空字符串的项
    .map((item) => ({
      groupId: item.groupId,
      totalPrice: item.totalPrice,
    }));
  // 计算每个组号数量,以及每组金额
  const counts = {};
  groups.forEach((item) => {
    const groupId = item.groupId;
    const totalPrice = Number(item.totalPrice);
    if (!counts[groupId]) {
      counts[groupId] = {
        count: 0,
        totalPrice: 0,
      };
    }
    counts[groupId].groupId = groupId;
    counts[groupId].count++;
    counts[groupId].totalPrice += totalPrice;
  });

  // 获取组数大于5的组号
  const countStr = Object.values(counts)
    .filter((group) => {
      return group.count > 5;
    })
    .map((group) => group.groupId);
  // 获取总金额大于500的组号
  const totalStr = Object.values(counts)
    .filter((group) => {
      return group.totalPrice > 500;
    })
    .map((group) => group.groupId);
  if (countStr.length > 0) {
    proxy.$modal.msgWarning('分组"' + countStr + '"数量超出限制');
    return false;
  } else if (totalStr.length > 0) {
    proxy.$modal.msgWarning('分组"' + totalStr + '"金额总和超出限制');
    return false;
  }
  return true;
}

// ==================== 西药处方管理相关方法 ====================

/**
 * 新增西药处方
 * 自动引入诊断和费用性质
 */
async function handleAddWesternPrescription() {
  // 检查患者信息是否完整
  if (!props.patientInfo || !props.patientInfo.encounterId) {
    proxy.$modal.msgWarning('患者信息不完整，无法创建处方');
    return;
  }

  prescriptionCounter.value++;
  const newPrescriptionId = `prescription_${Date.now()}_${prescriptionCounter.value}`;

  // 如果诊断列表为空，先加载诊断信息
  if (!diagnosisList.value || diagnosisList.value.length === 0) {
    try {
      const diagnosisRes = await getDiagnosisInfo();
      console.log('诊断信息加载完成:', diagnosisRes);
      // 确保诊断列表已更新
      if (diagnosisRes && diagnosisRes.data) {
        diagnosisList.value = diagnosisRes.data || [];
      }
    } catch (error) {
      console.error('加载诊断信息失败:', error);
      // 即使加载失败，也继续创建处方，只是不自动引入诊断
    }
  }

  // 如果费用性质列表为空，先加载费用性质信息
  if (!contractList.value || contractList.value.length === 0) {
    try {
      const res = await getContract({ encounterId: props.patientInfo.encounterId });
      console.log('费用性质信息加载完成:', res);
      if (res && res.data) {
        contractList.value = res.data;
      }
    } catch (error) {
      console.error('加载费用性质失败:', error);
      // 即使加载失败，也继续创建处方，只是不自动引入费用性质
    }
  }

  // 再次确认数据已加载
  console.log('数据加载检查 - 诊断列表:', diagnosisList.value?.length || 0, diagnosisList.value);
  console.log('数据加载检查 - 费用性质列表:', contractList.value?.length || 0, contractList.value);

  // 自动引入诊断：优先使用全局变量，否则从诊断列表中获取第一个主诊断，再否则获取第一个诊断
  let autoConditionDefinitionId = conditionDefinitionId.value;
  console.log('自动引入诊断 - 当前全局诊断ID:', autoConditionDefinitionId);
  console.log('自动引入诊断 - 诊断列表:', diagnosisList.value);

  if (!autoConditionDefinitionId && diagnosisList.value && diagnosisList.value.length > 0) {
    // 优先获取主诊断
    const mainDiagnosis = diagnosisList.value.find(item => item.maindiseFlag == 1);
    if (mainDiagnosis) {
      autoConditionDefinitionId = mainDiagnosis.definitionId;
      console.log('自动引入诊断 - 找到主诊断:', mainDiagnosis);
      // 同时更新全局变量
      conditionDefinitionId.value = autoConditionDefinitionId;
      conditionId.value = mainDiagnosis.conditionId;
      encounterDiagnosisId.value = mainDiagnosis.encounterDiagnosisId;
      diagnosisName.value = mainDiagnosis.name;
    } else {
      // 如果没有主诊断，使用第一个诊断
      autoConditionDefinitionId = diagnosisList.value[0].definitionId;
      console.log('自动引入诊断 - 使用第一个诊断:', diagnosisList.value[0]);
      // 同时更新全局变量
      conditionDefinitionId.value = autoConditionDefinitionId;
      conditionId.value = diagnosisList.value[0].conditionId;
      encounterDiagnosisId.value = diagnosisList.value[0].encounterDiagnosisId;
      diagnosisName.value = diagnosisList.value[0].name;
    }
  } else if (!autoConditionDefinitionId) {
    console.warn('自动引入诊断 - 无法自动引入：诊断列表为空或全局变量未设置');
  }

  // 自动引入费用性质：优先使用全局变量，否则从费用性质列表中获取第一个，再否则使用患者信息中的费用性质
  let autoAccountId = accountId.value;
  console.log('自动引入费用性质 - 当前全局费用性质ID:', autoAccountId);
  console.log('自动引入费用性质 - 费用性质列表:', contractList.value);
  console.log('自动引入费用性质 - 患者信息中的费用性质:', props.patientInfo?.accountId);

  if (!autoAccountId) {
    if (contractList.value && contractList.value.length > 0) {
      autoAccountId = contractList.value[0].accountId;
      console.log('自动引入费用性质 - 从列表获取:', contractList.value[0]);
      // 同时更新全局变量
      accountId.value = autoAccountId;
    } else if (props.patientInfo && props.patientInfo.accountId) {
      autoAccountId = props.patientInfo.accountId;
      console.log('自动引入费用性质 - 从患者信息获取:', autoAccountId);
      // 同时更新全局变量
      accountId.value = autoAccountId;
    } else {
      console.warn('自动引入费用性质 - 无法自动引入：费用性质列表为空且患者信息中也没有');
    }
  }

  // 创建处方对象，确保诊断和费用性质被正确设置
  const newPrescription = reactive({
    id: newPrescriptionId,
    name: `西药方${prescriptionCounter.value}`,
    prescriptionNo: '', // 处方单号码，保存时由后端生成
    conditionDefinitionId: autoConditionDefinitionId || undefined, // 诊断（自动引入）
    accountId: autoAccountId || undefined, // 费用性质（自动引入）
    expandOrder: [], // 展开的行
  });

  westernPrescriptions.value.push(newPrescription);
  allPrescriptionsData.value[newPrescriptionId] = []; // 初始化空数据

  console.log('新增西药处方完成:', {
    prescriptionId: newPrescriptionId,
    prescription: newPrescription,
    autoConditionDefinitionId: autoConditionDefinitionId,
    autoAccountId: autoAccountId,
    diagnosisListLength: diagnosisList.value?.length || 0,
    contractListLength: contractList.value?.length || 0,
    diagnosisList: diagnosisList.value,
    contractList: contractList.value
  });

  // 使用 nextTick 确保 Vue 响应式更新，然后再次检查并更新处方对象
  await nextTick();

  // 确保处方对象中的诊断和费用性质已正确设置（使用响应式对象直接更新）
  if (autoConditionDefinitionId) {
    newPrescription.conditionDefinitionId = autoConditionDefinitionId;
    console.log('已设置诊断ID到处方对象:', autoConditionDefinitionId);
  }
  if (autoAccountId) {
    newPrescription.accountId = autoAccountId;
    console.log('已设置费用性质ID到处方对象:', autoAccountId);
  }

  // 再次等待一个tick，确保视图更新
  await nextTick();
  console.log('最终处方对象:', {
    id: newPrescription.id,
    conditionDefinitionId: newPrescription.conditionDefinitionId,
    accountId: newPrescription.accountId
  });
}

/**
 * 切换到活跃处方（用于操作前的上下文切换）
 */
function switchToActivePrescription(prescriptionId) {
  // 保存当前处方的数据和展开状态
  if (currentPrescriptionId.value) {
    allPrescriptionsData.value[currentPrescriptionId.value] = [...prescriptionList.value];
    const currentPrescription = westernPrescriptions.value.find(p => p.id === currentPrescriptionId.value);
    if (currentPrescription) {
      currentPrescription.expandOrder = [...expandOrder.value];
    }
  }

  // 切换到新处方
  currentPrescriptionId.value = prescriptionId;

  // 加载新处方的数据
  if (allPrescriptionsData.value[prescriptionId]) {
    prescriptionList.value = [...allPrescriptionsData.value[prescriptionId]];
  } else {
    prescriptionList.value = [];
    allPrescriptionsData.value[prescriptionId] = [];
  }

  // 恢复该处方的展开状态、诊断和费用性质
  const prescription = westernPrescriptions.value.find(p => p.id === prescriptionId);
  if (prescription) {
    expandOrder.value = prescription.expandOrder || [];
    conditionDefinitionId.value = prescription.conditionDefinitionId || conditionDefinitionId.value;
    accountId.value = prescription.accountId || accountId.value;
  }

  // 重新计算总金额
  handleTotalAmount();

  console.log('切换到处方:', prescriptionId, '数据数量:', prescriptionList.value.length);
}

/**
 * 将当前处方数据同步回存储
 */
function syncCurrentPrescriptionData() {
  if (currentPrescriptionId.value) {
    allPrescriptionsData.value[currentPrescriptionId.value] = [...prescriptionList.value];
  }
}

/**
 * 更新展开行状态（同时更新全局和当前处方的 expandOrder）
 */
function updateExpandOrder(keys) {
  expandOrder.value = Array.isArray(keys) ? keys : [];

  // 同步到当前处方
  const currentPrescription = westernPrescriptions.value.find(p => p.id === currentPrescriptionId.value);
  if (currentPrescription) {
    currentPrescription.expandOrder = Array.isArray(keys) ? [...keys] : [];
  }
}

/**
 * 关闭处方（删除西药方）
 * 控制规则：
 * 1. 西药方有已保存的数据不能删除
 * 2. 西药方已签发和已收费不能删除
 * 3. 西药方只有在待保存和无数据的情况才能删除
 */
function handleClosePrescription(prescriptionId) {
  // 检查该处方是否有数据
  const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];
  const hasData = prescriptionData.length > 0;

  if (!hasData) {
    // 如果没有数据，直接删除
    doClosePrescription(prescriptionId);
    return;
  }

  // 检查是否有已保存的数据（statusEnum == 1 && (requestId || isSaved)）
  const hasSavedData = prescriptionData.some(item => {
    return item.statusEnum == 1 && (item.requestId || item.isSaved);
  });

  if (hasSavedData) {
    proxy.$modal.msgWarning('西药方有已保存的数据，不能删除');
    return;
  }

  // 检查是否有已签发的数据（statusEnum == 2）
  const hasIssuedData = prescriptionData.some(item => {
    return item.statusEnum == 2;
  });

  if (hasIssuedData) {
    proxy.$modal.msgWarning('西药方已签发，不能删除');
    return;
  }

  // 检查是否有已收费的数据（chargeStatus == 5 表示已收费）
  const hasChargedData = prescriptionData.some(item => {
    return item.chargeStatus == 5;
  });

  if (hasChargedData) {
    proxy.$modal.msgWarning('西药方已收费，不能删除');
    return;
  }

  // 如果所有数据都是待保存状态（statusEnum == 1 && !requestId && !isSaved）或无数据，可以删除
  // 提示用户确认
  proxy.$modal.confirm('确定要删除该西药方吗？').then(() => {
    doClosePrescription(prescriptionId);
  }).catch(() => {
    console.log('取消删除西药方');
  });
}

/**
 * 执行关闭处方操作
 */
function doClosePrescription(prescriptionId) {
  const index = westernPrescriptions.value.findIndex(p => p.id === prescriptionId);
  if (index === -1) return;

  // 删除处方
  westernPrescriptions.value.splice(index, 1);
  delete allPrescriptionsData.value[prescriptionId];

  console.log('关闭处方:', prescriptionId);
}

/**
 * 获取指定处方的总金额
 */
function getPrescriptionTotalAmount(prescriptionId) {
  const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];
  const total = prescriptionData.reduce((sum, item) => {
    return sum + (Number(item.totalPrice) || 0);
  }, 0);
  return total.toFixed(2);
}


/**
 * 获取已签发的处方单信息（用于处方单预览）
 * 返回已签发的药品处方单数据（statusEnum == 2 且 adviceType == 1 或 2）
 */
function getSignedPrescriptionInfo() {
  const signedPrescriptions = [];

  // 遍历所有处方
  Object.keys(allPrescriptionsData.value).forEach(prescriptionId => {
    const prescriptionData = allPrescriptionsData.value[prescriptionId] || [];
    const prescription = westernPrescriptions.value.find(p => p.id === prescriptionId);

    if (!prescription) return;

    // 筛选已签发的药品（西药和中成药）
    const signedMedicines = prescriptionData.filter(item =>
      item.statusEnum === 2 && (item.adviceType === 1 || item.adviceType === 2)
    );

    if (signedMedicines.length > 0) {
      // 构建处方单信息
      const prescriptionInfo = {
        prescriptionNo: prescription.name || `处方${prescriptionId}`,
        patientName: props.patientInfo?.patientName || '',
        requestTime: new Date().toISOString(),
        conditionDefinitionName: diagnosisName.value || '',
        prescriptionInfoDetail: signedMedicines.map(item => ({
          requestId: item.requestId,
          adviceName: item.adviceName || '',
          volume: item.volume || '',
          quantity: item.quantity || '',
          unitCode_dictText: item.unitCode_dictText || '',
          lotNumber: item.lotNumber || '',
          methodCode_dictText: item.methodCode_dictText || '',
          dose: item.dose || '',
          doseUnitCode_dictText: item.doseUnitCode_dictText || '',
          rateCode_dictText: item.rateCode_dictText || ''
        }))
      };

      signedPrescriptions.push(prescriptionInfo);
    }
  });

  return signedPrescriptions;
}

defineExpose({ getListInfo, getDiagnosisInfo, getSignedPrescriptionInfo });
</script>

<style lang="scss" scoped>
:deep(.el-table__expand-icon) {
  display: none !important;
}

.medicine-title {
  font-size: 16px;
  font-weight: 600;
  min-width: 280px;
  display: inline-block;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
  white-space: nowrap;
}

.medicine-info {
  font-size: 15px;
  font-weight: 600;
  color: #606266;
  white-space: nowrap;
}

.form-group {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #fff;
  padding: 6px 10px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
}

/* 调整element组件默认间距 */
// .el-select,
// .el-input-number {
//   margin-right: 0 !important;
// }

.el-input-number .el-input__inner {
  text-align: center;
}

.el-table__cell .el-form-item--default {
  margin-bottom: 0px;
}

/* 优化滚动条样式 - 支持水平和垂直滚动 */
.prescription-scroll-container {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
  /* 确保内容可以超出容器宽度，触发水平滚动 */
  overflow-x: auto;
  overflow-y: auto;
}

/* 垂直滚动条样式 */
.prescription-scroll-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.prescription-scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.prescription-scroll-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.prescription-scroll-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 水平滚动条样式 */
.prescription-scroll-container::-webkit-scrollbar:horizontal {
  height: 8px;
}

/* 确保表格可以水平滚动 */
.prescription-scroll-container .el-table {
  min-width: 100%;
}

.prescription-scroll-container .el-table__body-wrapper {
  overflow-x: auto;
}

/* 确保标题栏删除按钮可见 */
.prescription-header {
  position: relative;
  z-index: 1;
}

.prescription-header .el-button {
  position: relative;
  z-index: 10;
  visibility: visible !important;
  display: inline-block !important;
  opacity: 1 !important;
}
</style>
