<template>
  <div style="width: 100%">
    <div style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAddPrescription()" :disabled="false">
        新增
      </el-button>
      <el-button type="primary" @click="handleSaveBatch()" :disabled="false"> 保存 </el-button>
      <el-button type="primary" @click="handleSave()" :disabled="false"> 签发 </el-button>
      <el-button type="warning" plain @click="handleSingOut()" :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()" :disabled="false"> 组合 </el-button>
      <el-button type="default" @click="split()" :disabled="false"> 拆组 </el-button>
      <el-button type="danger" plain @click="handleDelete()" :disabled="false"> 删除 </el-button>
      <span class="descriptions-item-label"> 诊断： </span>
      <el-select v-model="conditionDefinitionId" placeholder="诊断" style="width: 180px">
        <el-option
          v-for="item in diagnosisList"
          :key="item.conditionId"
          :label="item.name"
          :value="item.definitionId"
          @click="handleDiagnosisChange(item)"
        />
      </el-select>
      <span class="descriptions-item-label"> 费用性质： </span>
      <el-select v-model="accountId" placeholder="费用性质" style="width: 180px">
        <el-option
          v-for="item in contractList"
          :key="item.accountId"
          :label="item.contractName"
          :value="item.accountId"
        />
      </el-select>
      <span class="descriptions-item-label">
        合计金额：{{ totalAmount ? totalAmount.toFixed(2) : 0 }}元
      </span>
      <el-button type="primary" style="float: right" @click="refresh()" :disabled="false">
        刷新
      </el-button>
    </div>
    <el-table
      max-height="650"
      ref="prescriptionRef"
      :data="prescriptionList"
      row-key="uniqueKey"
      border
      @cell-click="clickRow"
      @row-dblclick="clickRowDb"
      v-loading="loading"
      :expand-row-keys="expandOrder"
    >
      <el-table-column type="expand" width="1" style="width: 0">
        <template #default="scope">
          <el-form :model="scope.row" :rules="rowRules" :ref="'formRef' + 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: 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)"
                      />
                    </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)"
                      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-label="1"
                      :false-label="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)"
                      />
                    </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)"
                      />
                    </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)"
                        @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)">
                    确定
                  </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)"
                      />
                    </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)"
                      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-label="1"
                      :false-label="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)"
                      />
                    </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)"
                      />
                    </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)"
                        @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)">
                    确定
                  </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)"
                        @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)"
                        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 ? scope.row.totalPrice + ' 元' : '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)">
                    确定
                  </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
            v-model="checkAll"
            @change="
              (value) => {
                prescriptionList.forEach((item, index) => {
                  groupIndexList.push(index);
                  item.check = value;
                });
              }
            "
          />
        </template>
        <template #default="scope">
          <el-checkbox
            v-model="scope.row.check"
            @dblclick.stop=""
            placeholder=""
            @change="(value) => handleCheckBoxChange(value, scope.$index, scope.row)"
          />
        </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="getRowDisabled(scope.row)">
            <el-select
              v-model="scope.row.adviceType"
              :ref="'adviceTypeRef' + 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' + scope.$index"
                  v-model="scope.row.adviceName"
                  placeholder="请选择项目"
                  @input="handleChange"
                  @click="handleFocus(scope.row, scope.$index)"
                  @keyup.enter.stop="handleFocus(scope.row, scope.$index)"
                  @keydown="handleInputKeyDown(scope.row, $event)"
                  @blur="handleBlur(scope.row)"
                  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" 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>
    <OrderGroupDrawer
      ref="orderFroupRef"
      :diagnosis="diagnosisInfo"
      :organizationId="props.patientInfo.orgId"
      @useOrderGroup="handleSaveGroup"
    />
    <PrescriptionHistory
      ref="prescriptionHistoryRef"
      :diagnosis="diagnosisInfo"
      :patientInfo="props.patientInfo"
      @userPrescriptionHistory="handleSaveHistory"
    />
  </div>
</template>
      
<script setup>
import {
  getDiagnosisDefinitionList,
  savePrescription,
  getEncounterDiagnosis,
  getPrescriptionList,
  getOrgTree,
  savePrescriptionSign,
  singOut,
  saveEmr,
  getEmrDetail,
  updateGroupId,
  getContract,
  getAdviceBaseInfo,
  getActivityBindDevice,
} from '../api';
import adviceBaseList from '../adviceBaseList.vue';
import { computed, getCurrentInstance, nextTick, watch, unref } from 'vue';
import { calculateQuantityByDays, formatNumber } from '@/utils/his';
import OrderGroupDrawer from './orderGroupDrawer';
import PrescriptionHistory from './prescriptionHistory';
import Decimal from 'decimal.js';
import useUserStore from '@/store/modules/user';
import { ElMessageBox } from 'element-plus';

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 groupIndexList = ref([]);
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 prescriptionRef = ref();
const expandOrder = ref([]); //目前的展开行
const stockList = ref([]);
const contractList = ref([]);
const conditionId = ref('');
const accountId = ref('');
const checkAll = ref(false);
const { proxy } = getCurrentInstance();
const inputRefs = ref({}); // 存储输入框实例，格式: { rowIndex: { fieldName: el } }
const requiredProps = ref([]); // 存储必填项 prop 顺序
const totalAmount = ref(0);
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: '',
  },
]);
onMounted(() => {
  document.addEventListener('keydown', escKeyListener);
});

onBeforeUnmount(() => {
  document.removeEventListener('keydown', escKeyListener);
});
watch(
  () => expandOrder.value,
  (newValue) => {
    if (newValue.length > 0) {
      nextTick(() => {
        const index = prescriptionList.value.findIndex((row) => row.uniqueKey === newValue[0]);
        const items = proxy.$refs['formRef' + index]?.$el?.querySelectorAll('[data-prop]');
        requiredProps.value = Array.from(items).map((item) => item.dataset.prop);
        console.log(requiredProps.value, 'requiredProps.value');
      });
    } else {
      requiredProps.value = {};
    }
  }
);
watch(
  () => prescriptionList.value,
  (newVlaue) => {
    if (newVlaue && newVlaue.length > 0) {
      console.log(prescriptionList.value, 'prescriptionList.value');
      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 accumulator + (Number(currentRow.totalPrice) || 0);
    } else {
      return 0;
    }
  }, 0);
}
getList();
function getList() {
  getDiagnosisDefinitionList(queryParams.value).then((res) => {
    // prescriptionList.value = res.data.records;
    total.value = res.data.total;
  });
}
function refresh() {
  getListInfo(false);
}
function getListInfo(addNewRow) {
  isAdding.value = false;
  getPrescriptionList(props.patientInfo.encounterId).then((res) => {
    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 || '';

      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正确设置
      };
    });
    groupMarkers.value = getGroupMarkers(prescriptionList.value); // 更新标记
    if (props.activeTab == 'prescription' && addNewRow) {
      handleAddPrescription();
    }
  });
  getContract({ encounterId: props.patientInfo.encounterId }).then((res) => {
    contractList.value = res.data;
  });
  accountId.value = props.patientInfo.accountId;
}

function getDiagnosisInfo() {
  getEncounterDiagnosis(props.patientInfo.encounterId).then((res) => {
    diagnosisList.value = res.data;
    let diagnosisInfo = diagnosisList.value.filter((item) => {
      return item.maindiseFlag == 1;
    });
    diagnosisInfo.value = diagnosisInfo[0];
    conditionDefinitionId.value = diagnosisInfo[0].definitionId;
    conditionId.value = diagnosisInfo[0].conditionId;
    encounterDiagnosisId.value = diagnosisInfo[0].encounterDiagnosisId;
    diagnosisName.value = diagnosisInfo[0].name;
  });
}

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

// 新增医嘱
function handleAddPrescription() {
  if (diagnosisList.value.length == 0) {
    proxy.$modal.msgWarning('请先保存诊断后再开立医嘱');
    return;
  }
  if (isAdding.value) {
    proxy.$modal.msgWarning('请先保存当前医嘱');
    return;
  }
  isAdding.value = true;
  // 重置查询参数
  adviceQueryParams.value = {
    searchKey: '',
    adviceType: '',
    categoryCode: ''
  };

  // 在数组最前方添加一行，让新增行显示在最上边
  prescriptionList.value.unshift({
    uniqueKey: nextId.value++,
    showPopover: false,
    check: false,
    isEdit: true,
    statusEnum: 1,
  });
  groupMarkers.value = getGroupMarkers(prescriptionList.value);
  nextTick(() => {
    proxy.$refs['adviceRef0'].focus();
  });
}

/**
 * 点击行赋值
 */
function clickRow(row) {
  emit('selectDiagnosis', row);
}

// 行双击打开编辑块，仅待发送的可编辑
function clickRowDb(row) {
  if (row.statusEnum == 1) {
    row = { ...row, ...JSON.parse(row.contentJson), uniqueKey: row.uniqueKey };
    row.isEdit = true;
    row.doseUnitCode == JSON.parse(JSON.stringify(row.minUnitCode));
    const index = prescriptionList.value.findIndex((item) => item.uniqueKey === row.uniqueKey);
    prescriptionList.value[index] = row;
    // 确保只有当前行展开，先清空数组再添加当前行的uniqueKey
    expandOrder.value = [];
    expandOrder.value.push(row.uniqueKey);
  }
}

function up(index, row) {}

function down(index, row) {}

function handleDiagnosisChange(item) {
  diagnosisName.value = item.name;
  conditionId.value = item.conditionId;
  encounterDiagnosisId.value = item.encounterDiagnosisId;
}

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) {
  // 立即关闭当前弹窗
  prescriptionList.value[rowIndex.value].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[rowIndex.value].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[rowIndex.value] = {
    ...prescriptionList.value[rowIndex.value],
    ...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[rowIndex.value];
      prescriptionList.value[rowIndex.value] = {
        ...currentRow
      };
    }
  });
  prescriptionList.value[rowIndex.value].orgId = undefined;
  prescriptionList.value[rowIndex.value].dose = undefined;
  prescriptionList.value[rowIndex.value].unitCodeList = unitCodeList.value;
  // prescriptionList.value[rowIndex.value].doseUnitCode =
  //   row.minUnitCode != row.unitCode ? row.minUnitCode : row.unitCode;
  // prescriptionList.value[rowIndex.value].minUnitCode = JSON.parse(JSON.stringify(row.doseUnitCode));
  prescriptionList.value[rowIndex.value].doseUnitCode = row.doseUnitCode;
  prescriptionList.value[rowIndex.value].minUnitCode = row.minUnitCode;
  prescriptionList.value[rowIndex.value].unitCode =
    row.partAttributeEnum == 1 ? row.minUnitCode : row.unitCode;
  prescriptionList.value[rowIndex.value].categoryEnum = row.categoryCode;
  // prescriptionList.value[rowIndex.value].doseUnitCode_dictText = row.minUnitCode_dictText;
  prescriptionList.value[rowIndex.value].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) {
      expandOrder.value = [];
      proxy.$modal.msgWarning('该项目无库存');
      return;
    }
    stockList.value = row.inventoryList.map((item, index) => {
      return { ...item, ...row.priceList[index] };
    });
    prescriptionList.value[rowIndex.value].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[rowIndex.value].lotNumber = stock.lotNumber;
      prescriptionList.value[rowIndex.value].inventoryId = stock.inventoryId;
      prescriptionList.value[rowIndex.value].locationId = stock.locationId;
      prescriptionList.value[rowIndex.value].unitPrice = stock.price;
      prescriptionList.value[rowIndex.value].unitTempPrice = stock.price;
      prescriptionList.value[rowIndex.value].minUnitPrice = new Decimal(stock.price)
        .div(row.partPercent)
        .toFixed(2);
      prescriptionList.value[rowIndex.value].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[rowIndex.value].unitPrice = price;
    prescriptionList.value[rowIndex.value].unitTempPrice = price;
    prescriptionList.value[rowIndex.value].minUnitPrice = price;
    prescriptionList.value[rowIndex.value].positionId = row.locationId;
    prescriptionList.value[rowIndex.value].positionName = row.locationId_dictText || row.positionName || '';
    // 耗材可能没有库存列表，设置为空数组
    prescriptionList.value[rowIndex.value].stockList = [];
    prescriptionList.value[rowIndex.value].inventoryList = [];
  } else {
    // 诊疗类型：执行科室默认逻辑：优先使用诊疗项目维护的所属科室，如果没有则使用开单科室
    const defaultOrgId = row.positionId || props.patientInfo.orgId;
    prescriptionList.value[rowIndex.value].orgId = defaultOrgId;
    prescriptionList.value[rowIndex.value].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[rowIndex.value].skinTestFlag = 1;
        prescriptionList.value[rowIndex.value].skinTestFlag_enumText = '是';
        // 展开订单并继续后续流程
        expandOrderAndFocus(key, row);
      })
      .catch((action) => {
        // 用户点击"否"或关闭，不勾选皮试字段
        prescriptionList.value[rowIndex.value].skinTestFlag = 0;
        prescriptionList.value[rowIndex.value].skinTestFlag_enumText = '否';
        // 展开订单并继续后续流程
        expandOrderAndFocus(key, row);
      });
  } else {
    // 不是皮试药品，直接展开订单
    expandOrderAndFocus(key, row);
  }
}

/**
 * 展开订单并聚焦输入框
 */
function expandOrderAndFocus(key, row) {
  // 确保只有当前行展开，先清空数组再添加当前行的uniqueKey
  expandOrder.value = [];
  expandOrder.value.push(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() {
  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];
    // 通过requestId判断是否已保存，如果选中项未保存 直接从数组中移除，如果已保存，调接口删除
    if (deleteItem.check && deleteItem.statusEnum == 1 && !deleteItem.requestId) {
      prescriptionList.value.splice(i, 1);
      sum++;
    } else if (deleteItem.check && deleteItem.statusEnum == 1 && deleteItem.requestId) {
      deleteList.push({
        requestId: deleteItem.requestId,
        dbOpType: '3',
        adviceType: deleteItem.adviceType,
      });
    }
  }
  handleEmrTreatment();
  expandOrder.value = [];
  isAdding.value = false;
  adviceQueryParams.value.adviceType = undefined;
  adviceQueryParams.value.categoryCode = undefined;
  if (sum == selectRow.length) {
    proxy.$modal.msgSuccess('删除成功');
    groupIndexList.value = [];
    return;
  }
  if (deleteList.length > 0) {
    savePrescription({ adviceSaveList: deleteList }).then((res) => {
      if (res.code == 200) {
        proxy.$modal.msgSuccess('删除成功');
        groupIndexList.value = [];
        getListInfo(false);
      }
    });
  } else {
    proxy.$modal.msgWarning('所选医嘱不可删除，请先撤回后再删除');
    return;
  }
  groupMarkers.value = getGroupMarkers(prescriptionList.value); // 删除行会出现组号混乱的情况，所以这里重新更新标记
}

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

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

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

  let validList = saveList.filter((item) => {
    return !item.requestId;
  });
  if (validList.length > 0) {
    proxy.$modal.msgWarning('存在未保存的医嘱，请先点击保存按钮后再执行签发');
    return;
  }
  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 == 3) {
        treatment += '[' + (index + 1) + ']' + '  ';
        treatment += 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 handleClickOutside(row, index) {
  nextTick(() => {
    handleSaveSign(row, index);
  });
}

function stockFormat(partPercent, unit, minUnit, quantity) {
  let a = quantity % partPercent;
  let b = Math.floor(quantity / partPercent);
  console.log(partPercent, unit, minUnit, quantity);

  if (a == 0) {
    return b + ' ' + unit;
  }
  return b + ' ' + unit + ' ' + a + ' ' + minUnit;
}

// 单行处方保存
function handleSaveSign(row, index) {
  proxy.$refs['formRef' + index].validate((valid) => {
    if (valid) {
      row.isEdit = false;
      isAdding.value = false;
      expandOrder.value = [];
      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,
        contentJson: undefined // 确保contentJson不被序列化
      };
      // 对中成药类型（2）特别处理，确保adviceName被正确保存
      if (row.adviceType == 2) {
        rowToSave.adviceName = row.adviceName; // 确保adviceName被显式设置
      }
      row.contentJson = JSON.stringify(rowToSave);
      // 恢复原始的adviceType供前端显示使用
      row.adviceType = row.adviceType;

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

function handleSaveBatch() {
  if (expandOrder.value.length > 0) {
    proxy.$modal.msgWarning('请先点击确定确认当前医嘱');
    return;
  }
  if (prescriptionList.value[0].isEdit && !prescriptionList.value[0].adviceType) {
    prescriptionList.value.shift();
    isAdding.value = false;
    expandOrder.value = [];
  }
  let saveList = prescriptionList.value
    .filter((item) => {
      return item.statusEnum == 1 && !item.requestId;
    })
    .map((item) => {
      return {
        ...item,
        dbOpType: item.requestId ? '2' : '1',
      };
    });
  if (saveList.length == 0) {
    proxy.$modal.msgWarning('当前没有可保存医嘱');
    return;
  }
  savePrescription({ adviceSaveList: saveList }).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess('保存成功');
          getListInfo(false);
          nextId.value = 1;
        }
      });
}

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

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

// 组套保存
function handleSaveGroup(orderGroupList) {
  // orderGroupList.map((item) => {
  //   item.patientId = props.patientInfo.patientId;
  //   item.encounterId = props.patientInfo.encounterId;
  //   item.accountId = accountId.value;
  //   item.dbOpType = item.requestId ? '2' : '1';
  //   item.minUnitQuantity = item.quantity * item.partPercent;
  //   item.conditionId = conditionId.value;
  //   item.conditionDefinitionId = conditionDefinitionId.value;
  //   item.encounterDiagnosisId = encounterDiagnosisId.value;
  //   item.contentJson = JSON.stringify(item);
  //   prescriptionList.value.push(item);
  // });
  // let paramList = orderGroupList.map((item) => {
  //   return item.adviceDefinitionId;
  // });
  // getAdviceBaseInfo({
  //   adviceDefinitionIdParamList: paramList.join(','),
  //   organizationId: props.patientInfo.orgId,
  // }).then((res) => {
  // getOrgList();
  orderGroupList.forEach((item, index) => {
    rowIndex.value = prescriptionList.value.length;
    setValue(item.orderDetailInfos);
    // let orderGroupValue = orderGroupList.find(
    //   (k) => k.adviceDefinitionId == item.adviceDefinitionId
    // );

    prescriptionList.value[rowIndex.value] = {
      ...prescriptionList.value[rowIndex.value],
      // ...orderGroupValue,
      uniqueKey: nextId.value++,
      patientId: props.patientInfo.patientId,
      encounterId: props.patientInfo.encounterId,
      accountId: accountId.value,
      quantity: item.quantity,
      totalPrice: item.quantity * prescriptionList.value[rowIndex.value].unitPrice,
      unitCode: item.unitCode,
      unitCode_dictText: item.unitCodeName ? item.unitCodeName : '',
      statusEnum: 1,
      dbOpType: prescriptionList.value[rowIndex.value].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[rowIndex.value].contentJson = JSON.stringify(
      prescriptionList.value[rowIndex.value]
    );
  });
  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, e) => {
  proxy.$refs['formRef' + rowIndex].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[rowIndex]?.[nextProp]?.focus();
        }, 100);
      } else {
        handleSaveSign(row, rowIndex);
      }
    }
  });
};

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) {
        expandOrder.value = [];
      }
      prescriptionList.value.shift();
      isAdding.value = false;
      groupMarkers.value = getGroupMarkers(prescriptionList.value); // 删除行会出现组号混乱的情况，所以这里重新更新标记
    }
  }
}

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

function handleGroupId(paramList) {
  updateGroupId(paramList).then(() => {
    getListInfo(false);
  });
}

// 组合
function combination() {
  console.log(groupIndexList.value);

  if (groupIndexList.value.length <= 1) {
    proxy.$modal.msgWarning('至少选择两项');
    return;
  }

  // 相同分组用法需要相同
  let uniqueValues = new Set();
  // 相同分组诊断需要相同
  let uniqDiagnosis = new Set();
  // 相同分组诊断需要相同
  let uniqInjectFlag = new Set();
  let status = false;
  let isSave = false;
  groupIndexList.value.forEach((index) => {
    if (prescriptionList.value[index].statusEnum == 2) {
      status = true;
    }
    if (prescriptionList.value[index].statusEnum == 1 && !prescriptionList.value[index].requestId) {
      isSave = true;
    }
    uniqueValues.add(prescriptionList.value[index].methodCode);
    uniqDiagnosis.add(prescriptionList.value[index].diagnosisName);
    uniqInjectFlag.add(prescriptionList.value[index].injectFlag);
  });
  // 校验是否有已签发的医嘱
  if (isSave) {
    proxy.$modal.msgWarning('请先保存当前医嘱后再进行分组');
    return;
  }
  if (status) {
    proxy.$modal.msgWarning('已签发医嘱不允许分组');
    return;
  }
  if (uniqueValues.size != 1) {
    proxy.$modal.msgWarning('同一分组药品用法必须相同');
    return;
  }
  if (uniqDiagnosis.size != 1) {
    proxy.$modal.msgWarning('同一分组诊断必须相同');
    return;
  }
  if (uniqInjectFlag.size != 1) {
    proxy.$modal.msgWarning('同一分组必须全部为输液药品');
    return;
  }
  // 获取当前时间戳拼接组号做唯一组号
  let timestamp = Date.now().toString();
  let updateList = [];
  groupIndexList.value.forEach((index) => {
    updateList.push({
      requestId: prescriptionList.value[index].requestId,
      groupId: timestamp + groupIndex.value,
    });
    // prescriptionList.value[index].groupId = JSON.parse(JSON.stringify(groupIndex.value));
    prescriptionList.value[index].check = false;
  });
  // 更新组号
  handleGroupId({ groupList: updateList });
  // 根据组号排序
  sortPrescriptionList();
  groupMarkers.value = getGroupMarkers(prescriptionList.value); // 更新标记
  groupIndex.value++;
  groupIndexList.value = [];
}

// 拆组
function split() {
  if (groupIndexList.value.length < 1) {
    proxy.$modal.msgWarning('至少选择一项');
    return;
  }

  // 获取选中的所有行
  const selectedRows = groupIndexList.value.map((index) => prescriptionList.value[index]);

  // 校验是否包含已签发的医嘱
  if (selectedRows.some((row) => row.statusEnum === 2)) {
    proxy.$modal.msgWarning('已签发医嘱不允许拆组');
    return;
  }

  // 提取出这些行涉及的所有 groupId
  const selectedGroupIds = [...new Set(selectedRows.map((row) => row.groupId).filter(Boolean))];
  if (selectedGroupIds.length === 0) {
    proxy.$modal.msgWarning('请选择已分组的医嘱');
    return;
  }

  // 构建最终要更新的列表
  let updateList = [];

  // 遍历每个 groupId
  selectedGroupIds.forEach((groupId) => {
    // 当前分组下所有的医嘱
    const groupItems = prescriptionList.value.filter((item) => item.groupId === groupId);

    // 当前分组中被选中的医嘱
    const selectedInGroup = selectedRows.filter((row) => row.groupId === groupId);

    // 如果选中数 = 总数 - 1 → 拆掉整个分组
    if (selectedInGroup.length === groupItems.length - 1) {
      updateList.push(
        ...groupItems.map((item) => ({
          requestId: item.requestId,
          groupId: '',
        }))
      );
    } else {
      // 否则只更新选中的
      updateList.push(
        ...selectedInGroup.map((item) => ({
          requestId: item.requestId,
          groupId: '',
        }))
      );
    }
  });

  // 清除本地数据中的 groupId
  prescriptionList.value.forEach((item) => {
    if (updateList.some((u) => u.requestId === item.requestId)) {
      item.groupId = undefined;
      item.check = false; // 取消勾选
    }
  });

  // 更新分组号
  handleGroupId({ groupList: updateList });

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

  // 排序保持一致性
  sortPrescriptionList();

  // 清空选中索引
  groupIndexList.value = [];

  proxy.$modal.msgSuccess('拆组成功');
}
// 分组标记处理
function getGroupMarkers(prescriptionList) {
  const groupMap = {};
  const markers = [];

  // 遍历处方列表，记录每组的索引范围（忽略无 groupId 的项）
  prescriptionList.forEach((item, index) => {
    if (!item.groupId) {
      markers[index] = null; // 没有组号的标记为 null
      return;
    }

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

  // 根据每组的索引范围设置标记
  Object.values(groupMap).forEach((indices) => {
    if (indices.length === 1) {
      // 单个组成员，显示上下括号
      markers[indices[0]] = 'all';
    } else {
      indices.forEach((index, i) => {
        if (i === 0) {
          markers[index] = '┏';
        } else if (i === indices.length - 1) {
          markers[index] = '┗';
        } else {
          markers[index] = '┃';
        }
      });
    }
  });
  return markers;
}
const groupMarkers = ref([]);

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

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

    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 = unitCodeList.value.filter((item) => {
      return item.value == row.doseUnitCode;
    })[0];

    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) {
      if (row.rateCode && row.dispensePerDuration) {
        // 根据用药天数和用药频次计算数量
        let count = calculateQuantityByDays(row.rateCode, row.dispensePerDuration);
        if (count) {
          let quantity;
          if (row.unitCode == row.minUnitCode) {
            quantity = calculateQuantityBySplitType(row.partAttributeEnum, row.doseQuantity, count);
            prescriptionList.value[index].quantity = quantity;
            prescriptionList.value[index].totalPrice = (quantity * row.minUnitPrice).toFixed(2);
          } else {
            quantity = calculateQuantity(
              row.partAttributeEnum,
              row.doseQuantity,
              count,
              row.partPercent
            );
            prescriptionList.value[index].quantity = quantity;
            prescriptionList.value[index].totalPrice = (quantity * row.unitPrice).toFixed(2);
          }
        }
      } else {
        // 如果没有用药频次或用药天数，则根据数量计算总价（中成药兼容旧逻辑）
        if (row.adviceType == 2) {
          // 拆零比为1时 总价等于数量乘以单价
          if (row.partPercent == 1) {
            row.totalPrice = row.quantity * row.unitPrice;
          } else {
            // 拆零比不为1时， 如果当前总量单位是大单位，总价等于数量乘以大单位价格 否则总价等于数量乘以小单位价格
            if (row.unitCodeList && row.unitCodeList.find((k) => k.value == row.unitCode)) {
              if (row.unitCodeList.find((k) => k.value == row.unitCode).type == 'unit') {
                row.totalPrice = row.quantity * row.unitPrice;
              } else {
                row.totalPrice = (row.quantity * row.minUnitPrice).toFixed(2);
              }
            }
          }
        }
      }
    }
  });
  // proxy.$refs['formRef' + index].validate();
}

/**
 * 根据门诊拆分类型计算总药量
 *
 * @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);
// }

// 处理行chexkbox选中
function handleCheckBoxChange(value, index, row) {
  // 选中将当前行索引记录下来，取消将当前行索引删除
  if (value) {
    groupIndexList.value.push(index);
  } else {
    groupIndexList.value.splice(groupIndexList.value.indexOf(index), 1);
  }
  // 如果选中或取消行有组号，将全部相同组号的行全部选中，并记录或删除这些行的索引
  if (row.groupId) {
    // 获取组号相同行
    let sameGroupIdList = prescriptionList.value.filter((item) => {
      return item.groupId == row.groupId;
    });
    // 如果只有一个组号的情况不做处理
    if (sameGroupIdList.length == 1) {
      return;
    } else {
      sameGroupIdList.forEach((item) => {
        // 排除掉当前选中行
        if (row.uniqueKey != item.uniqueKey) {
          // 同步选中状态
          let currentIndex = prescriptionList.value.findIndex((k) => k.uniqueKey == item.uniqueKey);
          prescriptionList.value[currentIndex].check = value;
          if (value) {
            groupIndexList.value.push(currentIndex); // 或使用索引或唯一标识
          } else if (!value) {
            groupIndexList.value.splice(groupIndexList.value.indexOf(currentIndex), 1);
          }
        }
      });
    }
  }
  console.log(groupIndexList.value);
}

// 校验每个组号数量是否大于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;
}
defineExpose({ getListInfo, getDiagnosisInfo });
</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;
}
</style>