<template>
  <!-- 智能开方 -->
  <div class="prescribing flex-plane-center-top">
    <div class="pre-left" v-if="!isShrink">
      <!-- 标题信息 -->
      <div class="pre-title">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>患者信息</div>
        </div>
      </div>
      <div class="patiens-msg" v-if="Object.keys(patiensMsg).length>0">
        <p v-if="patiensMsg.sex">患者性别：{{patiensMsg.sex}}</p>
        <p v-if="patiensMsg.age">患者年龄：{{patiensMsg.age}}</p>
        <p
          v-if="patiensMsg.isGravidity && patiensMsg.isGravidity=='2'"
        >是否怀孕：{{patiensMsg.isGravidity=='1'?'否':patiensMsg.isGravidity=='2'?'是':'无'}}</p>
        <p
          v-if="patiensMsg.isBreastFeeding && patiensMsg.isBreastFeeding==1"
        >是否哺乳：{{patiensMsg.isBreastFeeding==1?'是':patiensMsg.isBreastFeeding==2?'否':'无'}}</p>
      </div>
      <div class="pre-title mr-t10">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div style="display: flex;justify-content: space-between; align-items: center; width: 100%">
            中医电子病历
            <el-button v-if="showRecordLoading" style="padding: 4px 8px; transform: translateY(2px)" size="mini" :loading="recordLoading" @click="loadRecord()">
              {{ recordLoading ? '' : '刷新' }}</el-button>
          </div>
        </div>
      </div>
      <div class="patiens-msg" v-if="patiensMsg.outpatientElectronicmedicalrecord">
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint">
          <span>主诉：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.chiefcomplaint}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.historypresent">
          <span>现病史：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.historypresent}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.pasthistory">
          <span>既往史：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.pasthistory}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.fourmedicine">
          <span>中医四诊：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.fourmedicine}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.physicalexamination">
          <span>体格检查：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.physicalexamination}}
        </p>
        <p v-if="patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination">
          <span>辅助检查：</span>
          {{patiensMsg.outpatientElectronicmedicalrecord.supplementaryexamination}}
        </p>
        <div v-if="patiensMsg.outpatientElectronicmedicalrecord.image1.length>0">
          <div style="margin: 4px 0 8px;">报告上传：</div>
          <el-image
            :preview-src-list="patiensMsg.outpatientElectronicmedicalrecord.image1"
            :src="item"
            :key="index"
            style="width:64px;height: 64px;margin-right: 10px;"
            alt
            v-for="(item,index) in patiensMsg.outpatientElectronicmedicalrecord.image1"
          />
        </div>
      </div>
      <!-- mr-t30 -->
      <div class="pre-title" v-if="false">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>中医诊断</div>
          <!-- inferRecipe(2) -->
          <el-button size="mini" type="warning" @click="tcmClick()" style="margin-left:10px;">推导</el-button>
        </div>
      </div>
      <!-- <TCMDiagnosis v-if="Object.keys(patiensMsg).length>0" :patiensMsg="patiensMsg" ref="TCM"></TCMDiagnosis> -->

      <div class="pre-title mr-t10">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>快捷查询</div>
        </div>
      </div>
      <!-- 协定方（中药处方/中药制剂时显示，适宜技术隐藏） -->
      <div class="mr-t10 agreement" v-if="container_i!=2">
        <div class="agree-tab flex-vertical-between">
          <div
            :class="agree_current==0?'flex-center agree-active':'flex-center'"
            @click.stop="changeAgree(0)"
          >协定方</div>
          <div
            :class="agree_current==1?'flex-center agree-active':'flex-center'"
            @click.stop="changeAgree(1)"
          >方剂</div>
          <div
            :class="agree_current==2?'flex-center agree-active':'flex-center'"
            @click.stop="changeAgree(2)"
          >参考医案</div>
        </div>
        <!-- 展开效果 -->
        <div class="collapse" v-if="agree_current==0">
          <el-collapse v-model="activeNames" accordion @change="activeChange">
            <el-collapse-item
              :title="item.name"
              :name="item.index"
              v-for="(item,index) in collapseData"
              :key="item.name+index"
            >
              <div class="collapse-body">
                <div
                  class="collapse-item flex-vertical-between"
                  v-for="(item1,index1) in item.list"
                  :key="item1.name+index1"
                >
                  <div class="med-name" @click="getAccordDetail(item1.preId)">{{item1.name}}</div>

                  <!-- <div class="med-btns flex-vertical-center-r">
                                        <div class="flex-center" @click="showAgree=true">换方</div>
                                        <div class="bg-yellow flex-center">合方</div>
                  </div>-->
                </div>

                <div class="collapse-more flex-center" @click="loadMoreCollapse(item)">
                  <img src="../../assets/point3.png" alt />
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- 第二个 和第三个 tab 选中效果 -->
        <div class="basis" v-if="agree_current!=0">
          <div class="basis-top-search flex-center">
            <div v-if="agree_current==1">
              <el-input placeholder="请输入内容" v-model="agree_key" size="mini">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <div v-if="agree_current==2">
              <el-input placeholder="请输入内容" v-model="agree_key1" size="mini">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </div>
            <div class="flex-center search-btn" @click="searchPre">搜索</div>
          </div>
          <!-- 方剂 -->
          <div v-if="agree_current==1">
            <div
              class="collapse-item flex-vertical-between"
              v-for="(item,index) in rPrescription.list"
              :key="'d'+index"
            >
              <div
                class="med-name"
                @click="getPreDetal(item.pried ||item.acupreid,1)"
              >{{item.prename || item.acupreid}}</div>

              <div class="med-btns flex-vertical-center-r" v-if="agree_current!=2">
                <div class="flex-center" @click.self.stop="inferChange(item)">换方</div>
                <div class="bg-yellow flex-center" @click.self.stop="inferChange1(item)">合方</div>
              </div>
            </div>
          </div>
          <!-- 参考议案 -->
          <div v-if="agree_current==2">
            <div
              class="collapse-item flex-vertical-between"
              v-for="(item,index) in rDoctorCase.list"
              :key="item.disname+index"
            >
              <div
                class="med-name"
                @click="getDCaseDetail(item.verifyid)"
              >{{item.disname}} {{item.attendingexpert}}</div>
            </div>
          </div>

          <div class="collapse-more flex-center" @click="loadMorePre">
            <img src="../../assets/point3.png" alt />
          </div>
        </div>
      </div>

      <!-- 适宜技术 协定方（仅 container_i==2显示） -->
      <SuitTechAgreement v-if="container_i==2" @turn="onSuitTechTurn" />

      <div class="pre-title mr-t10" v-if="false">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>就诊记录</div>
        </div>
      </div>
      <div class="pre-steps" v-if="false">
        <div class="steps">
          <el-steps direction="vertical" :active="patiensMsg.recordLength" space="55px">
            <el-step v-for="(item,index) in patiensMsg.patientRecord" :key="item.timeStr+index">
              <template slot="icon">
                <img src="../../assets/step.png" alt class="icon" />
              </template>
              <template slot="title">
                <div @click="getSeeDByID(item.id)" class="step-body">
                  <div class="step-name">{{item.timeStr}}</div>
                  <div class="step-name">{{item.illnessName}}</div>
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>
        <!-- <div class="find-more flex-center">
                    <img src="../../assets/more-down.png" alt="">
                    <span>查看更多</span>
        </div>-->
      </div>
    </div>

    <!-- 中间主体部分 -->

    <div class="pre-center">
      <!-- 768 页面 展示病名 -->
      <div class="page-768">
        <!-- 扩展icon -->
        <div class="kz-icon" @click="setShrink">
          <i class="el-icon-d-arrow-right" v-if="!isShrink"></i>
          <i class="el-icon-d-arrow-left" v-if="isShrink"></i>
        </div>
        <!-- 中医诊断 -->
        <TCMDiagnosis
          direction="horizontal"
          :patiensMsg="patiensMsg"
          v-if="Object.keys(patiensMsg).length>0"
          ref="TCM"
          class-name="prescr"
        ></TCMDiagnosis>
        <!-- 推导按钮 -->
        <div class="deduce">
          <el-button size="mini" type="primary" @click="tcmClick()">推导</el-button>

          <el-popover
            placement="top-start"
            title
            width="220"
            trigger="hover"
            style="margin-left:10px;"
            v-if="innerWidth <= 768"
          >
            <el-button size="mini" slot="reference" type="primary">HIS</el-button>
            <div class="his-msg his-msg-mini" v-if="Object.keys(patiensMsg).length>0">
              <div class="his-item">
                <div class="name">HIS病名：</div>
                <div class="value">
                  <el-input
                    size="mini"
                    disabled
                    :value="patiensMsg.maindiagnosis.namemedicinehis || ''"
                  ></el-input>
                </div>
              </div>
              <div class="his-item">
                <div class="name">HIS证型：</div>
                <div class="value">
                  <el-input
                    size="mini"
                    disabled
                    :value="patiensMsg.maindiagnosis.syndrometypeshis || ''"
                  ></el-input>
                </div>
              </div>
            </div>
          </el-popover>
        </div>
        <!-- his信息 -->
        <div class="his-msg" v-if="innerWidth>768 " style="flex-wrap: wrap;">
          <!-- <div class="his-item" v-if="Object.keys(patiensMsg).length>0">
            <div class="name">HIS病名：</div>
            <div class="value">
              <el-input size="mini" disabled :value="patiensMsg.maindiagnosis.namemedicinehis ||''"></el-input>
            </div>
          </div> -->
          <!-- <div class="his-item" v-if="Object.keys(patiensMsg).length>0">
            <div class="name">HIS证型：</div>
            <div class="value">
              <el-input
                size="mini"
                disabled
                :value="patiensMsg.maindiagnosis.syndrometypeshis || ''"
              ></el-input>
            </div>
          </div> -->
          <!-- 西医诊断 - 仅适宜技术处方 tab 显示 -->
          <div class="his-item" v-if="container_i == 2 && patiensMsg.maindiagnosis">
            <div class="name">西医主诊断：</div>
            <div class="value">
              <el-input
                size="mini"
                disabled
                :value="patiensMsg.maindiagnosis.diagnosis"
              ></el-input>
            </div>
          </div>
          <div class="his-item" v-if="container_i == 2">
            <div class="name">建议诊断：</div>
            <div class="value">
              <div class="western-disease-input-wrapper" @click="$refs.suggestDiagAutocomplete && $refs.suggestDiagAutocomplete.focus()">
                <el-tag
                  v-for="code in suggestDiag"
                  :key="code"
                  size="mini"
                  closable
                  @close="removeWesternDisease(code)"
                >{{ westernDiseaseNameMap[code] || code }}</el-tag>
                <el-autocomplete
                  ref="suggestDiagAutocomplete"
                  size="mini"
                  v-model="westernDiseaseSearch"
                  :fetch-suggestions="queryWesternDisease"
                  value-key="westname"
                  :placeholder="suggestDiag.length ? '' : '请搜索选择'"
                  clearable
                  :trigger-on-focus="true"
                  @select="onWesternDiseaseSelect"
                  @visible-change="onWesternDiseaseVisible"
                >
                  <template slot-scope="{ item }">
                    <div :class="{ 'autocomplete-disabled': item._disabled }">
                      {{ item.westname }}
                    </div>
                  </template>
                </el-autocomplete>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-vertical-between center-header">
        <div class="center-tab flex-vertical-center-l">
          <div v-for="(item,index) in contentTabs" :key="index"
               v-show="!item.hide" :data-tab-prescribing="item.id" class="flex-center" :class="{active: container_i === index}"
               @click="changeContainer(item, index)">
            <span :style="{color:item.color}">{{ item.name }}</span>
          </div>
        </div>
        <div class="header-total flex-vertical-center-r flex-wrap" v-if="false">
          <div v-if="contentTabs[0].check">
            中药处方总费用:
            <span>{{chineseM.allMoney}}元</span>
          </div>
          <div v-if="contentTabs[1].check">
            中药制剂总费用:
            <span>{{medicineC.allMoney}}元</span>
          </div>
          <div v-if="contentTabs[2].check">
            适宜技术处方总费用:
            <span>{{suitScience.allMoney}}元</span>
          </div>
          <div>
            合计费用：
            <span>{{totalPrice}}元</span>
          </div>
        </div>
        <!-- 右侧按钮 -->
        <div class="flex-vertical-center-r flex-wrap">
          <el-button v-if="container_i == 2 && unifyPrescriptionTitle" size="mini" style="margin-right: 10px;" @click="openSuitUnifyPresc" type="primary">医派协定方</el-button>
          <AiEModal v-if="AI_MODEL_URL" :url="AI_MODEL_URL" title="e生大模型">
            <template #default="{ handle }">
              <el-button size="mini" style="margin-right: 10px;" @click="handle" type="primary">e生大模型</el-button>
            </template>
          </AiEModal>
          <el-button v-if="showPrec && unifyPrescriptionTitle" size="mini" @click="openUnifyPrescPrec" type="primary">{{unifyPrescriptionTitle}}</el-button>
          <el-button size="mini" key="tongue" :loading="tongueAndFaceLoading" :disabled="!tongueAndFaceAnalysis" @click="openTongueAndFaceAnalysis" type="primary">舌面诊影像</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleReplenish"
          >{{ innerWidth > 768 ? '补充中医电子病历' :'补充病历' }}</el-button>
          <el-button v-if="container_i == 2" size="mini" @click="openSuitPresc" type="primary">协定方</el-button>
          <el-button size="mini" @click="openDCase" v-if="showPrec && isShrink">参考医案</el-button>
          <el-button v-if="showPrec" size="mini" @click="openPrec" type="primary">协定方/方剂</el-button>
          <el-popover
            placement="left"
            title
            width="150"
            trigger="hover"
            v-if="rRecomendR.length>0 && isShrink"
            style="margin-left:10px;"
          >
            <!-- hover -->
            <el-button size="mini" type="primary" slot="reference">推荐的方剂</el-button>
            <template>
              <div class="recommend flex-center" style="width:100%">
                <div class="banner">
                  <div class="r-banner-body">
                    <div
                      class="r-body-item flex-vertical-between"
                      v-for="(item1,index1) in rRecomendR"
                      :key="'c'+index1"
                    >
                      <div
                        :class="['med-name med-name-bg',tjRecipeId==item1.preid ||tjRecipeId==item1.pid  || tjRecipeId==item1.acupreid  ?'active':'',]"
                        v-if="item1.showType==0"
                        @click.stop="getPreDetal(item1.preid || item1,1)"
                      >
                        <span v-if="item1.prename">{{item1.prename}}</span>
                        <span
                          v-else
                        >{{item1.acupretype==1?'针灸':item1.acupretype==2?'艾灸':item1.acupretype==3?'推拿':'拔罐'}}</span>
                        <!-- {{item1.prename?item1.prename+'('+item1.book?item1.book:'暂无'+')': item1.acupretype==1?'针灸':item1.acupretype==2?'艾灸':item1.acupretype==3?'推拿':'拔罐'}} -->
                      </div>
                      <!-- 经验方 -->
                      <div
                        :class="['med-name med-name-bg',tjRecipeId==item1.preid ||tjRecipeId==item1.pid  ?'active':'',]"
                        v-else
                        @click="getExperinceDetail(item1.pid)"
                      >
                        <!-- <img src='~@/assets/expr.png' v-if="item1.showType==1" class="icon-expr" /> -->
                        <span>{{item1.name}}({{item1.experttitle}})</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </template>
          </el-popover>
          <el-button size="mini" type="primary" v-if="showPrec && isShrink&&rRecomendR.length==0">推荐的方剂</el-button>
        </div>
      </div>
      <!-- 代煎/配送 -->
      <!-- <div class="address">
        <medAdress
          ref="medAdress"
          :container_i="container_i"
          @psChange="psChange"
          @djChange="djChange"
          :isShowDj="isShowDj"
          :isShowPs="isShowPs"
        ></medAdress>
      </div>-->

      <!-- 表格数据展示 -->
      <div class="center-table">
        <chinese-medicine
          @find="findDrug($event)"
          v-show="container_i===0"
          id="chineseM"
          ref="chineseM"
          :totalAllMoney.sync="chineseM.allMoney"
          @submit="submitRecipe1()"
          @clear="clearContainer('0')"
          :showSubmit="showSubmit"
          :isShrink="isShrink"
          :isDaiJian="Number(isDaiJian)"
          :isPs="Number(isPs)"
          @updateDp="onUpdateDp"
        ></chinese-medicine>

        <medicineChinese
          @find="findDrug($event)"
          v-show="container_i==1"
          ref="medicineC"
          id="medicineC"
          @submit="submitRecipe1()"
          @clear="clearContainer('1')"
          :totalAllMoney.sync="medicineC.allMoney"
          :showSubmit="showSubmit"
          :isPs="Number(isPs)"
        ></medicineChinese>
        <!-- <suitScience
          @find="find($event)"
          v-show="container_i==2"
          ref="suitScience"
          id="suitScience"
          @submit="submitRecipe1()"
          @clear="clearContainer('2')"
          :totalAllMoney.sync="suitScience.allMoney"
          :showSubmit="showSubmit"
        ></suitScience> -->
        <AcupointTable
          v-show="container_i==2"
          ref="suitScience"
          :showEditable="false"
          :showGuide="true"
          :showEntrust="true"
          :showAgreementTotal="false"
          :useIsUpdateLock="true"
          :showSaveWhenLocked="true"
          :requiredTreatFields="true"
          :report-add-recipe="true"
          @save="submitRecipe1()"
          @clear="clearContainer('2')"
          @add-recipe="addRecipeFrom('3')"
          @active-project-change="onSuitActiveProjectChange"
        />
      </div>
    </div>

    <div class="pre-right" v-show="container_i==0 && !isShrink">
      <!-- 标题信息 -->
      <div class="pre-title flex-vertical-between">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>推荐的方剂</div>
        </div>
        <!-- <div class="tuidao flex-center" @click="inferRecipe(2)" v-if="rRecomendR.length>0">推导</div> -->
      </div>

      <!-- 推荐方剂 -->
      <div class="recommend flex-center" v-if="rRecomendR.length>0">
        <!-- <div class="arrow-left flex-center" @click="changeRbanner('reduce')">
          <img src="../../assets/arrow-left.png" alt="">
        </div>-->
        <div class="banner">
          <!-- <el-carousel ref="r_banner" height="80px" :initial-index='r_current' arrow='never' indicator-position='none'
          :autoplay='false'>-->
          <!-- <el-carousel-item v-for="(item,index) in rRecomendR" :key="'b'+index"> -->
          <div class="r-banner-body">
            <div
              class="r-body-item flex-vertical-between"
              v-for="(item1,index1) in rRecomendR"
              :key="'c'+index1"
            >
              <div class="med-name med-name-bg"
                   :class="{active: tjRecipeId && (tjRecipeId==item1.preid ||tjRecipeId==item1.pid || tjRecipeId==item1.acupreid)}"
                v-if="item1.showType==0"
                @click.stop="getPreDetal(item1.preid || item1,1)"
              >
                <span v-if="item1.prename">{{item1.prename}}</span>
                <span
                  v-else
                >{{item1.acupretype==1?'针灸':item1.acupretype==2?'艾灸':item1.acupretype==3?'推拿':''}}</span>
                <!-- {{item1.prename?item1.prename+'('+item1.book?item1.book:'暂无'+')': item1.acupretype==1?'针灸':item1.acupretype==2?'艾灸':item1.acupretype==3?'推拿':'拔罐'}} -->
              </div>
              <!-- 经验方 -->
              <div class="med-name med-name-bg"
                   :class="{active: tjRecipeId && (tjRecipeId==item1.preid ||tjRecipeId==item1.pid) }"
                v-else
                @click="getExperinceDetail(item1.pid)"
              >
                <!-- <img src='~@/assets/expr.png' v-if="item1.showType==1" class="icon-expr" /> -->
                <span>{{item1.name}}({{item1.experttitle}})</span>
              </div>

              <!-- <div class="med-btns flex-vertical-center-r"> -->
              <!-- 专家经验换方 -->
              <!-- <div class="flex-center" v-if="item1.showType==1" @click.self.stop="turnRecipe3(item1)">换方</div>
                <div class="flex-center bg-yellow" v-if="item1.showType==1" @click.self.stop="joinRecipe3(item1)">合方
                </div>

                <div class="flex-center" v-if="item1.showType==0"
                  @click.self.stop="inferChange(item1,item1.prename?'':1,item1.prename?'':1)">换方</div>
                <div class="bg-yellow flex-center" v-if="item1.showType==0"
                  @click.self.stop="inferChange1(item1,item1.prename?'':1,item1.prename?'':1)">合方
              </div>-->
              <!-- </div> -->
            </div>
          </div>
          <!-- </el-carousel-item> -->
          <!-- </el-carousel> -->
        </div>
        <!-- <div class="arrow-left flex-center" @click="changeRbanner('add')">
          <img src="../../assets/arrow-right.png" alt="">
        </div>-->
      </div>

      <!-- 安全合理用药检测 -->
      <div class="pre-title mr-t10" v-if="container_i!=2">
        <div class="flex-vertical-center-l title-container">
          <span></span>
          <div>安全合理用药检测<i style="margin-left: 2px;" class="el-icon-loading" v-if="reasonableSafeMedicinesLoading"></i></div>
        </div>
        <div class="patiens-msg reasonable-safe-medicines-wrapper" v-html="reasonableSafeMedicinesHTML"></div>
      </div>
    </div>

    <!-- 适宜技术  右栏（推荐方案 + 安全检测，仅 container_i==2显示） -->
    <div class="pre-right" v-show="container_i==2 && !isShrink">
      <SuitTechSidePanel
        :recommendations="rRecomendR"
        :activeId="suitTjRecipeId"
        :safetyItems="suitActiveSafety"
        @select="onSuitRecommendSelect"
      />
    </div>

    <!-- 方剂详情 -->
    <Popup
      :showDialog="showDialog"
      distanceTop="3vh"
      @cancle="changeRecipe"
      title="方剂详情"
      @confim="joinRecipe()"
      confimText="合方"
      cancleText="换方"
      :cancleStyle="{background:'#FFB55F',color:'#fff'}"
      width="700px"
    >
      <div class="drug-body" slot="body">
        <div v-if="preInfo.prename" class="drug-item flex-plane-center-l">
          <span>方剂名：</span>
          <div>{{preInfo.prename}}</div>
        </div>
        <div v-if="preInfo.prename" class="drug-item flex-plane-center-l">
          <span>功效：</span>
          <div>{{preInfo.efficacy}}</div>
        </div>
        <div v-if="preInfo.prename" class="drug-item flex-plane-center-l">
          <span>主治：</span>
          <div>{{preInfo.indication}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>处方明细：</span>
          <div class="flex-vertical-center-l flex-wrap">
            <span
              v-for="(item,index) in preInfo.items"
              :key="'e'+index"
            >{{item.matname || item.acuname}}{{item.dose}}{{item.unit}}</span>
          </div>
        </div>

        <div class="drug-item flex-plane-center-l">
          <span>方解：</span>
          <div>{{preInfo.annotation ||preInfo.operation}}</div>
        </div>
        <div v-if="preInfo.prename" class="drug-item flex-plane-center-l">
          <span>用法：</span>
          <div>{{preInfo.preusage}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>出处：</span>
          <div>{{preInfo.presource || preInfo.book}}</div>
        </div>
      </div>
    </Popup>

    <!-- 药品详情 -->
    <Popup
      width="80%"
      :showDialog="showDrug"
      @cancle="showDrug=false"
      distanceTop="3vh"
      title="药品详情"
      :showBtns="false"
    >
      <div class="drug-body" slot="body">
        <div class="drug-item flex-plane-center-l">
          <span>名称：</span>
          <div>{{drugInfo.matname}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>别名：</span>
          <div>{{drugInfo.matsynonyms}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>用法用量：</span>
          <div>{{drugInfo.matusage}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>用法禁忌：</span>
          <div>{{drugInfo.matsjj}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>性味：</span>
          <div>{{drugInfo.matflavour}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>归经：</span>
          <div>{{drugInfo.matmeridian}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>功效：</span>
          <div>{{drugInfo.matefficacy}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>应用：</span>
          <div>{{drugInfo.matapplication}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>使用注意：</span>
          <div>
            <div>{{drugInfo.mattaboo}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>图示：</span>
          <div
            class="flex-plane-center-l"
            v-for="(item,index) in drugInfo.matphoto"
            :key="'f'+index"
          >
            <img :src="item" alt />
          </div>
        </div>
        <div class="flex-vertical-center-l flex-wrap">
          <div class="drug-item1 flex-plane-center-l">
            <span>相似中药鉴别使用：</span>
            <div>
              <div v-for="(item,index) in drugInfo.xiangsi" :key="'g'+index">
                <span
                  class="mad-cy"
                  v-for="(item1,index1) in item.relmats"
                  :key="'h'+index1"
                >{{item1.matname}}{{index1==item.relmats.length-1?'':'、'}}</span>
                <div style="margin-bottom:10px;">{{item.differencedesc}}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="flex-vertical-center-l flex-wrap">
          <div class="drug-item1 flex-plane-center-l">
            <span>常用药对：</span>
            <div>
              <div v-for="(item,index) in drugInfo.changyong" :key="index">
                <span
                  class="mad-cy"
                  v-for="(item1,index1) in item.relmats"
                  :key="'i'+index1"
                >{{item1.matname}}{{index1==item.relmats.length-1?'':'、'}}</span>
                <div style="margin-bottom:10px;">{{item.differencedesc}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Popup>
    <!-- 药品详情 -->
    <Popup
      width="50%"
      distanceTop="5vh"
      :showDialog="showXuewei"
      @cancle="showXuewei=false"
      title="穴位详情"
      :showBtns="false"
    >
      <div class="drug-body" slot="body">
        <div class="drug-item flex-plane-center-l">
          <span>穴位名称：</span>
          <div>
            <div>{{xwinfo.acuname}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>定位：</span>
          <div>
            <div>{{xwinfo.acuposotion}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>解剖：</span>
          <div>
            <div>{{xwinfo.acudiscection}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>主治：</span>
          <div>
            <div>{{xwinfo.acumaintreat}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>操作：</span>
          <div>
            <div>{{xwinfo.acuoperation}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>针刺：</span>
          <div>
            <div>{{xwinfo.acuneedling}}</div>
            <!-- <div>2.通常补血用当归身，活血用当归尾，补血活血用全当归</div> -->
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>图示：</span>
          <!-- <div class="flex-plane-center-l" v-for="(item,index) in drugInfo.acuimg" :key="index">
                        <img :src="item" alt="">
          </div>-->
          <div class="img">
            <img :src="xwinfo.acuimg" alt />
          </div>
        </div>
      </div>
    </Popup>

    <!-- 我的协定方 -->
    <Popup
      :showDialog="showAgree"
      @cancle="showAgree=false"
      distanceTop="5vh"
      title="我的协定方"
      :showBtns="false"
    >
      <div class="drug-body" slot="body">
        <div class="drug-item flex-plane-center-l">
          <span>方名：</span>
          <div>{{agreeInfo.name}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>功效适应症：</span>
          <div>{{agreeInfo.effect}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>类别：</span>
          <div>{{agreeInfo.type=='0'?'组方':'配方'}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>明细：</span>
          <div class="detail">
            <p class="flex-center btns" @click="agreeTurnRecipe(agreeInfo)">转方</p>
            <p class="drug-detail flex-plane-center-l flex-wrap">
              <span
                v-for="(item,index) in agreeInfo.preStiDetails"
                :key="item.ypmc+index"
              >{{item.ypmc}}{{item.dose}}{{item.dw}}</span>
            </p>
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>分享医生：</span>
          <div>{{agreeInfo.createName}}</div>
        </div>
      </div>
    </Popup>

    <!-- 专家经验 -->
    <Popup
      :showDialog="showExpr"
      distanceTop="5vh"
      @cancle="showExpr=false"
      title="专家经验"
      :showBtns="false"
      width="700px"
    >
      <div class="drug-body" slot="body">
        <div class="drug-item flex-plane-center-l">
          <span>方名：</span>
          <div>{{exprInfo.name}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>方解：</span>
          <div>{{exprInfo.solution}}</div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>功效适应症：</span>
          <div>{{exprInfo.effect}}</div>
        </div>

        <div class="drug-item flex-plane-center-l">
          <span>明细：</span>
          <div class="detail">
            <div class="trun-join">
              <p class="flex-center btns" @click="turnRecipe3(exprInfo)">转方</p>
              <p class="flex-center btns bg-yellow" @click="joinRecipe3(exprInfo)">合方</p>
            </div>
            <p class="drug-detail flex-plane-center-l flex-wrap">
              <span
                v-for="item in exprInfo.prescriptionDetailVos"
                :key="item.drugname+item.pid"
              >{{item.drugname}}{{item.dose}}{{item.unit}}</span>
            </p>
          </div>
        </div>
        <div class="drug-item flex-plane-center-l">
          <span>专家名称：</span>
          <div>{{exprInfo.expert}}</div>
        </div>
      </div>
    </Popup>

    <!-- 名家验案详情 -->
    <Popup
      :showDialog="showTestCase"
      distanceTop="5vh"
      @cancle="showTestCase=false"
      title="名家验案详情"
      :showBtns="false"
      width="700px"
    >
      <div slot="body" class="testCase">
        <div v-if="!!testCaseInfo.content" style="white-space: pre-wrap;line-height: 2">{{ testCaseInfo.content }}</div>
        <template v-else>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">性别：</span>
            <div class="testCase-right">{{testCaseInfo.patientgender=='M'?'男':'女'}}</div>
          </div>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">年龄：</span>
            <div class="testCase-right">{{testCaseInfo.patientage}}岁</div>
          </div>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">婚姻：</span>
            <div class="testCase-right">{{testCaseInfo.patientmarriage=='0'?'未婚':'已婚'}}</div>
          </div>
          <div class="testCase-item flex-plane-center-l" v-if="testCaseInfo.dialist">
            <span class="testCase-left">主诉及现病史：</span>
            <div class="testCase-right">{{testCaseInfo.dialist[0].situation}}</div>
          </div>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">辨证：</span>
            <div class="testCase-right">{{testCaseInfo.chinesesymptom}}</div>
          </div>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">治法：</span>
            <div class="testCase-right">{{testCaseInfo.therapy}}</div>
          </div>
        </template>
        <div v-for="(item,index) in testCaseInfo.dialist" :key="index">
          <div class="testCase-title">{{index==0?'初诊':item.diatimes+'诊'}}</div>
          <div v-if="!testCaseInfo.content" class="testCase-item flex-plane-center-l">
            <span class="testCase-left">就诊日期：</span>
            <div class="testCase-right">{{item.checktime[0]}}</div>
          </div>
          <div class="testCase-item flex-plane-center-l">
            <span class="testCase-left">治疗意见：</span>
            <div
              class="testCase-right"
              v-for="(item1,index1) in item.fjlist"
              :key="item1.preusage+index1"
            >
              <div class="flex-vertical-center-l case-yijian">
                <span>{{item1.preusage}}</span>
                <div class="testCase-btns flex-center" @click="turnRecipe(item1)">转方</div>
              </div>
              <div class="flex-vertical-center-l flex-wrap case-detial">
                <span
                  v-for="(item2,index2) in item1.verpreitemlist"
                  :key="item2.matname+index2"
                >{{item2.matname}}{{item2.dose}}{{item2.unit}}</span>
              </div>
            </div>
          </div>
        </div>

        <div v-if="!testCaseInfo.content" class="testCase-item flex-plane-center-l">
          <span class="testCase-left">按语：</span>
          <div class="testCase-right">{{testCaseInfo.words}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">来源：</span>
          <div class="testCase-right">{{testCaseInfo.book}}</div>
        </div>
      </div>
    </Popup>
    <!-- 就诊记录详情 -->
    <Popup :showDialog="showRecord" @cancle="showRecord=false" title="就诊记录详情" :showBtns="false">
      <div slot="body" class="testCase" v-if="recordInfo.patient">
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">姓名：</span>
          <div class="testCase-right">{{recordInfo.patient.name}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">性别：</span>
          <div class="testCase-right">{{recordInfo.patient.sex}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">年龄：</span>
          <div class="testCase-right">{{recordInfo.patient.age}}岁</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">医疗机构：</span>
          <div class="testCase-right">{{recordInfo.patient.institutionidSelsourceName}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">科室名称：</span>
          <div class="testCase-right">{{recordInfo.patient.institutionidSelsourceName}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">诊断：</span>
          <div class="testCase-right">
            <div>中医诊断:{{recordInfo.mainDiagnosis.namemedicine?recordInfo.mainDiagnosis.namemedicine:'无'}}</div>
            <div>西医诊断:{{recordInfo.mainDiagnosis.diagnosis?recordInfo.mainDiagnosis.diagnosis:'无'}}</div>
          </div>
        </div>

        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">治疗意见：</span>
          <div
            class="testCase-right"
            v-for="(item,index) in recordInfo.patientprescription"
            :key="'i'+index"
          >
            <div class="flex-vertical-center-l case-yijian">
              <span>{{item.type=='0'?'中药处方'+(index+1):item.type=='1'?'中药制剂':'适宜技术处方'}}</span>
              <div class="testCase-btns flex-center" @click="turnRecipe1(item)">转方</div>
            </div>
            <div class="flex-vertical-center-l flex-wrap case-detial">
              <span
                v-for="(item1,index1) in item.myPatientDetailVos"
                :key="item1.name+index1"
              >{{item1.name}}{{item1.num}}{{item1.unit}}</span>
            </div>
          </div>
        </div>

        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">开方医生：</span>
          <div
            class="testCase-right"
          >{{recordInfo.patientprescription.length>0?recordInfo.patientprescription[0].updateUser:'无'}}</div>
        </div>
        <div class="testCase-item flex-plane-center-l">
          <span class="testCase-left">时间：</span>
          <div
            class="testCase-right"
          >{{recordInfo.patientprescription.length>0?recordInfo.patientprescription[0].updateTime:'无'}}</div>
        </div>
      </div>
    </Popup>

    <!-- 处方预览 -->
    <submitRecipe :show.sync="showPriview" :priviewData="priviewData"></submitRecipe>
    <!-- <div style="position:fixed;top:0;z-index:9999;width:100vw;">
      <suitMadePad></suitMadePad>
    </div>-->
    <!--参考医案例 页面768-->
    <Popup
      :showDialog="showCase"
      @cancle="showCase=false"
      title="参考医案"
      :showBtns="false"
      width="700px"
      distanceTop="5vh"
    >
      <div slot="body">
        <doctorCase :searchKey="agree_key1"></doctorCase>
      </div>
    </Popup>

    <!-- 查询协定方 方剂 页面768 -->
    <Popup
      :showDialog="showPresc"
      @cancle="showPresc=false"
      title="查询方剂/查询协定方"
      :showBtns="false"
      width="78%"
      distanceTop="5vh"
    >
      <div slot="body">
        <prescription></prescription>
      </div>
    </Popup>

    <!-- 查询医派协定方 页面768 -->
    <Popup
      :showDialog="showUnifyPresc"
      @cancle="showUnifyPresc=false"
      title="查询医派协定方"
      :showBtns="false"
      width="78%"
      distanceTop="5vh"
    >
      <div slot="body">
        <UnifyPrescription></UnifyPrescription>
      </div>
    </Popup>

    <!-- 查询医派协定方（适宜技术-医派协定方按钮，独立副本）页面768 -->
    <Popup
      :showDialog="showSuitUnifyPresc"
      @cancle="showSuitUnifyPresc=false"
      title="查询医派协定方"
      :showBtns="false"
      width="78%"
      distanceTop="5vh"
    >
      <div slot="body">
        <PrescriptionUnifySuit @turn="onSuitTechTurn" @open-detail="openSuitDetail"></PrescriptionUnifySuit>
      </div>
    </Popup>

    <!-- 查询协定方（适宜技术-协定方按钮，独立副本）页面768 -->
    <Popup
      :showDialog="showSuitPresc"
      @cancle="showSuitPresc=false"
      title="查询协定方"
      :showBtns="false"
      width="78%"
      distanceTop="5vh"
    >
      <div slot="body">
        <PrescriptionSuit @turn="onSuitTechTurn" @open-detail="openSuitDetail"></PrescriptionSuit>
      </div>
    </Popup>

    <!-- 协定方详情弹窗（查询弹窗点行查看；置于顶层，避免被查询弹窗 mask 遮挡） -->
    <SuitTechAgreementDetail
      :show.sync="suitDetailShow"
      :detail="suitDetailData"
      :loading="suitDetailLoading"
      :title="suitDetailTitle"
      :mode="suitDetailMode"
      @turn="onSuitDetailTurn"
    />

    <!-- 查询舌象分析 页面768 -->
    <Popup
        :showDialog="showTongueAnalysis"
        @cancle="showTongueAnalysis=false"
        title="舌面诊影像"
        :showBtns="false"
        width="70%"
        distanceTop="5vh"
    >
      <div style="height: 100%" slot="body">
        <TongueAnalysis v-if="showTongueAnalysis" :dataset="tongueAndFaceAnalysis"></TongueAnalysis>
      </div>
    </Popup>

    <!-- 安全合理用药弹窗 -->
    <Popup
      :showDialog.sync="showSafeD"
      @cancle="showSafeD=false"
      title="安全合理用药检测"
      :showBtns="false"
      width="700px"
      distanceTop="5vh"
      :destroyOnClose="true"
    >
      <div slot="body" v-loading="reasonableSafeMedicinesLoading">
        <div class="patiens-msg reasonable-safe-medicines-wrapper" v-html="reasonableSafeMedicinesHTML"></div>
      </div>
    </Popup>

    <!-- 选择代煎 地址栏 -->
    <Popup
      :showDialog="showAddress"
      @cancle="submitAddress(true)"
      @confim="submitAddress()"
      title="请和患者确认以下信息"
      width="700px"
      distanceTop="5vh"
    >
      <div slot="body">
        <medAdressNew
          ref="medAdress"
          :isDaijian="Number(isDaiJian)"
          :isPs="Number(isPs)"
          :isShowDj="isShowDj"
          :isShowPs="isShowPs"
          :optionsAgency="optionsAgency"
          :optionsDelivery="optionsDelivery"
        ></medAdressNew>
      </div>
    </Popup>
  </div>
</template>
<script>
import Popup from "@/components/Propup.vue";

import chineseMedicine from "@/components/ChineseMedicine.vue";
import medicineChinese from "@/components/MedicineAndChina.vue";
// import suitScience from "@/components/SuitScience.vue";
import AcupointTable from "@/views/business/components/AcupointTable.vue";

import submitRecipe from "./components/submitRecipe.vue";
// import TCMDiagnosis from "./components/TCMDiagnosis.vue";
import TCMDiagnosis from "../../components/TCMDiagnosis.vue";
import doctorCase from "./components/doctorCase.vue";
import prescription from "./components/prescription.vue";
import UnifyPrescription from "./components/prescription-unify.vue";
import PrescriptionUnifySuit from "./components/prescription-unify-suit.vue";
import PrescriptionSuit from "./components/prescription-suit.vue";
import TongueAnalysis from "./components/tongue-analysis.vue";
import safeDrug from "./components/safeDrug.vue";
import medAdress from "./components/medAddress.vue";
import medAdressNew from "./components/medAddressNew.vue";
import SuitTechAgreement from "./components/SuitTechAgreement.vue";
import SuitTechSidePanel from "./components/SuitTechSidePanel.vue";
import SuitTechAgreementDetail from "./components/SuitTechAgreementDetail.vue";
import {
  getPatiensBasisM,
  refreshElectronicInfo,
  getTongueAndFaceAnalysisRecords,
  addRecipe,
  getRecipeShowData,
  getRecipeDataByid,
  getAgreeRecipe,
  getSeeDByID,
  getDrugDetail,
  getAccordDetail,
  changeBasisPre,
  updateRecipe,
  changeExpre,
  recipeIsPay,
  getPreNumber,
  getRecipePriview,
  getMaxMinDoaseNumber,
  getRecipeByBasis,
  getRecipeBySuitTech
} from "@/api/diagnosis.js";
import { numberToUpperCase } from "@/utils/format.js";
import { addRecipeFrom } from "@/api/dataAnalysis.js";
import {
  getPrescriptionsList,
  getDoctorCaseL,
  getRationalMed,
  getRationalMedForPlat,
  inferRecipe,
  getDCaseDetail,
  changeAndJoin,
  getPreDetal,
  getAcupointD,
  getMedDetail,
  getXDiseaseName
} from "@/api/knowledge.js";
import {
  legacyDeduceIllnessPrescriptionMethod,
  checkReasonableSafeMedicinesMethod,
} from '@/request/api';
import {
  ReasonableSafeMedicine,
} from '@/request/model';

import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import { getExperinceDetail } from "@/api/business.js";
import { getSuitableTechInfo } from "@/api/technology.js";
import { setTimeout } from "timers";
import prescribing from "../../utils/minix/prescribing";

import {formatPicture} from "@/utils/picture";
import {CC_Dosage2Basis} from '@/utils/medicine';
import AiEModal from '@/components/AiEModal.vue';
import {tryRun} from '@/tool';

const reasonableSafeMedicine = new ReasonableSafeMedicine();

export default {
  mixins: [prescribing],
  components: {
    AiEModal,
    Popup,
    chineseMedicine,
    medicineChinese,
    // suitScience,
    AcupointTable,
    TCMDiagnosis,
    submitRecipe,
    prescription,
    UnifyPrescription,
    PrescriptionUnifySuit,
    PrescriptionSuit,
    TongueAnalysis,
    doctorCase,
    safeDrug,
    medAdress,
    medAdressNew,
    SuitTechAgreement,
    SuitTechSidePanel,
    SuitTechAgreementDetail
  },
  data() {
    return {
      AI_MODEL_URL: window.SIX_config.AI_MODEL_URL,
      unifyPrescriptionTitle: window.SIX_config.unifyPrescription,

      recordLoading: false, // 中医电子病历
      tongueAndFaceLoading: false, // 舌面象加载
      tongueAndFaceAnalysis: null, // 舌面象数据
      showTongueAnalysis: false, // 舌象分析弹窗

      showPriview: false, // 展示预览数据
      showDialog: false, // 方剂详情
      showDrug: false, // 药品详情
      showAgree: false, // 协定方
      showTestCase: false, // 名医医案
      showRecord: false, // 就诊记录
      showXuewei: false, // 穴位详情信息

      showTestCase: false, // 名医医案
      isTuiDaoSuit: false, //适宜技术处方是否推导过
      isTuiDaoZj: false, // 中药制剂是否推导过
      isTuiDaoZy: false, // 中药处方是否推导过
      raDoseShow: false,
      tjRecipeId: "", // 当前选中推荐 方剂的 id（中药处方/制剂用）
      suitTjRecipeId: "", // 适宜技术专用高亮 id（独立于 tjRecipeId，避免跨 tab 串扰）
      suitActiveSafety: [], // 适宜技术右侧「安全合理检测」项目（传给 SuitTechSidePanel :safetyItems）
      // 顶层协定方详情弹窗（查询弹窗点行查看；提升到顶层避免被查询弹窗 mask 遮挡）
      suitDetailShow: false,
      suitDetailData: {},
      suitDetailLoading: false,
      suitDetailPid: "",
      suitDetailTitle: "我的协定方", // 顶层详情弹窗标题（医派协定方=「医派协定方」）
      suitDetailMode: "agreement", // 顶层详情弹窗底部模式（unify=医派+科室）
      _prescribingInited: false,

      isMyMade: true, // 是否是自拟处方

      showExpr: false, // 专家经验
      priviewData: {}, // 预览数据
      exprInfo: {}, // 专家经验信息
      // 名医弹窗信息
      testCaseInfo: {},
      // 就诊记录 弹窗信息
      recordInfo: {},
      //药品弹窗信息
      drugInfo: {},
      xwinfo: {},
      // 方剂弹窗信息
      preInfo: {},
      // 协定方弹窗信息
      agreeInfo: {},
      // 右侧搜索
      agree_key: "",
      agree_key1: "",
      key: "",
      // 推荐方剂 下标
      r_current: 0,
      // 协定方下标
      agree_current: 0,
      // 协定方手风琴 选中
      activeNames: "0",
      activeNamesLast: "0",
      // 右侧手风琴面板数据
      collapseData: [
        {
          name: "个人",
          index: "0",
          page: 1,
          loadMore: true,
          list: []
        },
        {
          name: "二级科室",
          index: "1",
          page: 1,
          loadMore: true,
          list: []
        },
        {
          name: "科室",
          index: "2",
          page: 1,
          loadMore: true,
          list: []
        },
        {
          name: "本院",
          index: "3",
          page: 1,
          loadMore: true,
          list: []
        }
      ],

      // 右侧方剂列表
      rPrescription: {
        list: [],
        page: 1,
        loadMore: true,
        key: ""
      },
      // 右侧参考医案
      rDoctorCase: {
        list: [],
        page: 1,
        loadMore: true,
        key: ""
      },
      /**
       * 合理安全用药解析数据
       */
      reasonableSafeMedicinesHTML: '',
      reasonableSafeMedicinesLoading: false,
      rationalMed: [],
      // 从1-9 分别对应 超剂量 到 19反
      rationalMed1: [],
      rationalMed2: [],
      rationalMed3: [],
      rationalMed4: [],
      rationalMed5: [],
      rationalMed6: [],
      rationalMed7: [],
      rationalMed8: [],
      rationalMed9: [],
      rationalMed10: [],
      // 右侧推荐方剂
      rRecomendR: [],
      // 中间顶部tab
      container_i: 0,
      /* 下列顺便不能轻易变动 */
      contentTabs: [
        {
          id: '0',
          businesstype: '1',
          name: "中药处方",
          check: true,
          hide: true,
          color: '',
        },
        {
          id: '1',
          businesstype: '2',
          name: "中药制剂",
          check: false,
          hide: true,
          color: ""
        },
        {
          id: '2',
          businesstype: '7', // 适宜技术 businesstype 由 '3' 改为 '7'
          name: "适宜技术处方",
          check: false,
          hide: true,
          color: ""
        }
      ],
      patiensMsg: {}, // 患者信息
      patientMsgPreviewImages: [], // 患者信息预览图片
      dianosisMsg: [], // 诊断信息
      westernDiag: '', // 西医主诊断
      suggestDiag: [], // 建议诊断
      suggestDiagAll: [], // 建议诊断候选
      // 西医诊断搜索相关
      westernDiseaseOptions: [],
      westernDiseaseNameMap: {},
      westernDiseaseSearch: '',
      westernDiseasePage: 1,
      westernDiseaseHasMore: true,
      westernDiseaseLoading: false,

      ops: {
        vuescroll: {},
        scrollPanel: {},
        rail: {
          keepShow: true
        },
        bar: {
          hoverStyle: true,
          onlyShowBarOnScroll: false, //是否只有滚动的时候才显示滚动条
          background: "#C1C1C1", //滚动条颜色
          opacity: 0.5, //滚动条透明度
          "overflow-x": "hidden"
        }
      },
      showSubmit: true,

      // refs 信息暂存
      chineseM: {
        allMoney: 0,
        recipeTabs: []
      },
      medicineC: {
        allMoney: 0
      },
      suitScience: {
        allMoney: 0
      }
    };
  },
  created() {
    try { this._updateContentTabs(this.getuserinfo.ableprescription); } catch (_) { }
    // console.log(this.getIsSee, 'issee');
    this.showSubmit = String(this.getIsSee) == "true" ? true : false;

    // 获取右侧协定方数据
    this.getAgreeRecipe();

    if (this.getPatiensInfo.pid) {
      this.getPatiensBasisM();
      this.getPatientBasisTongueAndFaceAnalysis();
    }
  },
  mounted() {
    this._processRouteQuery().finally(() => {
      this._prescribingInited = true;
      if (this.container_i === 0) this.openAddress();
    });
  },
  beforeRouteLeave(to, from, next) {
    // console.log('query===处方页面跳转', to.path);
    if (to.path == "/index/recipe") {
      // console.log('清缓存', to.path);
      sessionStorage.removeItem("prescr" + this.getPatiensInfo.pid);
      next();
    } else {
      // console.log('存缓存', to.path);   
      this._setDataToStorage(next);
    }
  },

  watch: {
    'getuserinfo.ableprescription': {
      immediate: true,
      handler(value) {
        if (value) this._updateContentTabs(value);
      },
    },
    rationalMed10: {
      deep: true,
      immediate: true,
      handler: function() {
        this.countDose();
      }
    }
  },
  methods: {
    /**
     * 校验转方数据中是否有已支付的项目
     * @param {Array|Object} data - 转方数据（可以是数组或单个对象）
     * @param {string} nameField - 项目名称字段名（默认 'treatItemName'）
     * @returns {Object} { valid: boolean, filteredData: Array, skippedPaid: Array }
     */
    checkPaidProjects(data, nameField = 'treatItemName') {
      const acupointTable = this.$refs.suitScience;
      const paidNames = new Set();

      // 获取开方页面已支付的项目名称
      if (acupointTable && acupointTable.prescriptions) {
        acupointTable.prescriptions.forEach((p, i) => {
          const presData = acupointTable.prescriptionDataMap[i];
          if (p.itemName && presData && presData.paystate == 1) {
            paidNames.add(p.itemName);
          }
        });
      }

      // 如果没有已支付项目，直接返回
      if (paidNames.size === 0) {
        return { valid: true, filteredData: Array.isArray(data) ? data : [data], skippedPaid: [] };
      }

      const skippedPaid = [];
      const dataList = Array.isArray(data) ? data : [data];

      // 只过滤已支付的项目（已存在但未支付的项目会覆盖）
      dataList.forEach((item) => {
        const list = item.treatmentList?.length ? item.treatmentList : item.detail;
        if (!Array.isArray(list)) return;
        for (let i = list.length - 1; i >= 0; i--) {
          const itemName = list[i][nameField];
          // 检查是否已支付
          if (paidNames.has(itemName)) {
            skippedPaid.push(itemName);
            list.splice(i, 1);
          }
        }
      });

      // 检查是否还有数据
      const hasData = dataList.some((item) => {
        const list = item.treatmentList?.length ? item.treatmentList : item.detail;
        return Array.isArray(list) && list.length > 0;
      });

      return {
        valid: hasData,
        filteredData: dataList,
        skippedPaid
      };
    },

    async loadRecord(tips = true) {
      this.recordLoading = true;
      try {
        let data = await refreshElectronicInfo({
          patientId: this.getPatiensInfo.pid
        });
        if (data.outpatientElectronicmedicalrecord) {
          data.outpatientElectronicmedicalrecord.image1 = formatPicture(data.outpatientElectronicmedicalrecord.image1);
          this.patientMsgPreviewImages = [...data.outpatientElectronicmedicalrecord.image1];
        }
        this.patiensMsg = {...this.patiensMsg, ...data};
        if (tips) this.$message.success('刷新成功');
      } catch (e) {
        if (tips) this.$message.error(e.message);
      }
      this.recordLoading = false;
    },
    // 处理路由参数
    async _processRouteQuery() {
      const query = this.$route.query || {};
      // 暂存处方数据（不含药品）
      if (sessionStorage.getItem("prescr" + this.getPatiensInfo.pid)) await this._showDataFromStorage(true);
      // 名医名方 —> 方剂查询
      if (query.recipeID && query.kjType === "kj-fj") await this.getPreDetal(query.recipeID);
      // 就诊记录转方
      else if (query.recipeID) await this.getRecipeDataByid(this.$route.query.recipeID);
      // 适宜技术病历转方
      else if (query.suitRecordId) await this.suitTechRecordTurn(query.suitRecordId,this.getPatiensInfo.pid);
      // 处方管理 适宜技术转方
      // else if (query.suitRecipeId) await this.suitRecipeIdTurn(query.suitRecipeId);
      // 名医名方 —> 名医医案
      else if (query.doctorCase) await this.changeAndJoin();
      // 中医诊疗 -> 智能辨证
      else if (query.type === "tuidao") {
        this.isTuiDaoSuit = false;
        this.isTuiDaoZy = false;
        this.isTuiDaoZj = false;
        await this.inferRecipe();
        const current = this.contentTabs[this.container_i];
        if (!current) return;
        if (current.id === '0') this.isTuiDaoZy = true
        else if (current.id === '1') this.isTuiDaoZj = true
        else if (current.id === '2') this.isTuiDaoSuit = true
      }
      // 处方编辑 recipeType
      else if (query.from !== 'his' && this.getEditPreNo()) await this.getRecipeDataByid(this.getEditPreNo());
      // 暂存处方
      else if (sessionStorage.getItem("prescr" + this.getPatiensInfo.pid)) await this._showDataFromStorage();
      // 历史处方
      else {
        // 跟据就诊记录id获取处方号
        let res = await getPreNumber({pid: this.getPatiensInfo.pid}).catch(() => void 0);
        const has = res && res.ResultCode == 0 && res.Data.length > 0;
        if (has) await this.getRecipeShowData();

        else if (this.getEditPreNo()) await this.getRecipeDataByid(this.getEditPreNo());
      }
    },
    _hackUpdateContentTab(id) {
      setTimeout(() => {
        try {
          const el = this.$el.querySelector(`[data-tab-prescribing="${id}"]`);
          el.style.display = 'flex'
        } catch (_) {}
      }, 1000);
    },
    _updateContentTabs(value) {
      if (!value) return;
      const tabs = value.split(',');
      for (const id of tabs) {
        const index = this.contentTabs.findIndex(item => item.id === id);
        if (index !== -1) this.$set(this.contentTabs, index, {...this.contentTabs[index], hide: false});
        this._hackUpdateContentTab(id);
      }
      // 设置 container_i 为第一个可见的 tab
      const firstVisible = this.contentTabs.findIndex(tab => !tab.hide);
      if (firstVisible !== -1) {
        this.container_i = firstVisible;
      }
    },

    // 中医诊断推导点击
    async tcmClick(isauto = true) {
     this.isTuiDaoZy = false;
     this.isTuiDaoZj = false;
     this.isTuiDaoSuit = false;
      let params = this.$refs.TCM.getParams();

      if (!params.namemedicine || !params.syndrometypes) {
        this.$message.warning("请完善病名证型信息");
        return;
      }

      let newDiaMsg = this.$refs.TCM.getDiamsg();

      this.agree_key1 = params.namemedicine;
      this.patiensMsg.maindiagnosis.disCode = newDiaMsg.disCode;
      this.patiensMsg.maindiagnosis.symptomCode = newDiaMsg.symptomid;
      this.patiensMsg.maindiagnosis.therapyCode = newDiaMsg.therapyCode;
      this.patiensMsg.maindiagnosis.disid = newDiaMsg.disid;
      this.patiensMsg.maindiagnosis.symptomid = newDiaMsg.symptomid;
      this.patiensMsg.maindiagnosis.treatment = newDiaMsg.treatment;

      const current = this.contentTabs[this.container_i];
      if (current) {
        const loading = this.$loading({
          lock: true,
          text: `正在获取推荐处方数据`,
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        });
        try {
          const business = this.contentTabs.filter(tab => !tab.hide).map(tab => tab.businesstype).join(',');
          const results = await legacyDeduceIllnessPrescriptionMethod(business, this.patiensMsg.maindiagnosis);
          if (results.index == null) this.$message.warning(`暂无推荐处方`);
          else {
            if (isauto && current.id !== '1') await this.inferRecipe(2, current.businesstype, results[current.businesstype]);
            for (const tab of this.contentTabs) {
              if (tab.hide) continue;
              const type = tab.id === '1' && tab.id === current.id ? 3 : 4;
              this.inferRecipe(type, tab.businesstype, results[tab.businesstype]).then(() => {
                if (tab.id === current.id) {
                  if (current.id === '0') this.isTuiDaoZy = true;
                  else if (current.id === '1') this.isTuiDaoZj = true;
                  else if (current.id === '2') this.isTuiDaoSuit = true;
                }
              });
            }
            // 不管当前在哪个 tab 点推导，适宜技术都自动填入第一个推荐方案内容
            if (current.id !== '2' && results['7']) {
              this.fillSuitTechOnInfer(results['7']);
            }
            if (this.getPatiensInfo.pid) await this.getPatiensBasisM();
          }
        } catch (_) {}
        loading.close();
      }

      // 获取最新病名的参考医案
      this.rDoctorCase.page = 1;
      this.rDoctorCase.list = [];
      this.rDoctorCase.loadMore = true;
      await this.getDoctorCaseL();
      // --end
    },
    // 系统数据存入缓存
    _setDataToStorage(next) {
      let children = this.$children.filter(item => {
        return (
          item.name == "中药处方" ||
          item.name == "中药制剂" ||
          item.name == "适宜技术处方"
        );
      });

      let child1 = children[0];
      let child2 = children[1];
      let child3 = children[2];

      // 适宜技术：存前先把当前活动处方页的编辑同步进 prescriptionDataMap
      if (child3 && child3.saveCurrentTabData) child3.saveCurrentTabData();

      let obj = {
        contentTabs: this.contentTabs,
        container_i: this.container_i,
        rRecomendR: this.rRecomendR,
        suggestDiag: this.suggestDiag,
        suggestDiagAll: this.suggestDiagAll,
        suitTjRecipeId: this.suitTjRecipeId,
        child1: {
          recipe_tabs: child1.recipe_tabs,
          recipe_tabs_c: child1.recipe_tabs_c
        },
        child2: {
          tableData3: child2.tableData3,
          bottom_form: child2.bottom_form
        },
        child3: Object.assign({...child3.$data}, {acupointList: []}),
        rationalMed: {
          // 保存右侧合理用药信息
          rationalMed: this.rationalMed,
          // 从1-9 分别对应 超剂量 到 19反
          rationalMed1: this.rationalMed1,
          rationalMed2: this.rationalMed2,
          rationalMed3: this.rationalMed3,
          rationalMed4: this.rationalMed4,
          rationalMed5: this.rationalMed5,
          rationalMed6: this.rationalMed6,
          rationalMed7: this.rationalMed7,
          rationalMed8: this.rationalMed8,
          rationalMed9: this.rationalMed9,
          rationalMed10: this.rationalMed10
        }
      };

      sessionStorage.setItem(
        "prescr" + this.getPatiensInfo.pid,
        JSON.stringify(obj)
      );
      next();
      // getPatiensInfo
    },
    // 展示系统缓存数据
    async _showDataFromStorage(ignoreTable = false) {
      let storageData = JSON.parse(
        sessionStorage.getItem("prescr" + this.getPatiensInfo.pid)
      );
      let children = this.$children.filter(item => {
        return (
          item.name == "中药处方" ||
          item.name == "中药制剂" ||
          item.name == "适宜技术处方"
        );
      });
      let child1 = children[0];
      let child2 = children[1];
      let child3 = children[2];

      child1.recipe_tabs = storageData.child1.recipe_tabs;
      child1.recipe_tabs_c = storageData.child1.recipe_tabs_c;
      // 仅在 （中药处方）时才弹「请和患者确认信息」地址窗，
      this.contentTabs = storageData.contentTabs;
      this.container_i = storageData.container_i;
      if (typeof child1.loaded === 'function') await child1.loaded(storageData.child1);

      if (storageData.child1.recipe_tabs[0].totalTableD.length > 1) {
        this.isTuiDaoZy = true;
      }

      const suitPres = storageData.child3.prescriptions;
      if ((suitPres && suitPres.length > 0) || (storageData.child3.tableData4 && storageData.child3.tableData4.length > 1)) {
        this.isTuiDaoSuit = true;
      }

      if (ignoreTable) {
        for (const recipe of storageData.child1.recipe_tabs) {
          recipe.tableData = [];
          recipe.tableData1 = [];
          recipe.totalTableD = [];
        }
        storageData.child2.tableData3 = [];
        storageData.child3.tableData4 = [];
      }
      this.rRecomendR = Array.isArray(storageData.rRecomendR) ? storageData.rRecomendR : [];
      this.suggestDiag = Array.isArray(storageData.suggestDiag) ? storageData.suggestDiag : [];
      this.suggestDiagAll = Array.isArray(storageData.suggestDiagAll) ? storageData.suggestDiagAll : [];
      (this.suggestDiagAll || []).forEach(it => {
        if (it && it.westcode && it.westname) this.westernDiseaseNameMap[it.westcode] = it.westname;
      });
      this.suitTjRecipeId = storageData.suitTjRecipeId || "";
      // child1.getSelectType("剂型", 0);
      // child1.getSelectType("处方用法");
      // child1.getSelectType("中药服药时间");
      // child1.getSelectType("中药频次");
      // child1.getPharmacyID();
      child2.tableData3 = storageData.child2.tableData3;
      child2.bottom_form = storageData.child2.bottom_form;

      for (const [key, value] of Object.entries(storageData.child3)) child3[key] = value;

      this.rationalMed = storageData.rationalMed.rationalMed;
      // 保存右侧合理用药信息
      tryRun(() => { if (this.container_i === 0) child1._checkReasonableSafeMedicines(); });

      // 从1-9 分别对应 超剂量 到 19反
      this.rationalMed1 = storageData.rationalMed.rationalMed1;
      this.rationalMed2 = storageData.rationalMed.rationalMed2;
      this.rationalMed3 = storageData.rationalMed.rationalMed3;
      this.rationalMed4 = storageData.rationalMed.rationalMed4;
      this.rationalMed5 = storageData.rationalMed.rationalMed5;
      this.rationalMed6 = storageData.rationalMed.rationalMed6;
      this.rationalMed7 = storageData.rationalMed.rationalMed7;
      this.rationalMed8 = storageData.rationalMed.rationalMed8;
      this.rationalMed9 = storageData.rationalMed.rationalMed9;
      this.rationalMed10 = storageData.rationalMed.rationalMed10;
    },
    // 方剂顶部搜索
    searchPre() {
      if (this.agree_current == 1) {
        this.rPrescription.page = 1;
        this.rPrescription.list = [];
        this.rPrescription.loadMore = true;
        this.getPrescriptionsList();
      } else if (this.agree_current == 2) {
        this.rDoctorCase.page = 1;
        this.rDoctorCase.list = [];
        this.rDoctorCase.loadMore = true;
        this.getDoctorCaseL();
      }
    },
    // 方剂加载更多
    loadMorePre() {
      if (this.agree_current == 1) {
        if (!this.rPrescription.loadMore) {
          this.$message({
            showClose: false,
            message: "没有更多数据了",
            type: "warning "
          });
          return;
        }
        this.getPrescriptionsList(this.rPrescription.loadMore);
      } else if (this.agree_current == 2) {
        if (!this.rDoctorCase.loadMore) {
          this.$message({
            showClose: false,
            message: "没有更多数据了",
            type: "warning "
          });
          return;
        }
        this.getDoctorCaseL(this.rDoctorCase.loadMore);
      }
    },
    // 加载更多协定方数据
    loadMoreCollapse(item) {
      if (!item.loadMore) {
        this.$message({
          showClose: false,
          message: "没有更多数据了",
          type: "warning "
        });
        return;
      }
      this.getAgreeRecipe(item.loadMore);
    },
    // 手风琴 更改
    activeChange(e) {

      // if (this.activeNames == e) return;
      if (e) {
        this.activeNames = e;
        this.activeNamesLast = e;

        this.collapseData[this.activeNames].page = 1;
        this.collapseData[this.activeNames].loadMore = true;
        this.collapseData[this.activeNames].list = [];
        this.getAgreeRecipe(this.collapseData[this.activeNames].loadMore);
      } else {
        this.activeNames = this.activeNamesLast;
      }
    },
    // 处理中药处方提交数据
    dealRecipe1(data1) {
      let isAutoCheck = data1.isAutoCheck;
      let hasDoseNum = true; // 是否有剂数
      let hasData = true; // 是否有处方药品数据
      let hasAddress = true;
      let noFull = false; // 是否有药品库存不足
      let recipeAlert = [];
      data1.recipe_tabs.forEach((item, index) => {
        if (item.isMyMade) {
          this.addRecipeFrom("3");
        }

        if (!item.bottom_form.doseNum) {
          hasDoseNum = false;
        }
        if (item.bottom_form.radio == "0" && !item.bottom_form.savename) {
          hasAddress = false;
        }
        if (item.bottom_form.radio == "0" && !item.bottom_form.phone) {
          hasAddress = false;
        }

        if (item.bottom_form.radio == "0" && !item.bottom_form.province) {
          hasAddress = false;
        }

        if (item.bottom_form.radio == "0" && !item.bottom_form.city) {
          hasAddress = false;
        }

        if (item.bottom_form.radio == "0" && !item.bottom_form.area) {
          hasAddress = false;
        }
        if (item.bottom_form.radio == "0" && !item.bottom_form.address) {
          hasAddress = false;
        }

        if (item.totalTableD.length < 2) {
          hasData = false;
        }

        if (item.totalTableD.length - 1 < this.doseMin) {
          recipeAlert.push({
            text: `中药处方${index + 1}不符合最小药味数${this.doseMin}！`,
            isAllow: this.doseAllowMin
          });
        }

        if (item.totalTableD.length - 1 > this.doseMax) {
          recipeAlert.push({
            text: `中药处方${index + 1}不符合最大药味数${this.doseMax}！`,
            isAllow: this.doseAllowMax
          });
        }

        item.totalTableD.forEach(item1 => {
          if (item1.color == "red") {
            noFull = true;
          }
          if (!+item1.dose && item1.name) {
            hasDoseNum = false;
          }
        });
      });
      if (!hasData) {
        this.$message.error({
          message: "请完善中药处方药品信息",
          showClose: true,
          type: "error"
        });
        return [];
      }

      if (recipeAlert.length > 0) {
        recipeAlert.forEach(item => {
          if (item.text) {
            setTimeout(() => {
              this.$message({
                message: item.text,
                showClose: true,
                type: "warning"
              });
            }, 200);
          }
        });

        // return false;
      }
      // if (!hasAddress) {
      //   this.$message({
      //     message: "请完善中药处方配送信息",
      //     showClose: false,
      //     type: "error"
      //   });
      //   return false;
      // }
      if (!hasDoseNum) {
        this.$message.error({
          message: "请完善中药处方剂数剂量信息",
          showClose: false,
          type: "error"
        });
        return false;
      }

      if (noFull) {
        this.$message.error({
          message: "部分药品库存不足",
          showClose: false,
          type: "error"
        });
        return false;
      }
      // let data2 = children[1]
      // let data3 = children[2]
      let zhongPrescriptionVo = [];
      let medAdressData = {};
      if (this.showAddress) {
        medAdressData = this.$refs.medAdress.form;
      }

      // console.group("debug:20250558")
      data1.recipe_tabs.forEach((item, index) => {
        // console.log("填写值", item.bottom_form.radio)
        let obj = {
          seqn: index + 1,
          province:
            this.isShowPs && this.showAddress ? medAdressData.province : "", // 省
          city: this.isShowPs && this.showAddress ? medAdressData.city : "", // 市
          district: this.isShowPs && this.showAddress ? medAdressData.area : "", // 区
          address:
            this.isShowPs && this.showAddress ? medAdressData.address : "", // 详细地址
          agency: item.bottom_form.isDaiJian, // 代煎
          // agency: this.showAddress ? medAdressData.isDaiJian : 0, // 代煎
          // agency: this.isShowDj ? this.isDaiJian : 0, // 代煎
          allprice: item.bottom_form.allMoney, // 总金额(合计金额)
          command: item.bottom_form.zhutuo, // 嘱托
          consigneeName:
            this.isShowPs && this.showAddress ? medAdressData.savename : "", // 收货人姓名
          consigneePhone:
            this.isShowPs && this.showAddress ? medAdressData.phone : "", // 收货人电话
          deliveryfree:
            medAdressData.radio == 0 && this.isShowPs && this.showAddress
              ? item.bottom_form.moneyMsg.deliveryPrice
              : 0, // 配送费
          deploymentfree:
            item.bottom_form.doseType == "2" || item.bottom_form.doseType == "3"
              ? item.bottom_form.moneyMsg.specialDeploymentPrice
              : 0, // 特殊调配费
          dosageForm: item.bottom_form.doseType, // 剂型

          eatMedicineTime: item.bottom_form.time, // 服药时间
          frequency: item.bottom_form.num, // 频次
          friedfree: item.bottom_form.daijian
            ? item.bottom_form.moneyMsg.agencyPrice
            : 0, // 代煎费
          // isdelivery: this.isPs == 1 ? 0 : 1, // 是否配送
          isdelivery: item.bottom_form.radio,
          markfree:
            item.bottom_form.doseType == "0"
              ? item.bottom_form.moneyMsg.systemOfCreamPrice
              : 0, // 制膏费
          num: item.bottom_form.doseNum, //剂数
          pharmacyid: item.pharmacyID, // 药房id 暂时写死
          drugtype: item.radio.split("@")[1], // 药房类型
          price: item.bottom_form.nowRecipeMoney, // 单剂金额
          recordid: this.getPatiensInfo.pid, //门诊id
          strongFried: item.bottom_form.nongjian, //浓煎
          type: 0, // 处方类型
          useexplain: item.bottom_form.caozuo, // 操作指南
          usestr: item.bottom_form.usege, //处方用法
          zhongdetail: [], // 中药明细 表格内部数据
          // preId: this.$route.query.recipeID ? this.$route.query.recipeID : ""
          preId: item.preId || "",
        };
        // console.log("保存值", obj.isdelivery)
        item.totalTableD.forEach(item1 => {
          if (item1.name && item1.color != "red") {
            let obj1 = {
              allprice: item1.total,
              dose: Number(item1.dose),
              drugName: item1.name,
              drugid: item1.medid,
              platformdrugid: item1.matid,
              origin: item1.originname,
              seqn: item1.id,
              specification: item1.spec,
              unit: item1.unit,
              unitprice: item1.price,
              usagestr: item1.usage,
              preDetailId: this.getEditPreNo(),
            };
            obj.zhongdetail.push(obj1);
          }
        });

        if (!recipeAlert[index]) {
          recipeAlert.push({
            isAllow: 0
          });
        }
        // 当前审核流程为自动时 用his 的支付状态判断
        // if (isAutoCheck == 1) {

        // } else {
        //   if (
        //     !item.isPay &&
        //     (item.prescribed == 0 || !item.prescribed) &&
        //     recipeAlert[index].isAllow == 0
        //   ) {
        //     zhongPrescriptionVo.push(obj);
        //   }
        // }
        if (
          (item.paystate == 0 || !item.paystate) &&
          recipeAlert[index].isAllow == 0
        ) {
          zhongPrescriptionVo.push(obj);
        }
      });
      console.groupEnd()
      return zhongPrescriptionVo;
    },
    // 处理中药制剂提交数据
    dealRecipe2(data1) {
      let isAutoCheck = data1.isAutoCheck;
      if (!data1.tableData3.filter(item => item.name).length) {
        this.$message.error({ message: '请完善中药制剂药品信息', showClose: true });
        return {};
      }
      let hasDrugMsg = [];
      data1.tableData3.forEach((item, index) => {
        if (
          item.name &&
          (!item.dose || !item.usage || !item.timesQuan || !item.nums)
        ) {
          // ||  !item.time

          hasDrugMsg.push(index + 1);
        }
      });

      if (hasDrugMsg.length > 0) {
        this.$message.error(
          "请完善中药制剂处方药品相关信息(序号:" + hasDrugMsg.join(",") + ")"
        );
        return false;
      }
      let hasAddress = true;

      let medAdressData = {};
      if (this.showAddress) {
        medAdressData = this.$refs.medAdress.form;
      }

      this.addRecipeFrom("3");

      let obj = {
        province:
          this.showAddress && this.isShowPs ? medAdressData.province : "", // 省
        city: this.showAddress && this.isShowPs ? medAdressData.city : "", // 市
        district: this.showAddress && this.isShowPs ? medAdressData.area : "", // 区
        address: this.showAddress && this.isShowPs ? medAdressData.address : "",
        command: data1.bottom_form.zhutuo,
        consigneeName:
          this.showAddress && this.isShowPs ? medAdressData.savename : "",
        consigneePhone:
          this.showAddress && this.isShowPs ? medAdressData.phone : "",
        isdelivery: data1.bottom_form.radio,
        // isdelivery: this.isPs == 0 ? 1 : 0,
        deliveryfree:
          this.showAddress && this.isShowPs && medAdressData.radio == 0
            ? data1.moneyMsg.deliveryPrice
            : 0, // 配送费
        pharmacyid: data1.pharmacyID,
        type: 1,
        chengDetail: [],
        // preId: this.$route.query.recipeID ? this.$route.query.recipeID : ""
        preId: data1.preId || "",
      };

      data1.tableData3.forEach(item => {
        if (item.name) {
          let obj1 = {
            allprice: item.total,
            dose: item.dose,
            drugName: item.name,
            drugid: item.medid,
            frequency: item.nums,
            medicationtime: item.time,
            origin: item.from,
            price: item.price,
            secondDose: item.timesQuan,
            seqn: item.id,
            specification: item.spec,
            unit: item.unit,
            usagestr: item.usage,
            preDetailId: this.getEditPreNo(),
            bzdw: item.doseUnit,
            zxdw: item.timesUnit
          };

          obj.chengDetail.push(obj1);
        }
      });

      // if ((data1.isPay || data1.prescribed == 1) && isAutoCheck == 0) {
      //   return {};
      // }
      // && isAutoCheck == 1
      if (data1.paystate == 1) {
        return {};
      }

      return obj;
    },
    // 处理适宜剂数处方提交数据
    dealRecipe3(data1) {
      try {
      // 新版 AcupointTable 组件
      const acupointTable = this.$refs.suitScience;
      if (!acupointTable) {
        this.$message.error({ message: '适宜技术处方组件未加载', showClose: true });
        return [];
      }

      // 校验：至少有一个处方
      if (!acupointTable.prescriptions || acupointTable.prescriptions.length === 0) {
        this.$message.error({ message: '请先新增适宜技术处方', showClose: true });
        return [];
      }

      // 过滤掉已付费的处方
      const unpaidPrescriptions = acupointTable.prescriptions
        .map((p, index) => ({ p, index }))
        .filter(({ index }) => {
          const data = acupointTable.prescriptionDataMap[index];
          return !data || (!data.isPay && data.paystate != 1);
        });

      // 校验操作指南
      const hasOperationGuide = unpaidPrescriptions.every(({ index }) => {
        const d = acupointTable.prescriptionDataMap[index];
        return d && d.operationGuide && d.operationGuide.trim();
      });
      if (!hasOperationGuide) {
        this.$message.error({ message: '请完善适宜技术处方操作指南', showClose: true });
        return [];
      }

      // 校验单次数量
      const hasSingleCount = unpaidPrescriptions.every(({ index }) => {
        const d = acupointTable.prescriptionDataMap[index];
        return d && d.singleCount > 0;
      });
      if (!hasSingleCount) {
        this.$message.error({ message: '请完善适宜技术处方单次数量', showClose: true });
        return [];
      }

      // 获取治疗列表
      const treatmentList = acupointTable.buildTreatmentList();
      if (!treatmentList || treatmentList.length === 0) {
        this.$message.error({ message: '请完善适宜技术处方信息', showClose: true });
        return [];
      }

      const recordid = this.getPatiensInfo.pid || "";

      const result = unpaidPrescriptions.map(({ p, index }, treatmentIndex) => {
        const treatmentItem = treatmentList[treatmentIndex];
        const d = acupointTable.prescriptionDataMap[index] || {};

        // 计算该项目的总金额
        const singleAmount = parseFloat(d.singlePrice) || 0;
        const treatCount = d.treatCount || 0;
        const projectTotal = singleAmount * treatCount;

        return {
          accordPid: recordid,
          num: treatCount,
          thisRecipePrice: singleAmount,
          totalAmount: projectTotal,
          command: d.command || "",
          useexplain: d.operationGuide || "",
          type: "2",
          sourceId: recordid,
          sourceType: "2",
          suggestDiag: Array.isArray(this.suggestDiag) ? this.suggestDiag.join(',') : (this.suggestDiag || ""),
          westernDiag: this.westernDiag || "",
          treatmentList: [treatmentItem],
        };
      });

      if (acupointTable.isMyMade) {
        this.addRecipeFrom("3");
      }

      return result;
      } catch (error) {
        console.error('dealRecipe3异常:', error);
        this.$message.error({ message: '处理适宜技术处方数据时发生错误', showClose: true });
        return [];
      }
    },
    // 获取数据 赋值给 中药处方
    assignRecipe1(data, loading) {
      setTimeout(() => {
        let children = this.$children.filter(item => {
          return (
            item.name == "中药处方" ||
            item.name == "中药制剂" ||
            item.name == "适宜技术处方"
          );
        });

        let data1 = children[0];
        let isAutoCheck = data1.isAutoCheck;
        let arr = [];
        data.forEach((item, index) => {
          let objAssaign = {};
          // let medAdressData = this.$refs.medAdress;
          let obj = {
            name: "处方1",
            pharmacyID: "", // 药房id
            totalTableD: [],
            tableData: [
              {
                id: 1
              }
            ],
            radio: "1",
            tableData1: [],
            bottom_form: {
              doseNum: "",
              doseType: "",
              doseTypeList: [],
              usegeList: [],
              usege: "",
              num: "",
              numList: [], // 频次后台数据
              daijian: "",
              nongjian: "",
              time: "",
              timeList: [], // 服药时间后台数据
              caozuo: "",
              zhutuo: "",
              radio: item.isdelivery,
              daijian: "1",
              provinceList: [],
              cityList: [],
              areaList: [],
              province: "",
              city: "",
              area: "",
              address: "",
              phone: "",
              doseType1: "",
              doseNum1: "",
              savename: "",
              nowRecipeMoney: 0, //单剂金额
              nowRecipeMoney1: 0, //当前处方金额
              allMoney: 0, // 合计金额

              moneyMsg: {} // 价格数据
            },
            prescribed: 0, //是否开方  0 否 1 是,
            paystate: 0,
            preId: null
          };

          // if (
          //   index == data.length - 1 &&
          //   item.prescribed == 1 &&
          //   isAutoCheck == 0
          // ) {
          //   objAssaign = JSON.parse(JSON.stringify(obj));
          // }
          // && isAutoCheck == 1
          if (index == data.length - 1 && item.paystate == 1) {
            objAssaign = JSON.parse(JSON.stringify(obj));
          }
          if (this.$route.query.type == "edit") {
          } else {
          }
          obj.preId = item.preId ? item.preId : "";
          obj.name = "处方" + (index + 1);

          obj.radio = item.pharmacyid + "@" + item.drugtype;
          obj.pharmacyID = item.pharmacyid;
          obj.bottom_form.doseNum = item.num;
          obj.bottom_form.doseType = item.dosageForm;
          obj.bottom_form.usege = item.usestr;
          obj.bottom_form.nongjian = item.strongFried;
          obj.bottom_form.num = item.frequency;
          obj.bottom_form.caozuo = item.useexplain;
          obj.bottom_form.zhutuo = item.command;

          if (!!this.getEditPreNo()) {
            if (item.revierwstate == 1 && isAutoCheck == 0) {
              obj.prescribed = 0;
            } else {
              obj.prescribed = item.prescribed;
            }

            obj.paystate = item.paystate;

            // if (isAutoCheck == 1) {

            // }
            console.group("debug:20250558")
            // console.log('配送原始', item.isdelivery);
            obj.bottom_form.radio = item.isdelivery == null ? null : Number(item.isdelivery);
            console.log('配送赋值', obj.bottom_form.radio);
            console.groupEnd()
            obj.bottom_form.savename = item.consigneeName;
            obj.bottom_form.phone = item.consigneePhone;
            obj.bottom_form.address = item.address;
            obj.bottom_form.province = item.province;
            obj.bottom_form.city = item.city;
            obj.bottom_form.area = item.district;

            if (obj.paystate == 1) {
              obj.bottom_form.disable = true;
              obj.disable = true;
            }
          } else {
            obj.prescribed = item.prescribed;
            obj.paystate = item.paystate;

            if (obj.paystate == 1) {
              obj.bottom_form.disable = true;
              obj.disable = true;
            }
          }

          obj.bottom_form.moneyMsg = {
            deliveryPrice: item.deliveryfree,
            specialDeploymentPrice: item.deploymentfree,
            agencyPrice: item.friedfree,
            systemOfCreamPrice: item.markfree
          };
          //

          obj.bottom_form.daijian = item.agency;
          obj.bottom_form.isDaiJian = Number(item.agency);
          // medAdressData.isDaiJian = Number(item.agency);
          obj.bottom_form.nowRecipeMoney = item.price;
          obj.bottom_form.nowRecipeMoney1 = item.thisRecipePrice;
          obj.bottom_form.allMoney = item.allprice;

          obj.bottom_form.time = item.eatMedicineTime;
          // data1.getProver()
          obj.bottom_form.provinceList = data1.provinceList1;

          if (item.isdelivery == "0") {
            data1.recipe_tabs_c = index;
            data1.getArea(item.province, 1);
            data1.getArea(item.city, 2);
          }

          setTimeout(() => {
            data1.recipeChange(index);
          }, 500);

          item.zhongdetail.forEach((item1, index1) => {
            let obj1 = {
              drugList: [],
              page: 1,
              loadMore: true,
              usageList: [],
              id: item1.seqn,
              name: item1.drugName,
              // pid:
              matid: item1.platformdrugid || item1.matid, // 知识库
              matname: item1.platformdrugname, // 知识库
              spec: item1.specification, // 规格
              dose: item1.dose, // 剂量
              unit: item1.unit, // 单位
              // usage: item.usagestr, // 用法
              usage: item1.usagestr,
              price: item1.unitprice,
              total: item1.allprice,
              inventory: item1.instock, // 库存
              key: "",
              search_i: index1,
              medid: item1.drugid, // 药品id
              originname: item1.origin // 产地名称
            };

            obj.totalTableD.push(obj1);
            data1.getSelectType("中药药品用法", index1);
          });
          obj.totalTableD.push({
            drugList: [],
            page: 1,
            loadMore: true,
            usageList: [],
            showSearch: false,
            search_i: 0,
          });
          obj.totalTableD.filter((item3, index3) => {
            return (item3.id = index3 + 1);
          });

          obj.tableData = obj.totalTableD.filter(item2 => {
            return Number(item2.id) % 2 != 0;
          });
          obj.tableData1 = obj.totalTableD.filter(item2 => {
            return Number(item2.id) % 2 == 0;
          });

          arr.push(obj);

          // if (
          //   index == data.length - 1 &&
          //   item.prescribed == 1 &&
          //   isAutoCheck == 0
          // ) {
          //   // arr.push(objAssaign)

          //   setTimeout(() => {
          //     data1.addRecipeTba(arr.length - 1);
          //   }, 500);
          // }
          // && isAutoCheck == 1
          if (index == data.length - 1 && item.paystate == 1) {
            // arr.push(objAssaign)

            setTimeout(() => {
              data1.addRecipeTba(arr.length - 1);
            }, 500);
          }
        });

        data1.recipe_tabs_c = arr.length - 1;
        data1.recipe_tabs = arr;
        data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.radio =
          arr[arr.length - 1].bottom_form.radio;

        data1.changePharmacy(
          arr[arr.length - 1].radio,
          arr[arr.length - 1].radio,
          true,
        );
        data1.$forceUpdate();
        loading.close();
      }, 1000);
    },
    // 获取数据 赋值给 中药制剂
    assignRecipe2(data, loading) {
      setTimeout(() => {
        let children = this.$children.filter(item => {
          return (
            item.name == "中药处方" ||
            item.name == "中药制剂" ||
            item.name == "适宜技术处方"
          );
        });
        let data1 = children[1];
        let isAutoCheck = data1.isAutoCheck;

        data1.bottom_form.zhutuo = data.command;
        data1.preId = data.preId ? data.preId : "";
        if (!!this.getEditPreNo()) {
          data1.bottom_form.radio = data.isdelivery == null ? null : Number(data.isdelivery);
          data1.bottom_form.savename = data.consigneeName;
          data1.bottom_form.phone = data.consigneePhone;
          data1.bottom_form.address = data.address;
          data1.province = data.province;
          data1.city = data.city;
          data1.area = data.district;
          if (data.revierwstate == 1) {
            data1.prescribed = 0; // 是否已开方 0否 1是
            data1.paystate = 0;
          } else {
            data1.prescribed = data.prescribed; // 是否已开方 0否 1是
            data1.paystate = data.paystate;
          }
        } else {
          data1.prescribed = data.prescribed; // 是否已开方 0否 1是
          data1.paystate = data.paystate;
        }
        data1.bottom_form.zhutuo = data.command;

        if (data.province) {
          data1.getArea(data.province, 1);
        }
        if (data.city) {
          data1.getArea(data.city, 2);
        }

        data1.nowRecipeMoney = data.thisRecipePrice;
        data1.allMoney = data.allprice;

        let arr = [];
        data.chengDetail.forEach((item, index) => {
          let obj = {
            id: item.seqn,

            drugList: [],
            search_i: "",
            page: 1,
            loadMore: true,
            usageList: [],
            numList: [],
            timeList: [],

            name: item.drugName,
            spec: item.specification, // 规格
            dose: item.dose, // 剂量
            unit: item.unit, // 单位
            usage: item.usagestr, // 用法

            nums: item.frequency, //频次

            timesQuan: item.secondDose, // 次用量,
            timesUnit: item.zxdw,
            time: item.medicationtime, // 服药时间
            doseUnit: item.bzdw,
            from: item.origin, // 产地
            price: item.price,
            total: item.allprice,
            inventory: item.instock, // 库存
            key: "",
            medid: item.drugid
          };

          data1.getSelectType("中药制剂药品用法", index);
          data1.getSelectType("中药制剂服药时间", index);
          data1.getSelectType("中药制剂频次", index);
          arr.push(obj);
        });
        arr.push({
          key: "",

          page: 1,
          drugList: [],
          usageList: [],
          numList: [],
          timeList: [],
          loadMore: true
        });
        data1.tableData3 = arr;

        data1.tableData3.filter((item, index) => {
          return (item.id = index + 1);
        });
        this.$forceUpdate();
        loading.close();
      }, 1000);
    },
    // 获取数据 赋值给 适宜技术处方
    assignRecipe3(data, loading, append = false) {
      // console.log('适宜技术数据', data);
      setTimeout(() => {
        const acupointTable = this.$refs.suitScience;
        if (!acupointTable) {
          loading.close();
          return;
        }

        // 优先恢复缓存数据（追加模式不恢复缓存）
        if (!append && acupointTable.restoreCachedData()) {
          loading.close();
          return;
        }

        // 兼容数组和对象两种格式，处理数组时合并所有treatmentList
        const dataArray = Array.isArray(data) ? data : [data];
        if (!dataArray.length) {
          loading.close();
          return;
        }

        // 使用第一个数据作为基础处方信息
        const techData = dataArray[0];

        // 追加模式下不覆盖处方元数据和支付状态，只追加治疗项
        if (!append) {
          // 存储处方级字段，提交时需要用到
          console.log('适宜技术处方赋值数据', techData);
          acupointTable._prescriptionMeta = {
            preId: techData.preId || "",
            technologyType: techData.technologyType || "",
            num: techData.num || 0,
            allprice: techData.allprice || 0,
            thisRecipePrice: techData.thisRecipePrice || 0,
            totalAmount: techData.totalAmount || 0,
            prescribed: techData.prescribed || 0,
            paystate: techData.paystate || 0,
            revierwstate: techData.revierwstate || 0,
            command: techData.command || "",
            useexplain: techData.useexplain || "",
            sourceType: techData.sourceType || "",
            westernDiag: techData.westernDiag || "",
          };

          // 西医主诊断（只读，接口返回）和建议诊断（用户输入）
          this.westernDiag = techData.westernDiag || '';
          // 建议诊断候选（后端返回的全部）→ 规范化成对象数组，并预填充 name 映射
          const rawSuggest = techData.suggestDiag;
          const rawArr = typeof rawSuggest === 'string'
            ? rawSuggest.split(',').filter(Boolean)
            : Array.isArray(rawSuggest) ? rawSuggest : [];
          this.suggestDiagAll = rawArr.map(it => {
            if (it && typeof it === 'object') {
              const code = it.westcode || it.code;
              return { westcode: code, westname: it.westname || it.name || code };
            }
            return { westcode: it, westname: this.westernDiseaseNameMap[it] || it };
          });
          this.suggestDiagAll.forEach(it => {
            if (it.westcode) this.westernDiseaseNameMap[it.westcode] = it.westname;
          });
          this.suggestDiag = this.suggestDiagAll.length ? [this.suggestDiagAll[0].westcode] : [];
        }

        // 合并所有数据中的treatmentList
        const mergedTreatmentList = dataArray.reduce((acc, item) => {
          const list = item.treatmentList?.length ? item.treatmentList : item.detail;
          if (Array.isArray(list)) {
            acc.push(...list);
          }
          return acc;
        }, []);

        // 根据模式选择加载方式
        if (mergedTreatmentList.length > 0) {
          if (append) {
            acupointTable.appendFromServerData(mergedTreatmentList);
          } else {
            acupointTable.loadFromServerData(mergedTreatmentList);
          }
        }

        // 追加模式下不覆盖处方状态和支付状态
        if (!append) {
          // 处方状态（必须在 loadFromServerData 之后设置，因为 loadFromServerData 会调用 loadTabData 覆盖 paystate）
          if (this.getEditPreNo()) {
            if (techData.revierwstate == 1) {
              acupointTable.prescribed = 0;
              acupointTable.paystate = 0;
            } else {
              acupointTable.prescribed = techData.prescribed || 0;
              acupointTable.paystate = techData.paystate || 0;
            }
          } else {
            acupointTable.prescribed = techData.prescribed || 0;
            acupointTable.paystate = techData.paystate || 0;
          }

          // 嘱托(command)和支付状态(paystate)在处方级(technologies[i])，loadFromServerData 按治疗项取不到，补设到组件
          const _prescriptionCommand = techData.command || "";
          acupointTable.command = _prescriptionCommand;
          if (acupointTable.prescriptionDataMap) {
            Object.keys(acupointTable.prescriptionDataMap).forEach(idx => {
              acupointTable.prescriptionDataMap[idx].command = _prescriptionCommand;
              // 为每个处方设置支付状态
              const numIdx = Number(idx);
              if (dataArray[numIdx]) {
                acupointTable.prescriptionDataMap[idx].paystate = dataArray[numIdx].paystate || 0;
                acupointTable.prescriptionDataMap[idx].isPay = dataArray[numIdx].isPay || false;
              }
            });
          }
        }

        loading.close();
      }, 500);
    },
    // 协定方数据转方 赋值给中药处方
    agreeAssignToTCM(data, loading, request = true) {
      let children = this.$children.filter(item => {
        return (
          item.name == "中药处方" ||
          item.name == "中药制剂" ||
          item.name == "适宜技术处方"
        );
      });

      let data1 = children[0];
      console.log(data1, "打印data1");
      data1.recipe_tabs[data1.recipe_tabs_c].disable = false;
      if (data.isupdate && data.isupdate === "1") {
        // 专家经验 不允许 修改
        data1.recipe_tabs[data1.recipe_tabs_c].disable = true;
        sessionStorage.setItem("isupdateExpre", "1");
      }

      if (data.type && data.type === "1") {
        // 协定方 不允许 修改
        data1.recipe_tabs[data1.recipe_tabs_c].disable = true;
        sessionStorage.setItem("isupdateExpre", "1");
      }

      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.preType = data.type;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.disable =
        data.type == "1";
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.preType = data.type;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.doseNum = data.num || '';
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.doseType =
        data.curetype;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.nongjian =
        data.density;
      data1.recipe_tabs[
        data1.recipe_tabs_c
      ].bottom_form.specialDeploymentPrice = data.deploymentfree;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.num = data.frequency;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.time =
        data.medicationtime;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.agencyPrice =
        data.fryingfee;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.systemOfCreamPrice =
        data.markfree;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.radio =
        data.prescriptiontype;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.usege = data.usrage;

      data1.recipe_tabs[data1.recipe_tabs_c].totalTableD = [];
      this.checkReasonableSafeMedicines([]);

      if (!request) return;

      // 赋值给表格
      data.preStiDetails.forEach((item, index) => {
        let obj1 = {
          drugList: [],
          page: 1,
          loadMore: true,
          usageList: [],
          id: item.seqn,
          pid: item.pid,
          name: item.ypmc || item.drugname,
          matname: item.platformdrugname, // 知识库id
          matid: item.platformdrugid, // 知识库name
          spec: item.gg || item.specification, // 规格
          dose: item.dose, // 剂量
          unit: item.dw || item.unit, // 单位
          usage: item.usagestr, // 用法
          // usage: "",
          // price: item.lsjg,
          price: item.price ? item.price : 0,
          total: item.price ? item.price * item.dose : 0,
          inventory: item.kc, // 库存
          key: "",
          search_i: index,
          medid: item.ypmc ? item.pid || item.matid : drugid, // 药品id
          originname: item.cdmc, // 产地名称
          showSearch: false
        };
        obj1.ggnum = +item.ggnum || 1;
        obj1.xbzxs = +item.xbzxs || '34'.includes(item.zylx) ? obj1.ggnum : 1;
        data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.push(obj1);
        data1.getSelectType("中药药品用法", index);
      });
      data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.push({
        drugList: [],
        page: 1,
        loadMore: true,
        usageList: [],
        showSearch: false,
        search_i: 0,
        key: "",
        id: 1
      });

      data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.filter(
        (item3, index3) => {
          return (item3.id = index3 + 1);
        }
      );

      data1.recipe_tabs[data1.recipe_tabs_c].tableData = data1.recipe_tabs[
        data1.recipe_tabs_c
      ].totalTableD.filter(item2 => {
        return Number(item2.id) % 2 != 0;
      });
      data1.recipe_tabs[data1.recipe_tabs_c].tableData1 = data1.recipe_tabs[
        data1.recipe_tabs_c
      ].totalTableD.filter(item2 => {
        return Number(item2.id) % 2 == 0;
      });

      this.showAgree = false;
      this.showExpr = false;
      this.showPresc = false;
      this.showUnifyPresc = false;

      data1.getPharmacyID();
      data1.changePharmacy();
    },
    // 存为协定方后打开处方
    openRecipeAfterAgree() {
      let zhongPrescriptionVo = this.zhongPrescriptionVo;
      let chengPrescriptionVo = this.chengPrescriptionVo;
      let technologyPrescriptionVo = this.technologyPrescriptionVo;
      this._getRecipePriview(
        zhongPrescriptionVo,
        chengPrescriptionVo,
        technologyPrescriptionVo
      );
    },
    // 提交中药处方
    async submitRecipe1() {
      const cancel = (id) => {
        this.saving = false;
        this.$refs.suitScience && this.$refs.suitScience.saveDone();
        if (id) this.container_i = this.contentTabs.findIndex(tab => tab.id === id);
      }

      this.saving = true;
      if (!await this.$refs.TCM.saveDiagnosisData()) return cancel();

      let zhongPrescriptionVo = [];
      let chengPrescriptionVo = {};
      let technologyPrescriptionVo = [];

      const selected = this.contentTabs[this.container_i];
      const tabs = this.contentTabs.filter(tab => tab.check && tab.id !== selected.id)
      tabs.unshift(selected);

      for (const tab of tabs) {


        const child = this.$children.find(child => child.name === tab.name);
        if (!(child.saveable || selected.id === tab.id)) continue;

        switch (tab.id) {
          case /*中药处方*/
          '0': {
            zhongPrescriptionVo = this.dealRecipe1(child);
            if (!zhongPrescriptionVo || !zhongPrescriptionVo.length) return cancel(tab.id);
            try {
              const {filter, force} = await this.getRationalSafeUse();
              if (filter) {
                const results = await Promise.all(child.recipe_tabs.map((item, index) => {
                  return checkReasonableSafeMedicinesMethod(item.totalTableD, {
                    patient: this.patiensMsg,
                    illness: this.$refs.TCM.getIllness(),
                  }).then(medicines => ReasonableSafeMedicine.analysis(medicines, {filter}));
                }));
                const sign = (index, value) => tryRun(() => {
                  zhongPrescriptionVo[index].zhongdetail.find(item => item.platformdrugid === value).sign = this.getuserinfo.username;
                });
                const tips = results.map((item, index) => {
                  for (const value of item.sign()) sign(index, value);
                  const value = item.toString();
                  return value ? `<div style="padding-top: ${index ? 12 : 0}px;border-bottom: 1px dashed #dcdcdc;"><h2 style="margin-bottom: 16px;">处方${index + 1}</h2><div class="reasonable-safe-medicines-wrapper">${value}</div></div>` : '';
                }).join('');
                if (tips) {
                  if (!force) {
                    this.$message({
                      dangerouslyUseHTMLString: true,
                      customClass: 'message-rational-safe-use-wrapper',
                      message: tips,
                      duration: 1000 * 3,
                      showClose: true,
                    })
                  } else if (await this.$confirm(tips, '温馨提示：是否保存处方?', {
                    confirmButtonText: '保存',
                    cancelButtonText: '取消',
                    dangerouslyUseHTMLString: true,
                    customClass: 'message-rational-safe-use-wrapper',
                  }).then(() => /* 继续 */ false, () => /* 取消 */ true)) return cancel(tab.id);
                }
              }
            } catch (e) {}
            break;
          }
          case /*中药制剂*/
          '1': {
            if (+child.paystate === 1) continue;
            chengPrescriptionVo = this.dealRecipe2(child);
            if (!chengPrescriptionVo || !Object.keys(chengPrescriptionVo).length) return cancel(tab.id);
            break;
          }
          case /*适宜技术*/
          '2': {
            if (+child.paystate === 1) continue;
            technologyPrescriptionVo = this.dealRecipe3(child);
            if (!technologyPrescriptionVo || !technologyPrescriptionVo.length) return cancel(tab.id);
            break;
          }
        }
      }

      console.log("【处方保存数据】中药处方:", JSON.stringify(zhongPrescriptionVo, null, 2));
      console.log("【处方保存数据】中药制剂:", JSON.stringify(chengPrescriptionVo, null, 2));
      console.log("【处方保存数据】适宜技术:", JSON.stringify(technologyPrescriptionVo, null, 2));

      await this._getRecipePriview(
          zhongPrescriptionVo,
          chengPrescriptionVo,
          technologyPrescriptionVo
      );
      return cancel();
    },

    // 修改推荐方剂轮播图下标
    changeRbanner(type) {
      if (type == "add") {
        if (this.r_current == 3) {
          this.r_current = 0;
        } else {
          this.r_current += 1;
        }

        this.$refs.r_banner.setActiveItem(this.r_current);
      } else if (type == "reduce") {
        if (this.r_current == 0) {
          this.r_current = 3;
        } else {
          this.r_current -= 1;
        }

        this.$refs.r_banner.setActiveItem(this.r_current);
      }
    },
    // 修改协定方 tab
    changeAgree(type) {
      this.agree_current = type;
      if (type == 0) {
        // this.activeNames = '0'
        this.collapseData[this.activeNames].page = 1;
        this.collapseData[this.activeNames].loadMore = true;
        this.collapseData[this.activeNames].list = [];
        this.getAgreeRecipe(this.collapseData[this.activeNames].loadMore);
      } else if (type == 1) {
        this.getPrescriptionsList();
      } else if (type == 2) {
        this.getDoctorCaseL();
      }
    },

    // 查看药品信息
    findDrug(scope) {
      console.log(scope, "药品信息");
      // this.showDrug = true
      if (scope.row.color == "red") {
        this.getMedDetail(scope.row.medid);
      } else {
        this.getDrugDetail(scope.row.medid);
      }
    },
    //  查看穴位信息
    find(scope) {
      this.getAcupointD(scope.row.acuid);
    },
    clearContainer(id) {
      try { this.contentTabs.find(tab => tab.id === id).color = ''; } catch (e) {}
      switch (id.toString()) {
        case '0': this.isTuiDaoZy = false; break;
        case '1': this.isTuiDaoZj = false; break;
        case '2': this.isTuiDaoSuit = false; break;
      }
    },
    // ========== 西医诊断搜索（分页） ==========
    async searchWesternDisease(query) {
      this.westernDiseasePage = 1;
      this.westernDiseaseHasMore = true;
      this._wdQuery = query || "";
      this.westernDiseaseLoading = true;
      try {
        const pinyin = /^[A-Za-z]+$/g;
        const serchtype = query && pinyin.test(query) ? "1" : "";
        const res = await getXDiseaseName({
          pageid: 1,
          pagesize: 200,
          keyword: query || "",
          serchtype,
        });
        if (res.code == 0) {
          const list = res.data?.wests || [];
          // 保留已选中但不在搜索结果中的选项
          const selectedCodes = Array.isArray(this.suggestDiag)
            ? this.suggestDiag
            : [];
          const resultCodes = new Set(list.map((i) => i.westcode));
          const preserved = selectedCodes
            .filter((code) => !resultCodes.has(code))
            .map((code) => ({
              westcode: code,
              westname: this.westernDiseaseNameMap[code] || code,
            }));
          this.westernDiseaseOptions = [...preserved, ...list];
          this.westernDiseaseHasMore = list.length >= 200;
          list.forEach((item) => {
            if (item.westcode && item.westname) {
              this.westernDiseaseNameMap[item.westcode] = item.westname;
            }
          });
        }
      } catch (e) {
        console.error("搜索西医诊断失败", e);
      } finally {
        this.westernDiseaseLoading = false;
      }
    },
    async loadMoreWesternDisease() {
      if (this.westernDiseaseLoading || !this.westernDiseaseHasMore) return;
      this.westernDiseasePage++;
      this.westernDiseaseLoading = true;
      try {
        const query = this._wdQuery || "";
        const pinyin = /^[A-Za-z]+$/g;
        const serchtype = query && pinyin.test(query) ? "1" : "";
        const res = await getXDiseaseName({
          pageid: this.westernDiseasePage,
          pagesize: 200,
          keyword: query,
          serchtype,
        });
        if (res.code == 0) {
          const list = res.data?.wests || [];
          this.westernDiseaseOptions = this.westernDiseaseOptions.concat(list);
          this.westernDiseaseHasMore = list.length >= 200;
          list.forEach((item) => {
            if (item.westcode && item.westname) {
              this.westernDiseaseNameMap[item.westcode] = item.westname;
            }
          });
        }
      } catch (e) {
        console.error("加载更多西医诊断失败", e);
      } finally {
        this.westernDiseaseLoading = false;
      }
    },
    onWesternDiseaseVisible(show) {
      if (!show) {
        const wrap = document.querySelector(
          ".western-disease-input-wrapper .el-scrollbar__wrap",
        );
        if (wrap && this._wdScroll) {
          wrap.removeEventListener("scroll", this._wdScroll);
        }
      }
    },
    queryWesternDisease(queryString, cb) {
      const selectedCodes = Array.isArray(this.suggestDiag) ? this.suggestDiag : [];
      const kw = (queryString || '').trim();
      const options = (Array.isArray(this.suggestDiagAll) ? this.suggestDiagAll : [])
        .filter(it => !kw || (it.westname || it.westcode || '').includes(kw))
        .map(it => ({
          ...it,
          _disabled: selectedCodes.includes(it.westcode),
        }));
      cb(options.length ? options : [{ westname: "暂无数据", _disabled: true }]);
    },
    onWesternDiseaseSelect(item) {
      if (item._disabled) {
        this.$nextTick(() => {
          this.westernDiseaseSearch = "";
        });
        return;
      }
      if (!item || !item.westcode) return;
      if (!Array.isArray(this.suggestDiag)) {
        this.suggestDiag = [];
      }
      if (!this.suggestDiag.includes(item.westcode)) {
        this.suggestDiag.push(item.westcode);
        this.westernDiseaseNameMap[item.westcode] = item.westname;
      }
      this.westernDiseaseSearch = "";
    },
    removeWesternDisease(code) {
      if (!Array.isArray(this.suggestDiag)) return;
      this.suggestDiag = this.suggestDiag.filter((c) => c !== code);
    },
    // 顶部tab 改变
    async changeContainer(item, type) {
      // 切离适宜技术tab时，缓存当前数据
      if (this.container_i === 2 && type !== 2) {
        this.$refs.suitScience && this.$refs.suitScience.cacheCurrentData();
      }

      this.container_i = type;
      item.check = true;

      // 切换到适宜技术tab时，重置标志位以允许重新获取数据
      if (type === 2) {
        this.isTuiDaoSuit = false;
      }

      await this.inferRecipe(3, item.businesstype);

      const child = this.$children.find(child => child.name === item.name);
      if (!child) return
      if (item.id === '0') {
        try { this.tjRecipeId = child.recipe_tabs[child.recipe_tabs_c].id; } catch (e) { this.tjRecipeId = "" }
      } else if (item.id === '2') {
        // 适宜技术高亮由独立变量 suitTjRecipeId 管理
      }
    },
    checked(item1) {
      this.contentTabs.forEach(item => {
        if (item.name == item1.name) {
          item.check = !item.check;
        }
      });
      let type = this.container_i;

      setTimeout(() => {
        if (type == 0) {
          let arr = this.$refs.chineseM.recipe_tabs;
          let allmoney = 0;
          arr.forEach(item => {
            allmoney += item.bottom_form.allMoney;
          });
          this.chineseM.allMoney = allmoney;
        } else if (type == 1) {
          console.log(this.$refs.medicineC.allMoney);
          this.medicineC.allMoney = this.$refs.medicineC.allMoney;
        } else if (type == 2) {
          // this.suitScience.allMoney = this.$refs.suitScience.allMoney;
          this.suitScience.allMoney = this.$refs.suitScience?.totalPrice || 0;
        }
      }, 500);
    },

    // 名家验案转方
    turnRecipe(item) {
      this.setDrugsInfo(item.verpreitemlist);
      this.setRecipeId('');
      this.changeAndJoin();
      this.addRecipeFrom("5");
    },
    // 就诊记录转方
    turnRecipe1(item) {
      // 病历转方
      this.addRecipeFrom("6");

      this.getRecipeDataByid(item.pid);
      this.showRecord = false;
      this.showAgree = false;
    },
    transposition(recipe) {
     const is = recipe.medicine.every(m => m.matid);
     if (is) {
       // 调用 方剂 换方
       const medicines = recipe.medicine.map((m, i) => {
         const medicine = {
           matid: m.matid,
           matname: m.ypmc,
           dose: m.dose,
           unit: m.dw || m.zxdw || m.bzdw,
           useage: m.usagestr,
           seqn: i + 1,
         }
         medicine.ggnum = +m.ggnum || 1;
         medicine.xbzxs = +m.xbzxs || '34'.includes(m.zylx) ? medicine.ggnum : 1;
         return medicine;
       });
       if (recipe.__RecipeFrom__ === '2') this.agreeAssignToTCM(recipe, void 0, true);
       this.setDrugsInfo(medicines);
       this.setRecipeId('');
       this.changeAndJoin(1);
     } else if (recipe.__RecipeFrom__ === '2') {
       this.agreeInfo = recipe;
       this.changeBasisPre(this.agreeInfo.pid);
     }
     if (recipe.__RecipeFrom__) this.addRecipeFrom(recipe.__RecipeFrom__ /* 2 协定方*/);
    },

    /**
     * 协定方转方
     * @deprecated
     */
    turnRecipe2() {
      this.addRecipeFrom("2");
      this.changeBasisPre(this.agreeInfo.pid);

      // this.showAgree = false
    },
    // 专家经验合方
    joinRecipe3(info) {
      let children = this.$children.filter(item => {
        return (
          item.name == "中药处方" ||
          item.name == "中药制剂" ||
          item.name == "适宜技术处方"
        );
      });

      let data1 = children[0];
      let data = info;

      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.preType = data.type;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.disable =
        data.type == "1";
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.preType = data.type;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.doseType =
        data.curetype;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.nongjian =
        data.density;
      data1.recipe_tabs[
        data1.recipe_tabs_c
      ].bottom_form.specialDeploymentPrice = data.deploymentfree;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.num = data.frequency;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.time =
        data.medicationtime;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.agencyPrice =
        data.fryingfee;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.systemOfCreamPrice =
        data.markfree;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.radio =
        data.prescriptiontype;
      data1.recipe_tabs[data1.recipe_tabs_c].bottom_form.usege = data.usrage;

      if (data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.length == 1) {
        data1.recipe_tabs[data1.recipe_tabs_c].totalTableD = [];
      } else {
        data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.pop();
      }

      if (info.isupdate == "1") {
        this.turnRecipe3(info);

        return;
      }

      // 赋值给表格
      data.preStiDetails.forEach((item, index) => {
        let obj1 = {
          drugList: [],
          page: 1,
          loadMore: true,
          usageList: [],
          id: item.seqn,
          // pid:
          name: item.ypmc || item.drugname,
          matid: item.platformdrugid || item.matid,
          matname: item.platformdrugname,
          spec: item.gg || item.specification, // 规格
          dose: item.dose, // 剂量
          unit: item.dw || item.unit, // 单位
          // usage: item.usagestr, // 用法
          usage: "",
          // usage: item.yf,
          // price: item.lsjg,
          price: item.price ? item.price : 0,
          total: item.price ? item.price * item.dose : 0,
          inventory: item.kc, // 库存
          key: "",
          search_i: index,
          medid: item.ypmc ? item.pid : drugid, // 药品id
          originname: item.cdmc, // 产地名称
          showSearch: false
        };
        obj1.ggnum = +item.ggnum || 1;
        obj1.xbzxs = +item.xbzxs || '34'.includes(item.zylx) ? obj1.ggnum : 1;
        data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.push(obj1);
        data1.getSelectType("中药药品用法", index);
      });
      data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.push({
        drugList: [],
        page: 1,
        loadMore: true,
        usageList: [],
        showSearch: false,
        search_i: 0,
        key: "",
        id: 1
      });

      data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.filter(
        (item3, index3) => {
          return (item3.id = index3 + 1);
        }
      );

      data1.recipe_tabs[data1.recipe_tabs_c].tableData = data1.recipe_tabs[
        data1.recipe_tabs_c
      ].totalTableD.filter(item2 => {
        return Number(item2.id) % 2 != 0;
      });
      data1.recipe_tabs[data1.recipe_tabs_c].tableData1 = data1.recipe_tabs[
        data1.recipe_tabs_c
      ].totalTableD.filter(item2 => {
        return Number(item2.id) % 2 == 0;
      });

      this.showAgree = false;
      this.showExpr = false;

      data1.getPharmacyID();
    },
    //专家经验转方
    turnRecipe3(info) {
      this.changeExpre(info);
    },
    // 适宜技术处方 专方 和方
    suitChnageOrJoin(type = "", info) {
      // type = '' 专访 type == 1 和方
      if (this.container_i == 1) return;

      const child = this.$children.find(child => child.name === '适宜技术处方');
      if (!child) return;

      const loading = this.$loading({
        lock: true,
        text: "正在处理数据,请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let drugs = this.getDrugInfo;
      const recipeId = +type !== 1 ? this.getRecipeId : "";
      this.setRecipeId('');
      this.tjRecipeId = recipeId

      const merge = !(info && info.operation)
      if (type == "") {
        child.bottom_form.caozuo = merge || !info ? '' : info.operation;
        // 转方
        child.tableData4 = [];
        drugs.forEach((item, index) => {
          let obj = {
            id: index + 1,
            name: item.acuname,
            acuname: item.acuname,
            acuid: item.acuid
          };
          // 锚点
          if (merge && item.acuoperation) child.bottom_form.caozuo += obj.acuname + ':' + item.acuoperation + ' ';
          child.tableData4.push(obj);
        });
        child.tableData4.push({
          id: "",
          name: "",
          acuname: "",
          acuid: ""
        });

        child.tableData4.filter((item, index) => {
          return (item.id = index + 1);
        });
      } else if (type == 1) {
        child.tableData4.pop();
        for (const item of drugs) {
          if (child.tableData4.find(({acuid}) => acuid === item.acuid)) continue;
          let obj = {
            id: child.tableData4.length + 1,
            name: item.acuname,
            acuname: item.acuname,
            acuid: item.acuid,
          };
          // 锚点
          if (merge && item.acuoperation) child.bottom_form.caozuo += obj.acuname + ':' + item.acuoperation + ' ';
          child.tableData4.push(obj);
        }
        child.tableData4.push({
          id: "",
          name: "",
          acuname: "",
          acuid: ""
        });

        child.tableData4.filter((item, index) => {
          return (item.id = index + 1);
        });
      }
      child.recipeId = recipeId
      this.showDialog = false;

      loading.close();
    },
    // 换方 按钮 直接点击
    inferChange(item, type = "", type1 = "") {
      // type == 1  type1 == 1  不掉详情接口 直接转方 和方
      this.addRecipeFrom("4", 2);
      if (type == 1 && type1 == 1) {
        this.setDrugsInfo(item.items);
        this.setRecipeId('');
        this.suitChnageOrJoin('', item);
        return;
      }
      console.log(item, "item");
      this.getPreDetal(item.preid || item.pried || item.acupreid);
    },
    // 和方按钮直接点击
    inferChange1(item, type = "", type1 = "") {
      let isupdateExpre = sessionStorage.getItem("isupdateExpre");
      if (isupdateExpre == "1") {
        this.$message("请先清空当前处方");
        return;
      }
      this.addRecipeFrom("4", 2);
      if (type == 1 && type1 == 1) {
        this.setDrugsInfo(item.items);
        this.setRecipeId('');
        this.suitChnageOrJoin(1, item);
        return;
      }

      this.getPreDetal(item.preid || item.pried || item.acupreid, 2);
    },
    //方剂合方
    joinRecipe() {
      let isupdateExpre = sessionStorage.getItem("isupdateExpre");
      if (isupdateExpre == "1") {
        this.$message("请先清空当前处方");
        return;
      }
      if (!this.preInfo.prename) {
        this.addRecipeFrom("4", 2);
        this.suitChnageOrJoin(1, this.preInfo);
        return;
      }
      this.addRecipeFrom("4");
      this.setDrugsInfo(this.preInfo.items);
      this.setRecipeId('');
      this.changeAndJoin(2);
    },
    // 方剂换方
    changeRecipe(e) {
      if (e == 1) {
        this.showDialog = false;
        // this.tjRecipeId = ''
        return;
      }
      if (!this.preInfo.prename) {
        this.addRecipeFrom("4", 2);
        // 适宜技术处方
        this.suitChnageOrJoin('', this.preInfo);
        return;
      }
      this.addRecipeFrom("4");
      this.setDrugsInfo(this.preInfo.items);
      this.changeAndJoin(1);
    },
    // 药方是否支付
    async _recipeIsPay(id, type, index) {
      let res = await recipeIsPay({
        preId: id,
        visitId: JSON.parse(sessionStorage.getItem("patiensInfo")).pid
      });
      // console.log(res, "支付状态");
      if (res.ResultCode == 0) {
        // 跟据id 回显
        let children = this.$children.filter(item => {
          return (
            item.name == "中药处方" ||
            item.name == "中药制剂" ||
            item.name == "适宜技术处方"
          );
        });

        let data1 = children[0];
        let data2 = children[1];
        let data3 = children[2];

        if (type == 1) {
          // 根据处方id 回显
          setTimeout(() => {
            if (data1.recipe_tabs[data1.recipe_tabs_c].totalTableD.length > 1) {
              data1.recipe_tabs[data1.recipe_tabs_c].isPay = res.Data;
            }

            if (data2.tableData3.length > 1) {
              data2.isPay = res.Data;
            }

            if (data3.tableData4.length > 1) {
              data3.isPay = res.Data;
            }
          }, 1000);
        }

        if (type == 2) {
          setTimeout(() => {
            // 处方回显
            if (index) {
              data1.recipe_tabs[index].isPay = res.Data;
            }

            if (data2.tableData3.length > 1) {
              data2.isPay = res.Data;
            }

            if (data3.tableData4.length > 1) {
              data3.isPay = res.Data;
            }
          }, 1000);
        }
      }
    },
    // 获取穴位信息
    async getAcupointD(id) {
      let res = await getAcupointD({
        acuid: id
      });
      if (res.code == 0) {
        this.xwinfo = res.data;
        this.showXuewei = true;
      }
    },
    // 获取病人 左侧信息
    async getPatiensBasisM() {
      let res = await getPatiensBasisM({
        patientId: this.getPatiensInfo.pid
        // patientId: '4e9db43d-25aa-4683-9564-5120deac2c56'
      });
      if (res.ResultCode == 0) {
        // res.Data.recordLength = res.Data.patientRecord.length;
        // this.agree_key = res.Data.maindiagnosis ?
        //   res.Data.maindiagnosis.namemedicine ?
        //   res.Data.maindiagnosis.namemedicine :
        //   "" :
        //   "";
        this.agree_key1 = res.Data.maindiagnosis
          ? res.Data.maindiagnosis.namemedicine
            ? res.Data.maindiagnosis.namemedicine
            : ""
          : "";
        res.Data.secondarydiagnosis = res.Data.secondarydiagnosis
          ? res.Data.secondarydiagnosis
          : [];
        this.patiensMsg = res.Data;

        this.patiensMsg.outpatientElectronicmedicalrecord.image1 = formatPicture(this.patiensMsg.outpatientElectronicmedicalrecord.image1);
        // if (!this.patiensMsg.maindiagnosis.disid) {
        //   this.$message.warning("请先提交一条诊断信息");
        //   this.$router.replace({
        //     path: "/index/diagnosis"
        //   });

        //   return;
        // }
        // if (this.patiensMsg.maindiagnosis.disid) {

        //   this.inferRecipe();
        // }
      } else return false;
    },
    async openTongueAndFaceAnalysis() {
      if (!this.tongueAndFaceAnalysis) await this.getPatientBasisTongueAndFaceAnalysis()
      if (this.tongueAndFaceAnalysis) this.showTongueAnalysis = true;
    },
    // 获取病人 舌面象数据
    async getPatientBasisTongueAndFaceAnalysis() {
      this.tongueAndFaceLoading = true;
      try {
        const get = getTongueAndFaceAnalysisRecords.bind(null, this.getPatiensInfo ? this.getPatiensInfo.pid : "")
        let result = await get(1, 3);
        this.tongueAndFaceAnalysis = result.total > 0 ? {...result, get} : null;
      } catch (e) {
        this.$message.error(e.ResultInfo);
      }
      this.tongueAndFaceLoading = false;
    },
    // 获取处方预览数据
    async _getRecipePriview(zhongyao, zhongchengyao, technology) {
      const loading = this.$loading({
        lock: true,
        text: "正在提交",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      console.log(zhongyao, zhongchengyao, technology, "处方预览数据");
      let params = {
        recordid: this.getPatiensInfo.pid,
        technologies: technology,
        zhongchengyao: zhongchengyao,
        zhongyao: zhongyao
      };
      let res = await getRecipePriview(params).catch(err => {
        loading.close();
        // 保存失败时恢复保存按钮状态
        this.$refs.suitScience && this.$refs.suitScience.saveDone();
      });
      if (res.ResultCode == 0) {
        loading.close();
        res.Data.tcmPrescriptionFormVos.forEach((item, index) => {
          // if(item.)
          item.isdelivery = zhongyao[index].isdelivery;
        });
        this.priviewData = res.Data;
        sessionStorage.setItem(
          "priviewRawData",
          JSON.stringify({
            zhongyao,
            zhongchengyao,
            technology
          })
        );
        this.showPriview = true;
      } else {
        // 保存失败时恢复保存按钮状态
        loading.close();
        this.$refs.suitScience && this.$refs.suitScience.saveDone();
      }
    },

    // 获取处方回显数据
    async getRecipeShowData() {
      const loading = this.$loading({
        lock: true,
        text: "正在加载数据",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await getRecipeShowData(this.getPatiensInfo.pid).catch(err => {
        loading.close();
      });
      console.log(res, "有处方并且获取处方回显数据");
      if (res.ResultCode == 0) {
        if (!res.Data.flag) {
          loading.close();
          if (this.getPatiensInfo.pid) {
            await this.getPatiensBasisM();
          }
          return;
        }
        this.contentTabs[0].check = res.Data.zhongyao.length > 0;
        this.contentTabs[1].check = res.Data.zhongchengyao.chengDetail !== null;
        // 适宜技术回显
        this.contentTabs[2].check = res.Data.technologies.length > 0;

        this.container_i = Math.max(this.contentTabs.findIndex(item => item.check), 0);

        this.chineseM.allMoney = res.Data.zhonyaoPrice;
        this.medicineC.allMoney = res.Data.zhonchengPrice;
        this.suitScience.allMoney = res.Data.technologyPrice;

        if (this.contentTabs[0].check) {
          this.assignRecipe1(res.Data.zhongyao, loading);
          res.Data.zhongyao.forEach((item, index) => {
            this._recipeIsPay(item.preId, 2, index);
          });
        }
        if (this.contentTabs[1].check) {
          this.assignRecipe2(res.Data.zhongchengyao, loading);
          this._recipeIsPay(res.Data.zhongchengyao.preId, 2);
        }
        if (this.contentTabs[2].check) {
          // 适宜技术支持多条处方
          this.assignRecipe3(res.Data.technologies, loading);
          res.Data.technologies.forEach((item, index) => {
            if (item && item.preId) this._recipeIsPay(item.preId, 2, index);
          });
        }
        if (this.getPatiensInfo.pid) {
          this.getPatiensBasisM();
        }
      }
    },

    // 根据id 获取处方回显数据
    async getRecipeDataByid(id) {
      let params = {
        pid: id
      };
      const loading = this.$loading({
        lock: true,
        text: "正在处理转方数据",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await getRecipeDataByid(params).catch(err => {
        loading.close();
      });
      if (res.ResultCode == 0) {
        if (res.Data.type == 0) {
          res.Data.zhongdetail = res.Data.detail;
          let arr = [];
          arr.push(res.Data);
          this.container_i = 0;
          this.contentTabs[0].check = true;
          this.contentTabs[1].check = false;
          this.contentTabs[2].check = false;
          this.assignRecipe1(arr, loading);
        } else if (res.Data.type == 1) {
          res.Data.chengDetail = res.Data.detail;
          this.container_i = 1;
          this.contentTabs[0].check = false;
          this.contentTabs[1].check = true;
          this.contentTabs[2].check = false;
          this.assignRecipe2(res.Data, loading);
        } else if (res.Data.type == 2) {
          // 适宜技术转方前校验：跳过开方页面已支付的相同项目
          const checkResult = this.checkPaidProjects(res.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          res.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          this.container_i = 2;
          this.contentTabs[0].check = false;
          this.contentTabs[1].check = false;
          this.contentTabs[2].check = true;
          // 转方数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(res.Data, loading, true);
          // 回显的是已保存处方(非推荐方案)，清空推荐高亮
          this.suitTjRecipeId = "";
        }

        await this._recipeIsPay(id, 1);
      }
    },
    // 适宜技术病历转方回显
    async suitTechRecordTurn(recordId,visitId) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理转方数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        console.log('转方就诊id', recordId, "就诊id",visitId);
        const res = await getRecipeBySuitTech({ recordId ,visitId});
        console.log('适宜技术病历转方回显', res);
        if (res.ResultCode === 0 && res.Data) {
          // 转方前校验
          const checkResult = this.checkPaidProjects(res.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          res.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          this.container_i = 2;
          this.contentTabs[0].check = false;
          this.contentTabs[1].check = false;
          this.contentTabs[2].check = true;
          // 转方是主动换方案
          if (this.$refs.suitScience) {
            this.$refs.suitScience._cachedPrescriptions = null;
            this.$refs.suitScience._cachedPrescriptionDataMap = null;
          }
          // 转方数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(res.Data, loading, true);
          // 病历转方回显(非推荐方案)，清空推荐高亮
          this.suitTjRecipeId = "";
        } else {
          loading.close();
        }
      } catch (e) {
        loading.close();
        console.error('适宜技术病历转方失败', e);
      }
    },
    // 处方管理 适宜技术转方
    async suitTechRecipeTurn(preId) {
      const loading = this.$loading({
        lock: true,
        text: '正在处理转方数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      console.log('适宜技术处方转方入参', preId); 
      try {
        const res = await getRecipeBySuitTech({ preId });
        console.log('适宜技术处方转方回显', res);
        if (res.ResultCode === 0 && res.Data) {
          console.log('获取数据', res.Data);
          // 转方前校验：跳过开方页面已支付的相同项目
          const checkResult = this.checkPaidProjects(res.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          res.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          this.container_i = 2;
          this.contentTabs[0].check = false;
          this.contentTabs[1].check = false;
          this.contentTabs[2].check = true;
          // 转方是主动换方案
          if (this.$refs.suitScience) {
            this.$refs.suitScience._cachedPrescriptions = null;
            this.$refs.suitScience._cachedPrescriptionDataMap = null;
          }
          // 转方数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(res.Data, loading, true);
          // 病历转方回显(非推荐方案)，清空推荐高亮
          this.suitTjRecipeId = "";
        } else {
          loading.close();
        }
      } catch (e) {
        loading.close();
        console.error('适宜技术处方转方失败', e);
      }
    },
    //获取右侧协定方列表
    async getAgreeRecipe(load = true) {
      if (!load) return;
      let params = {
        type: this.activeNames,

        pageId: this.collapseData[this.activeNames].page,
        pageSize: 10
      };
      let res = await getAgreeRecipe(params);
      if (res.ResultCode == 0) {
        if (
          this.collapseData[this.activeNames].list.length <=
          res.Data.TotalRecordCount
        ) {
          this.collapseData[this.activeNames].list = [
            ...this.collapseData[this.activeNames].list,
            ...res.Data.Items
          ];

          if (
            this.collapseData[this.activeNames].list.length >=
            res.Data.TotalRecordCount
          ) {
            this.collapseData[this.activeNames].loadMore = false;
          } else {
            this.collapseData[this.activeNames].page += 1;
          }
        } else {
          this.collapseData[this.activeNames].loadMore = false;
        }
      }
    },
    // 获取方剂列表
    async getPrescriptionsList(load = true) {
      if (!load) return;
      let params = {
        pageid: this.rPrescription.page,
        pagesize: 5,
        searchtype: "",
        keyword: this.agree_key
      };
      let res = await getPrescriptionsList(params);
      if (res.code == 0) {
        if (this.rPrescription.page <= res.data.TotalPageCount) {
          this.rPrescription.list = [
            ...this.rPrescription.list,
            ...res.data.pres
          ];

          if (this.rPrescription.page == res.data.TotalPageCount) {
            this.rPrescription.loadMore = false;
          } else {
            this.rPrescription.page += 1;
          }
        } else {
          this.rPrescription.loadMore = false;
        }
      }
    },
    // 获取参考医案
    async getDoctorCaseL(load = true) {
      if (!load) return;
      let params = {
        pageid: this.rDoctorCase.page,
        pagesize: 5,
        searchtype: "",
        keyword: this.agree_key1
      };
      let res = await getDoctorCaseL(params);
      if (res.code == 0) {
        if (this.rDoctorCase.page <= res.data.TotalPageCount) {
          res.data.verifys.filter(item => {
            return (item.content = item.disname + " " + item.attendingexpert);
          });
          this.rDoctorCase.list = [
            ...this.rDoctorCase.list,
            ...res.data.verifys
          ];

          if (this.rDoctorCase.page == res.data.TotalPageCount) {
            this.rDoctorCase.loadMore = false;
          } else {
            this.rDoctorCase.page += 1;
          }
        } else {
          this.rPrescriprDoctorCasetion = { ...this.rPrescriprDoctorCasetion, loadMore: false, };
        }
      }
    },
    /**
     * 检测合理安全用药
     * 可供 子组件 调用 {@link ChineseMedicine }
     * @param medicines 药品
     * @return {Promise<*>}
     */
    async checkReasonableSafeMedicines(medicines) {
      this.reasonableSafeMedicinesLoading = true;
      medicines = await checkReasonableSafeMedicinesMethod(medicines, {
        patient: this.patiensMsg,
        illness: this.$refs.TCM.getIllness(),
      });
      return await this.updateReasonableSafeMedicines(medicines);
    },
    /**
     * 更新合理安全用药
     * 可供 子组件 调用 {@link ChineseMedicine }
     * @param medicines 药品
     * @return {Promise<>}
     */
    async updateReasonableSafeMedicines(medicines) {
      const data = reasonableSafeMedicine.analysis(medicines);
      this.reasonableSafeMedicinesHTML = data.toString();
      this.reasonableSafeMedicinesLoading = false;
      return data;
    },
    // 推导处方
    async inferRecipe(type = 1, businesstype, res) {
      if (!this.patiensMsg.maindiagnosis || !this.patiensMsg.maindiagnosis.disid) {
        if (!this.getPatiensInfo.pid || (await this.getPatiensBasisM().catch(e => false)) === false) return;
      }
      // if (this.container_i == 1) return;
      if (type != 4) {
        // if (!this.patiensMsg.maindiagnosis.disid) {
        //   this.$message.warning('请先提交一条诊断信息');
        //   this.$router.replace({
        //     path: '/index/diagnosis'
        //   })
        //   return;
        // }
      }

      if (type != 4 && businesstype == null) {
        businesstype =
          this.container_i == 0 ? "1" : this.container_i == 2 ? "7" : "1"; // 适宜技术由 '3' 改为 '7'
      }

      let params = {
        businesstype: businesstype,
        disCode: this.patiensMsg.maindiagnosis.disCode,
        symptomCode: this.patiensMsg.maindiagnosis.symptomCode,
        therapyCode: this.patiensMsg.maindiagnosis.therapyCode,
        disid: this.patiensMsg.maindiagnosis.disid,
        symid: this.patiensMsg.maindiagnosis.symptomid,
        therapy: this.patiensMsg.maindiagnosis.treatment
      };
      let loading = { close() {} };
      if (!res) {
        loading = this.$loading({
          lock: true,
          text: `正在获取推荐${ +businesstype === 2 ? '制剂' : '方剂' }数据`,
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        res = await inferRecipe(params).catch(err => { loading.close(); });
      }
      if (res.code == 0) {
        loading.close();

        let arr = [];
        res.data.expList.forEach(item => {
          item.showType = 1; // 专家经验
          item.book = item.book ? item.book : "(暂无)";
        });

        res.data.schemes[0].pres.forEach(item => {
          item.showType = 0; // 之前的推导出
          item.book = item.book ? item.book : "(暂无)";
        });
        // this.inferRecipeId = res.data.schemes[0].preid
        let arr2 = res.data.expList.concat(res.data.schemes[0].pres);
        if (type == 4) {
          try { this.contentTabs.find(tab => tab.businesstype === businesstype).color = arr2.length > 0 ? "red" : ""; } catch (e) {}
          return;
        } else if (+type === 1) {
          for (const tab of this.contentTabs) { if (!tab.hide) tab.color = "" }
        }
        if (arr2.length > 0) {
          this.tjRecipeId = arr2[0].preid || arr2[0].pid || arr2[0].acupreid;
        } else {
          let children = this.$children.filter(item => {
            return (
              item.name == "中药处方" ||
              item.name == "中药制剂" ||
              item.name == "适宜技术处方"
            );
          });
          let child = children[0];
          if (
            !child.recipe_tabs[child.recipe_tabs_c].isPay ||
            child.recipe_tabs[child.recipe_tabs_c].paystate == 0
          ) {
            // child.clearRecipe();
          }
        }
        this.rRecomendR = arr2;
        // 适宜技术：用独立高亮变量 suitTjRecipeId
        if (this.container_i == 2 && type !== 3) {
          const presList = (res.data.schemes && res.data.schemes[0] && res.data.schemes[0].pres) || [];
          if (presList.length > 0) {
            this.suitTjRecipeId = presList[0].preid || presList[0].pid || presList[0].acupreid;
          }
        }

        if (this.$route.query.type != "tuidao" && type == 1) return;
        if (type === 3) {
          try { if (this.contentTabs[this.container_i].id === '0' && this.isTuiDaoZy) return; } catch (e) {}
          try { if (this.contentTabs[this.container_i].id === '1' && this.isTuiDaoZj) return; } catch (e) {}
          try { if (this.contentTabs[this.container_i].id === '2' && this.isTuiDaoSuit) return; } catch (e) {}
        }
        if (this.rRecomendR.length == 0) return;

        let children = this.$children.filter(item => {
          return (
            item.name == "中药处方" ||
            item.name == "中药制剂" ||
            item.name == "适宜技术处方"
          );
        });
        let child = children[0];
        let child2 = children[2];

        if (
          child.recipe_tabs[child.recipe_tabs_c].isPay ||
          child.recipe_tabs[child.recipe_tabs_c].paystate == 1
        ) {
          // 已付费
          child.addRecipeTba();
        }
        if (child2.isPay || child2.paystate == 1) {
          // 已付费
          this.$message.error("当前为已付费处方,暂不支持推导");

          return;
        }

        setTimeout(async() => {
          if (
            // this.$route.query.infer &&
            // this.$route.query.infer == "true" &&
            // && child.recipe_tabs[child.recipe_tabs_c].totalTableD.length == 1
            this.container_i == 0
          ) {
            this.addRecipeFrom("4");

            if (arr2[0].showType == 1) {
              // 专家经验
              this.turnRecipe3(arr2[0]);
            } else {
              // 推导处方
              this.getPreDetal(arr2[0].preid);
            }

            if (type == 3) {
              this.isTuiDaoZy = true;
            }
          } else if (this.container_i == 2) {
            if (type !== 3) {
              // 适宜技术推导填入第一个方案
              this.fillSuitTechOnInfer(res);
              this.addRecipeFrom("4", 2);
            }
            if (type == 3) {
              this.isTuiDaoSuit = true;
            }
          } else if (this.container_i == 1) {
            if (arr2.length) {
              const info = arr2[0];
              let drugs = Array.isArray(info) ? info : info && typeof info === 'object' ? [info] : [];
              this.setDrugsInfo(drugs.map(item=> {
                return {
                  medid: item.drugid,
                  name: item.drugname,
                }
              }));
              this.setRecipeId('');
              this.changeAndJoinZJ();

              if (type == 3)  this.isTuiDaoZj = true;
            }

          }
        }, 500);
      }
    },
    async openSuitDetail(pid, mode = "agreement") {
      if (!pid) return;
      this.suitDetailPid = pid;
      // 医派协定方(unify)：标题「医派协定方」、底部展示医派+科室；否则默认「我的协定方」+分享医生
      this.suitDetailMode = mode;
      this.suitDetailTitle = mode === "unify" ? "医派协定方" : "我的协定方";
      this.suitDetailLoading = true;
      this.suitDetailShow = true;
      try {
        const res = await getSuitableTechInfo(pid);
        if (res.ResultCode === 0) {
          this.suitDetailData = res.Data || {};
        }
      } catch (e) {
        console.error("获取协定方详情失败", e);
      } finally {
        this.suitDetailLoading = false;
      }
    },
    onSuitDetailTurn() {
      if (!this.suitDetailPid) return;
      this.suitDetailShow = false;
      this.onSuitTechTurn(this.suitDetailPid, this.suitDetailData);
    },
    fillSuitTechDiagnosis(detail) {
      if (!detail) return;
      if (this.$refs.TCM && (detail.disName || detail.synName || detail.theName)) {
        this.$refs.TCM.setParams({
          namemedicine: detail.disName || '',
          disid: detail.disId || '',
          disCode: detail.disCode || '',
          symptomid: detail.synId || detail.synCode || '',
          syndrometypes: detail.synName || '',
          treatment: detail.theName || '',
          therapyCode: detail.theCode || ''
        });
      }
      if (detail.westernCode) {
        const wdCodes = String(detail.westernCode).split(',').map(s => s.trim()).filter(Boolean);
        const wdNames = detail.westernDiag ? String(detail.westernDiag).split(',').map(s => s.trim()) : [];
        wdCodes.forEach((code, i) => {
          if (code && wdNames[i]) this.westernDiseaseNameMap[code] = wdNames[i];
        });
        // 默认只取第一个，其余让用户在下拉里自选
        this.suggestDiag = wdCodes.length ? [wdCodes[0]] : [];
        this.suggestDiagAll = wdCodes.map((code, i) => ({ westcode: code, westname: wdNames[i] || this.westernDiseaseNameMap[code] || code }));
      }
    },
    // 适宜技术 · 协定方转方（详情弹窗转方）
    async onSuitTechTurn(pid, detail) {
      const loading = this.$loading({
        lock: true,
        text: '正在转方',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const res = await getRecipeByBasis({
          sourcePid: pid,
          recordId: this.getPatiensInfo.pid || undefined,
          sourceType: 'accord',
        });
        if (res.ResultCode === 0 && res.Data) {
          // 转方前校验：跳过开方页面已支付的相同项目
          const checkResult = this.checkPaidProjects(res.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          res.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          // 协定方转方：回填病名/证型/治法 + 建议诊断
          this.fillSuitTechDiagnosis(detail);
          // 转方是主动换方案
          if (this.$refs.suitScience) {
            this.$refs.suitScience._cachedPrescriptions = null;
            this.$refs.suitScience._cachedPrescriptionDataMap = null;
          }
          // 转方数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(res.Data, loading, true);
          // 协定方转方：内容来自协定方(非推荐方案)，清空推荐高亮，避免误高亮之前的推荐
          this.suitTjRecipeId = "";
          // 转方成功，关闭协定方/医派协定方查询弹窗
          this.showSuitPresc = false;
          this.showSuitUnifyPresc = false;
        } else {
          loading.close();
        }
      } catch (e) {
        loading.close();
        console.error('适宜技术协定方转方失败', e);
      }
      this.addRecipeFrom("2");
    },
    // 适宜技术  推荐方案
    async onSuitRecommendSelect(item, detail) {
      const sourcePid = item.pid || item.preid || item.acupreid;
      if (!sourcePid) return;
      // if (this.$refs.suitScience && (this.$refs.suitScience.isPay || this.$refs.suitScience.paystate == 1)) {
      //   this.$message.error('当前为已付费处方,暂不支持推导');
      //   return;
      // }
      const loading = this.$loading({
        lock: true,
        text: '正在获取适宜技术处方数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const recipeRes = await getRecipeByBasis({
          sourcePid,
          recordId: this.getPatiensInfo.pid || undefined,
          sourceType: 'localExpert',
        });
        if (recipeRes.ResultCode === 0 && recipeRes.Data) {
          // 转方前校验：跳过开方页面已支付的相同项目
          const checkResult = this.checkPaidProjects(recipeRes.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          recipeRes.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          // 推荐方案换入是主动换方案
          if (this.$refs.suitScience) {
            this.$refs.suitScience._cachedPrescriptions = null;
            this.$refs.suitScience._cachedPrescriptionDataMap = null;
          }
          // 转方数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(recipeRes.Data, loading, true);
          this.suitTjRecipeId = sourcePid;
          // 回填病名/证型/治法 + 建议诊断
          this.fillSuitTechDiagnosis(detail);
        } else {
          loading.close();
        }
      } catch (e) {
        loading.close();
        console.error('适宜技术推荐载入失败', e);
      }
      this.addRecipeFrom("4", 2);
    },
    // 适宜技术 · 推导后自动填入第一个推荐方案内容（不管当前在哪个 tab）
    async fillSuitTechOnInfer(res) {
      if (!res || res.code !== 0 || !res.data) return;
      const presList = (res.data.schemes && res.data.schemes[0] && res.data.schemes[0].pres) || [];
      if (presList.length === 0) return; // 没有推荐方案则不填入
      // 默认高亮第一个推荐方案
      this.suitTjRecipeId = presList[0].pid;
      const acupointTable = this.$refs.suitScience;
      if (!acupointTable) return;
      if (acupointTable.isPay || acupointTable.paystate == 1) {
        this.$message.error('当前为已付费处方,暂不支持推导');
        return;
      }
      const loading = this.$loading({
        lock: true,
        text: '正在获取适宜技术处方数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const recipeRes = await getRecipeByBasis({
          sourcePid: presList[0].pid,
          recordId: this.getPatiensInfo.pid || undefined,
          sourceType: 'localExpert',
        });
        if (recipeRes.ResultCode === 0 && recipeRes.Data) {
          // 推导前校验：跳过开方页面已支付的相同项目
          const checkResult = this.checkPaidProjects(recipeRes.Data, 'treatItemName');
          if (checkResult.skippedPaid.length > 0) {
            this.$message.warning(`${checkResult.skippedPaid.join('、')}项目已支付，不可转方`);
          }
          if (!checkResult.valid) {
            loading.close();
            return;
          }
          recipeRes.Data = checkResult.filteredData.length === 1 ? checkResult.filteredData[0] : checkResult.filteredData;

          // 推导时设置建议诊断
          const techData = Array.isArray(recipeRes.Data) ? recipeRes.Data[0] : recipeRes.Data;
          if (techData) {
            const rawSuggest = techData.suggestDiag;
            const rawArr = typeof rawSuggest === 'string'
              ? rawSuggest.split(',').filter(Boolean)
              : Array.isArray(rawSuggest) ? rawSuggest : [];
            this.suggestDiagAll = rawArr.map(it => {
              if (it && typeof it === 'object') {
                const code = it.westcode || it.code;
                return { westcode: code, westname: it.westname || it.name || code };
              }
              return { westcode: it, westname: this.westernDiseaseNameMap[it] || it };
            });
            this.suggestDiagAll.forEach(it => {
              if (it.westcode) this.westernDiseaseNameMap[it.westcode] = it.westname;
            });
            this.suggestDiag = this.suggestDiagAll.length ? [this.suggestDiagAll[0].westcode] : [];
          }

          // 推导是主动换方案：清掉切tab产生的缓存，避免 assignRecipe3 开头 restoreCachedData 用旧数据拦截
          acupointTable._cachedPrescriptions = null;
          acupointTable._cachedPrescriptionDataMap = null;
          // 推导数据追加到当前处方后面（不覆盖）
          this.assignRecipe3(recipeRes.Data, loading, true);
        } else {
          loading.close();
        }
      } catch (e) {
        loading.close();
        console.error('适宜技术推导填入失败', e);
      }
    },
    onSuitActiveProjectChange(prescription) {
      if (!prescription) {
        this.suitActiveSafety = [];
        return;
      }
      const b = prescription.basisStitutionsnondrug || {};
      const pick = (key) => b[key] || "";
      this.suitActiveSafety = [
        {
          itemName: prescription.itemName || "",
          connotation: pick("connotation"),
          excludedContent: pick("excludedContent"),
          limitPayScope: pick("limitPayScope"),
          remark: pick("remark"),
        },
      ];
    },

    // 新增处方来源
    async addRecipeFrom(type, isSuit = "") {
      if (type != 3) {
        let children = this.$children.filter(item => {
          return (
            item.name == "中药处方" ||
            item.name == "中药制剂" ||
            item.name == "适宜技术处方"
          );
        });
        let child = children[0];
        let child2 = children[2];
        // debugger;
        child.recipe_tabs[child.recipe_tabs_c].isMyMade = false;
        if (isSuit == 2) {
          child2.isMyMade = false;
        }
      }
      let res = await addRecipeFrom({
        type: type
      });
    },
    // 获取参考医案详情
    async getDCaseDetail(id) {
      let res = await getDCaseDetail({
        verId: id
      });
      if (res.code == 0) {
        this.showTestCase = true;
        res.data.dialist.forEach(item => {
          item.checktime = item.checktime.split(" ");
          item.diatimes = numberToUpperCase(item.diatimes - 1);
        });
        this.testCaseInfo = res.data;
      }
    },
    // 协定方转方 判断
    async changeBasisPre(id) {
      let params = {
        basisPreId: id
      };
      let res = await changeBasisPre(params);
      if (res.ResultCode == 0) {
        this.agreeAssignToTCM(this.agreeInfo);
      }
    },
    // 专家经验转方判断
    async changeExpre(info) {
      let params = {
        basisPreId: info.pid
      };
      let res = await changeExpre(params);
      if (res.ResultCode == 0) {
        // info.preStiDetails = info.prescriptionDetailVos
        this.agreeAssignToTCM(info);
      }
    },
    // 名家验案和 方剂转方/合方
    async changeAndJoin(type = 1) {
      // type == 1 转方  type ==2 合方
      let children = this.$children.filter(item => {
        return (
          item.name == "中药处方" ||
          item.name == "中药制剂" ||
          item.name == "适宜技术处方"
        );
      });
      let child = children[0];
      child.recipe_tabs[child.recipe_tabs_c].disable = false;
      let drugs = this.getDrugInfo;
      const recipeId = +type === 1 ? this.getRecipeId : "";
      this.setRecipeId('');
      this.tjRecipeId = recipeId;

      // let type1 = 0
      let type1 = child.recipe_tabs[child.recipe_tabs_c].radio.split("@")[1];

      let ids = [];
      drugs.forEach(item => {
        item.oldDose = CC_Dosage2Basis(item);
        let idDose = item.matid + "&" + item.oldDose + "&" + (item.useage || "");
        ids.push(idDose);
      });

      if (this.container_i == 1) return;
      const loading = this.$loading({
        lock: true,
        text: "正在处理药品数据,请稍等",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let res = await changeAndJoin({
        pharmacyid: child.recipe_tabs[child.recipe_tabs_c].pharmacyID,
        type: type1, // child.recipe_tabs[child.recipe_tabs_c].radio,
        drugIds: ids
      }).catch(err => {
        loading.close();
      });
      if (this.container_i == 0) {
        // 中药处方
        if (res.ResultCode == 0) {
          const getUsage = (function (list = [], value = '') {
            if (!Array.isArray(list) || list.length === 0) return void 0;
            const option = value && list.find(item => item.value === value || item.key == value);
            return option ? option.key : list[0].key;
          }).bind(null, child.usageList);

          let noDrugs = []; // 查找不到的药品
          let hasDrugs = []; // 查找的到的药品
          res.Data.forEach((item, index) => {
            drugs.forEach((item1, index1) => {
              if (item == item1.matid) {
                // debugger
                item1.color = "red";
                let obj = {
                  drugList: [],
                  page: 1,
                  loadMore: true,
                  usageList: [],
                  seqn: item1.seqn,
                  ypmc: item1.matname,
                  gg: "",
                  dw: item1.unit,
                  lsjg: item1.price ? item1.price : 0,
                  price: item1.price ? item1.price : 0,
                  kc: 0,
                  cdmc: "无",
                  pid: item1.matid,
                  matname: item1.platformdrugname, // 知识库id
                  matid: item1.platformdrugid || item1.matid, // 知识库name
                  color: "red",
                  dose: item1.dose,
                  usage: item1.useage || item1.usagestr, // child.usegeList[0].key,
                  showSearch: false,

                  key: "",
                  search_i: index
                };
                obj.oldDose = item1.oldDose;
                /* 修正 */ obj.usage = obj.useage = getUsage(obj.usage);
                noDrugs.push(obj);
                // noDrugs.push(item1.matname)
              }

              if (item instanceof Object && item.oldYpid == item1.matid) {
                item.oldDose = item.placeholderdose || item1.oldDose;
                item.ggnum = +item.ggnum || 1;
                item.xbzxs = +item.xbzxs || '34'.includes(item.zylx) ? item.ggnum : 1;
                if (item.kc > 0) hasDrugs.push(item);
                else {
                  item.color = 'red';
                  noDrugs.push(item);
                }
              }
            });
          });
          hasDrugs = hasDrugs.concat(noDrugs);
          if (hasDrugs.length > 0 && type == 1) {
            child.recipe_tabs[child.recipe_tabs_c].totalTableD = [];
            // console.log(hasDrugs, 'has');
            // 赋值给表格
            hasDrugs.forEach((item, index) => {
              let obj1 = {
                drugList: [],
                page: 1,
                loadMore: true,
                usageList: [],
                id: item.seqn,
                pid: item.pid,
                name: item.ypmc,
                matname: item.platformdrugname, // 知识库id
                matid: item.platformdrugid || item.matid, // 知识库name
                spec: item.gg, // 规格
                dose: item.dose, // 剂量
                unit: item.dw, // 单位
                // usage: item.usagestr, // 用法
                usage: item.useage || item.usagestr, // child.usegeList[0].key,
                // price: item.lsjg,
                price: item.price ? item.price : 0,
                total: item.price * item.dose,
                inventory: item.kc, // 库存
                key: "",
                search_i: index,
                medid: item.pid, // 药品id
                originname: item.cdmc, // 产地名称
                showSearch: false,
                color: item.color ? item.color : "#000"
              };
              /* 修正 */ obj1.usage = obj1.useage = getUsage(obj1.usage);
              obj1.oldDose = +item.oldDose || '';
              obj1.ggnum = +item.ggnum || 1;
              obj1.xbzxs = +item.xbzxs || '34'.includes(item.zylx) ? obj1.ggnum : 1;

              child.recipe_tabs[child.recipe_tabs_c].totalTableD.push(obj1);
              child.getSelectType("中药药品用法", index);
            });
            child.recipe_tabs[child.recipe_tabs_c].totalTableD.push({
              drugList: [],
              page: 1,
              loadMore: true,
              usageList: [],
              showSearch: false,
              search_i: 0,
              id: 1,
              key: ""
            });

            child.recipe_tabs[child.recipe_tabs_c].totalTableD.filter(
              (item3, index3) => {
                return (item3.id = index3 + 1);
              }
            );

            child.recipe_tabs[
              child.recipe_tabs_c
            ].tableData = child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD.filter(item2 => {
              return Number(item2.id) % 2 != 0;
            });
            child.recipe_tabs[
              child.recipe_tabs_c
            ].tableData1 = child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD.filter(item2 => {
              return Number(item2.id) % 2 == 0;
            });
          } else if (hasDrugs.length > 0 && type == 2) {
            child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD = child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD.filter(item => {
              return item.name;
            });
            // console.log(hasDrugs, "has");
            // 赋值给表格
            hasDrugs.forEach((item, index) => {
              let obj1 = {
                color: item.color ? item.color : "#000",
                drugList: [],
                page: 1,
                loadMore: true,
                usageList: [],
                id: item.seqn,
                pid: item.pid,
                name: item.ypmc,
                matname: item.platformdrugname, // 知识库id
                matid: item.platformdrugid || item.matid, // 知识库name
                spec: item.gg, // 规格
                dose: item.dose, // 剂量
                unit: item.dw, // 单位
                // usage: item.usagestr, // 用法
                usage: item.useage || item.usagestr, // child.usegeList[0].key,
                // price: item.lsjg,
                price: item.price ? item.price : 0,
                total: item.price * item.dose,
                inventory: item.kc, // 库存
                key: "",
                search_i: index,
                medid: item.pid, // 药品id
                originname: item.cdmc, // 产地名称
                showSearch: false
              };
              /* 修正 */ obj1.usage = obj1.useage = getUsage(obj1.usage);
              obj1.oldDose = +item.oldDose || '';
              obj1.ggnum = +item.ggnum || 1;
              obj1.xbzxs = +item.xbzxs || '34'.includes(item.zylx) ? obj1.ggnum : 1;

              child.recipe_tabs[child.recipe_tabs_c].totalTableD.push(obj1);
              child.getSelectType("中药药品用法", index);
            });
            child.recipe_tabs[child.recipe_tabs_c].totalTableD.push({
              drugList: [],
              page: 1,
              loadMore: true,
              usageList: [],
              showSearch: false,
              search_i: 0,
              id: 1,
              key: ""
            });
            child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD = this.removeRepeat(
              child.recipe_tabs[child.recipe_tabs_c].totalTableD,
              "medid"
            );
            child.recipe_tabs[child.recipe_tabs_c].totalTableD.filter(
              (item3, index3) => {
                return (item3.id = index3 + 1);
              }
            );

            child.recipe_tabs[
              child.recipe_tabs_c
            ].tableData = child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD.filter(item2 => {
              return Number(item2.id) % 2 != 0;
            });
            child.recipe_tabs[
              child.recipe_tabs_c
            ].tableData1 = child.recipe_tabs[
              child.recipe_tabs_c
            ].totalTableD.filter(item2 => {
              return Number(item2.id) % 2 == 0;
            });
          }

          this.showTestCase = false;
          this.showDialog = false;
          this.showPresc = false;
          this.showUnifyPresc = false;
          loading.close();
          this.checkReasonableSafeMedicines(child.recipe_tabs[child.recipe_tabs_c].totalTableD);
          try { child.recipe_tabs[child.recipe_tabs_c].id = recipeId; } catch (e) {}
        }
      } else if (this.container_i == 2) {
        // 适宜技术处方
      }
    },
    async changeAndJoinZJ(type = 1) {
      const child = this.$children.find(item => item.name === '中药制剂');
      const drugs = this.getDrugInfo;
      const recipeId = +type === 1 ? this.getRecipeId : '';
      this.setRecipeId('');
      this.tjRecipeId = recipeId;
      const [pharmacyID, val] = child.recipe.radio.split('@');
      const drugIds = drugs.filter(item => item.name).map(item => `${item.medid}&${item.doce || ''}&${item.usage || ''}`);
      const loading = this.$loading({
        lock: true,
        text: '正在处理药品数据,请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const data = await changeAndJoin({ pharmacyid: pharmacyID, type: val, drugIds }).then(res => {
          if (+res.ResultCode === 0) return res.Data
          else throw res
        });
        const medicines = data.map(item => {
          if (typeof item === 'string') {
            const item1 = drugs.find(item1 => item1.medid === item);
            return item1 ? { ...item1, color: 'red' } : void 0;
          } else if (item && typeof item === 'object') {
            const obj = {
              color: item.kc == 0 ? "red" : "#000",
              name: item.ypmc,
              spec: item.gg, // 规格
              timesQuan: item.timesQuan || item.ycjl || "", // 次用量
              timesUnit: item.timesUnit || item.ycjldw || "", // 次用量单位
              dose: item.dose, // 剂量 数量
              doseUnit: item.doseUnit || item.jldw || '', // 数量单位
              unit: item.dw, // 单位
              // unit: item.bzdw, // 单位
              // usage: item.usagestr, // 用法
              usage: item.usage || "",
              // price: item.lsjg,
              price: item.price,
              total: 0,
              inventory: item.kc, // 库存
              key: "",
              search_i: 0,
              medid: item.pid, // 药品id
              showSearch: false,
              originname: item.cdmc // 产地名称
            };
            return obj;
          }
        }).filter(Boolean);
        if (type === 1) {
          medicines.push({
            search_i: 0,
            key: "",
            page: 1,
            drugList: [],
            usageList: [],
            numList: [],
            timeList: [],
            loadMore: true
          });
          child.tableData3 = medicines;
        }
      } catch (e) {
        console.log(e);
      }
      loading.close();
    },
    // 跟据就诊记录id 获取就诊记录详细信息
    async getSeeDByID(id) {
      let params = {
        recId: id
      };
      const loading = this.$loading({
        lock: true,
        text: "正在查找数据",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let res = await getSeeDByID(params).catch(err => {
        loading.close();
      });
      if (res.ResultCode == 0) {
        loading.close();
        this.recordInfo = res.Data;
        this.showRecord = true;
      }
    },
    // 获取中药详情
    async getMedDetail(id) {
      let res = await getMedDetail({
        matid: id
      });
      if (res.code == 0) {
        res.data.matphoto = res.data.matphoto.split(",");
        // res.data.matphoto = res.data.matphoto.split(',')
        res.data.xiangsi = res.data.relativedata.filter(item => {
          return item.relativetype == 1;
        });
        res.data.changyong = res.data.relativedata.filter(item => {
          return item.relativetype == 2;
        });
        this.drugInfo = res.data;
        this.showDrug = true;
      }
    },
    // 获取药品详细信息并展示
    async getDrugDetail(id) {
      let res = await getDrugDetail({
        stiDrugId: id
      });
      if (res.ResultCode == 0) {
        res.Data.matphoto = res.Data.matphoto.split(",");
        // res.data.matphoto = res.data.matphoto.split(',')
        res.Data.xiangsi = res.Data.relativedata.filter(item => {
          return item.relativetype == 1;
        });
        res.Data.changyong = res.Data.relativedata.filter(item => {
          return item.relativetype == 2;
        });
        this.drugInfo = res.Data;
        this.showDrug = true;
      }
    },
    // 获取方剂详情
    async getPreDetal(id, type = "") {
      if (id instanceof Object) {
        // 适宜技术处方
        this.preInfo = id;
        this.setDrugsInfo(id.items);
        this.setRecipeId(id.acupreid);
        this.showDialog = true;
        return;
      }

      let res = await getPreDetal({
        preid: id
      });

      if (res.code === 0) {
        this.preInfo = res.data;
        /*if (type == 1 || type == "") {
          this.tjRecipeId = id;
        }*/
        this.setDrugsInfo(res.data.items);
        this.setRecipeId(id);
        if (!type || type == 2) {
          // console.log(res.data, 'RES.datas');
          if (type == "") {
            this.changeAndJoin(1);
          } else {
            this.changeAndJoin(2);
          }
        } else {
          this.showDialog = true;
        }
      }
    },
    // 获取协定方详细信息
    async getAccordDetail(id) {
      // console.log('[协定方详情] id:', id);
      addRecipeFrom({ type: 2 }).catch();
      let res = await getAccordDetail({
        pid: id
      });
      // console.log('[协定方详情] 接口返回:', res);
      if (res.ResultCode == 0) {
        this.agreeInfo = res.Data;
        // console.log('[协定方详情] agreeInfo:', this.agreeInfo);
        this.showAgree = true;
      }
    },
    // 获取专家经验详细信息
    async getExperinceDetail(id) {
      let res = await getExperinceDetail({
        pid: id
      });

      if (res.ResultCode == 0) {
        this.tjRecipeId = id;
        this.exprInfo = res.Data;
        this.showExpr = true;
      }
    },
    // 去重
    removeRepeat(arr, key) {
      let obj = {};
      arr = arr.reduce((pre, next) => {
        obj[next[key]] ? "" : (obj[next[key]] = true && pre.push(next));
        return pre;
      }, []);
      return arr;
    },
    countDose() {
      let show = false;
      this.rationalMed10.forEach(item => {
        if (item.showDose) {
          show = true;
        }
      });
      this.$forceUpdate();
      this.raDoseShow = show;
    },
    getEditPreNo() {
      return this.$route.query && this.$route.query.recipeType === "edit" ? this.$route.query.recipeID : this.getPreNo;
    },
    ...mapMutations({
      setRecipeId: "drug/setRecipeId",
      setDrugsInfo: "drug/setDrugsInfo"
    })
  },
  computed: {
    // 显示协定方按钮
    showPrec() {
      try { return this.contentTabs[this.container_i].id === '0' } catch (e) { return true }
    },
    // 三种药房合计金额
    totalPrice() {
      return (this.contentTabs[0].check
        ? Number(this.chineseM.allMoney)
        : 0 + this.contentTabs[1].check
        ? Number(this.medicineC.allMoney)
        : 0 + this.contentTabs[2].check
        ? Number(this.suitScience.allMoney)
        : 0
      ).toFixed(2);
    },
    ...mapGetters(["getPatiensInfo", "getuserinfo", "getDrugInfo", "getRecipeId", "getIsSee", "getPreNo"]),
    showRecordLoading() {
      return true;
    },
  },
  filters: {
    ftsjj(value) {
      if (value == 1) {
        return "慎用";
      }
      if (value == 2) {
        return "忌用";
      }
      if (value == 3) {
        return "禁用";
      }
    },
    fyfsjj(value) {
      if (value == 1) {
        return "孕妇慎用";
      }
      if (value == 2) {
        return "孕妇忌用";
      }
      if (value == 3) {
        return "孕妇禁用";
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";
@import "../../style/media/diagnosis/prescribing-common.scss";
.prescribing {
  height: 100%;
  // background: red;

  // AcupointTable 在适宜技术处方 tab 中撑满高度并允许滚动
  .center-table ::v-deep .recipe-acupoint-wrapper {
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;

    .recipe-acupoint {
      flex: 1;
      min-height: 0;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
  }

  .pre-title {
    margin-bottom: 10px;

    .title-container {
      span {
        width: 3px;
        height: 14px;
        background: #5386f6;
        border-radius: 1px;
        display: inline-block;
      }

      div {
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #5386f6;
        margin-left: 9px;
      }
    }

    .patiens-msg {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;

      .p {
        margin-bottom: 5px;
        cursor: default;

        .patiens-name {
          color: #5386f6;
          font-weight: bold;
          font-size: 16px;
        }

        .patiens-desc {
          display: inline-block;

          .matname {
            color: #5386f6;
          }
        }

        .patiens-cate {
          font-weight: bold;
        }
      }
    }
  }

  .pre-left {
    height: 100%;
    width: 200px;
    padding: 10px 12px;
    background: #fff;
    box-sizing: border-box;
    margin-right: 5px;
    overflow-y: auto;
    height: 470px;

    .patiens-msg {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #333333;

      h4 {
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #333333;
        margin-bottom: 5px;
      }

      p {
        span {
          display: inline-block;
          width: 70px;
          text-align: right;
        }

        margin-bottom: 5px;
      }
    }

    .pre-steps {
      .find-more {
        cursor: pointer;

        img {
          width: 12px;
        }

        span {
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #ffae45;
          margin-left: 7px;
        }
      }

      .icon {
        width: 22px;
      }

      .step-body:hover {
        background: #d8d8d8;
      }

      .step-name {
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        cursor: pointer;
      }
    }
  }

  .pre-right {
    overflow: auto;
    height: 100%;
    margin-left: 5px;
    width: 200px;
    padding: 10px 10px;
    background: #fff;
    box-sizing: border-box;
    overflow-y: auto;
    height: 470px;

    .tuidao {
      cursor: pointer;
      width: 70px;
      height: 26px;
      background: #ffae45;
      border-radius: 2px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #ffffff;
    }
  }

  // 协定方
  .agreement {
    .agree-tab {
      div {
        width: 66px;
        height: 24px;
        background: rgba($color: #5386f6, $alpha: 0.1);
        font-size: 13px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        cursor: pointer;
      }

      .agree-active {
        background: #5386f6;
        color: #fff;
      }
    }

    .collapse {
      border: 1px solid #ebeef5;

      // padding: 0 0 0 10px;
    }

    .collapse-item {
      // margin-bottom: 10px;
      padding: 13px;
      border-bottom: 1px dashed #ebeef5;

      .med-name {
        // width: 70px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;
        cursor: pointer;
      }

      .med-name:hover {
        background: #d8d8d8;
      }

      .med-btns {
        margin-left: 10px;

        div {
          width: 34px;
          height: 20px;
          background: #5386f6;
          border-radius: 2px;
          color: #fff;
          font-size: 12px;
          font-family: PingFang SC;
          font-weight: 400;
          cursor: pointer;
          color: #ffffff;
        }

        .bg-yellow {
          background: #ffae45;
          margin-left: 10px;
        }
      }
    }

    .collapse-more {
      // margin-top: 10px;

      img {
        width: 26px;
      }
    }

    .basis {
      border: 1px solid #ebeef5;

      .basis-top-search {
        padding: 9px 7px 9px 11px;
        border-bottom: 1px dashed #eaeaea;

        .search-btn {
          width: 37px;
          height: 28px;
          background: #ffb55f;
          border-radius: 0 2px 2px 0;
          cursor: pointer;
          font-size: 12px;
          font-family: Source Han Sans CN;
          font-weight: 400;
          color: #ffffff;
        }
      }
    }
  }

  .pre-center {
    display: flex;
    flex-direction: column;
    flex: 1;
    padding: 5px 5px;
    background: #fff;
    box-sizing: border-box;
    overflow: hidden;

    > div { flex: none; }
    > div.center-table { flex: auto; }
    .center-tab {
      div {
        cursor: default;
        width: 146px;
        height: 26px;
        background: rgba($color: #5386f6, $alpha: 0.1);
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #666666;
        margin-right: 2px;

        span {
          margin-right: 9px;
        }
      }

      .active {
        background: #5386f6;
        color: #fff;
      }

      .checked {
        img {
          width: 16px;
          margin-top: 5px;
        }
      }
    }

    .header-total {
      font-size: 12px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;

      div {
        margin-left: 20px;
      }

      span {
        color: #ff3a3a;
      }
    }

    .center-table {
      border: 2px solid #dedede;
      padding: 0px 0 0;
      height: 100%;
      overflow: hidden;
      // min-height: 680px;
      // position: relative;

      .table-header {
        padding-bottom: 0px;
        border-bottom: 2px solid #dedede;

        .table-label {
          .label-item {
            cursor: pointer;
            width: 134px;
            border-right: 2px solid #eaeaea;

            div {
              color: #666;
              transform: rotate(45deg);
              font-size: 28px;
              margin-left: 12px;
              margin-top: 1px;
            }
          }

          span {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #666666;
          }

          .l_active {
            color: #5386f6;
          }
        }
      }

      .add-presc {
        width: 70px;
        height: 26px;
        background: #ffae45;
        border-radius: 4px;
        font-size: 12px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
        margin-right: 20px;
      }

      .table-container {
        padding: 37px 10px;

        .t-con-header {
          margin-bottom: 20px;

          .t-con-radio {
            flex: 1;
          }

          .t-radio-title {
            width: 82px;
            font-size: 16px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #333333;
          }

          .t-radio-group {
            flex: 1;
          }

          .add-presc1 {
            width: 84px;
            height: 34px;
            background: #ffae45;
            border-radius: 4px;
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: bold;
            color: #ffffff;
          }
        }
      }

      .table-show {
        width: 100%;

        // background: #5386F6;
        // overflow: hidden;

        .table-left-body {
          width: 49.5%;
          position: relative;
          perspective: 100px;
          padding-bottom: 53px;
        }

        .table-left {
          width: 100%;
          overflow-y: auto;
          border: 1px solid #dedede;
          box-sizing: border-box;

          .table-l-hader {
            white-space: nowrap;

            div {
              display: inline-block;
              // padding: 15px 10px;
              background: #f3fffb;
              text-align: center;
              height: 48px;
              line-height: 48px;
              border: 1px solid #dedede;
              border-bottom: 0 !important;
              // border-top: 0 !important;
            }

            .med-name {
              margin-left: 50px;
            }

            .kucun {
              padding-right: 120px;
            }

            .fixed-r {
              position: fixed;
              right: 0;
            }

            .fixed-left {
              position: fixed;
              left: 0;
            }
          }

          .table-l-item {
            white-space: nowrap;

            .bg-green {
              .div1 {
                background: #f3fffb;
                border: 1px solid #dedede;
              }
            }

            .div1 {
              display: inline-block;
              // padding: 15px 10px;
              background: #ffffff;
              text-align: center;
              height: 53px;
              line-height: 53px;
              border: 1px solid #dedede;
              z-index: 9999;
              border-top: 0 !important;
            }

            .med-name {
              margin-left: 50px;
            }

            .kucun {
              padding-right: 120px;
              border-right: 1px solid #dedede;
            }

            .fixed-r {
              position: fixed;
              right: 0;
            }

            .fixed-left {
              position: fixed;
              left: 0;
              // border-left: 1px solid #DEDEDE;
            }

            .no-data {
              width: 100%;
              box-sizing: border-box;
              // border-top: 1px solid #DEDEDE;
              position: relative;
              left: 0;
              right: 0;
              bottom: 0px;
              // float: left;
            }
          }
        }
      }

      .operate {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-around;

        img {
          width: 16px;
        }
      }

      .bottom-input {
        background: #fff;
        padding: 12.5px 30px 12.5px 52px;
        position: relative;
        // z-index: 999;
        // perspective: 100px;

        .div {
          width: 154px;
        }

        .table-choose {
          z-index: 9999;
          width: 332px;
          height: 221px;
          background: #ffffff;
          border: 2px solid #d8d8d8;
          position: relative;
          top: 2px;
          left: -48px;
          overflow: auto;

          .table-choose-h {
            background: #f3fffb;

            div {
              height: 36px;
              width: 73px;
            }

            div:first-child {
              width: 115px;
            }
          }

          .t-c-b {
            cursor: pointer;

            .td {
              background: #f3fffb;
            }

            p {
              border: 1px solid #ededed;
              height: 36px;
              width: 73px;
              // flex: 1;
              box-sizing: border-box;
            }

            p:first-child {
              width: 115px;
            }
          }
        }
      }

      .table-bottom {
        // position: absolute;
        // bottom: 0;
        // right: 0;
        // left: 0;\
        padding: 0 37px;
        margin-top: 241px;

        .header-about {
          .item {
            margin-right: 20px;
            margin-bottom: 10px;

            span {
              font-size: 16px;
              font-family: PingFang SC;
              font-weight: 400;
              color: #333333;
            }

            .div1 {
              width: 120px;
            }

            .div2 {
              width: 74px;
            }

            .city1 {
              width: 120px;
            }

            .div3 {
              width: 92px;
            }

            .div4 {
              width: 160px;
            }

            .input-suffix {
              line-height: 36px;
            }
          }

          .right {
            width: 70px;
            height: 26px;
            background: #ffae45;
            border-radius: 4px;
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #ffffff;
            margin-bottom: 10px;
            cursor: pointer;
          }
        }
      }

      .table-b-bottom {
        padding: 10px 27px;
        border-top: 2px solid #dedede;
        margin-top: 10px;

        .t-b-l-item {
          font-size: 16px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;
          margin-right: 20px;

          span {
            color: #ff6245;
          }
        }

        .t-b-b-right {
          div {
            width: 130px;
            height: 46px;
            background: #ffae45;
            border-radius: 4px;
            font-size: 16px;
            font-family: PingFang SC;
            font-weight: 500;
            color: #ffffff;
            cursor: pointer;
          }

          .bg-green {
            background: #5386f6;
            margin-left: 20px;
          }
        }
      }

      // 中成药 和适宜技术配方
      .chinese_medicine {
        padding: 0 37px;

        .clearer {
          width: 84px;
          height: 34px;
          background: #ffae45;
          border-radius: 4px;
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: bold;
          color: #ffffff;
          cursor: pointer;
          margin-bottom: 20px;
        }

        .c-m-table {
          width: 100%;
          overflow: hidden;

          .unit {
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #000000;
            // margin-left: 10px;
          }

          .input {
            width: 40px;
          }
        }
      }
    }
  }
}

.table-choose3 {
  z-index: 99999;
  width: 332px;
  height: 221px;
  background: #ffffff;
  border: 2px solid #d8d8d8;
  // position: absolute;
  position: fixed;

  margin-top: 33px;
  // left: -4px;
  overflow: auto;

  .table-choose-h {
    background: #f3fffb;

    div {
      height: 36px;
      width: 73px;
    }

    div:first-child {
      width: 115px;
    }
  }

  .t-c-b {
    cursor: pointer;

    .td {
      background: #f3fffb;
    }

    p {
      border: 1px solid #ededed;
      height: 36px;
      width: 73px;
      // flex: 1;
      box-sizing: border-box;
    }

    p:first-child {
      width: 115px;
    }
  }
}

.drug-body {
  box-sizing: border-box;
  // height: 50vh;
  padding: 0 50px;

  .drug-item {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #333333;
    margin-bottom: 10px;

    .trun-join {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }

    .bg-yellow {
      margin-left: 10px;
      background: #ffae45 !important;
    }

    span {
      display: inline-block;
      width: 100px;
      text-align-last: justify;
    }

    div {
      flex: 1;

      img {
        width: 126px;
        height: 126px;
        // background: red;
        margin-right: 32px;
      }

      span {
        text-align-last: left;
      }
    }

    .detail {
      flex: 1;

      .btns {
        width: 80px;
        height: 30px;
        background: #5386f6;
        border-radius: 2px 2px 2px 2px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
        margin-bottom: 20px;
      }

      .drug-detail {
        span {
          text-align-last: left;
          margin-right: 10px;
          margin-bottom: 10px;
        }
      }
    }
  }

  .drug-item1 {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #333333;
    margin-bottom: 15px;
    margin-right: 50px;

    div {
      flex: 1;
    }
  }

  .mad-cy {
    color: #5386f6;
    font-weight: bold;
  }
}

.testCase {
  padding: 0 50px;

  .testCase-item {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #333333;
    margin-bottom: 10px;

    .testCase-left {
      text-align-last: justify;
      width: 112px;
    }

    .testCase-right {
      flex: 1;
    }

    .case-yijian {
      margin-bottom: 15px;

      span {
        margin-right: 5px;
      }

      .testCase-btns {
        width: 80px;
        height: 30px;
        background: #5386f6;
        border-radius: 2px 2px 2px 2px;
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
      }
    }

    .case-detial {
      span {
        margin-right: 20px;
        margin-bottom: 15px;
      }
    }
  }

  .testCase-title {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #5386f6;
    margin-bottom: 15px;
  }
}

// 推荐方剂
.recommend {
  cursor: pointer;
  .arrow-left {
    width: 11px;
    height: 80px;
    background: #d8d8d8;
    border-radius: 6px;

    img {
      width: 6px;
    }
  }

  .banner {
    flex: 1;
    height: 80px;
    margin: 0 0px;
    overflow-y: auto;

    .r-banner-body {
      cursor: pointer;
      .r-body-item {
        margin-bottom: 10px;

        .med-name {
          // width: 70px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 14px;
          font-family: PingFang SC;
          font-weight: 400;
          color: #333333;

          span {
            cursor: pointer;
          }
        }

        .icon-expr {
          width: 18px;
        }

        .med-name1 {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          flex: 1;

          img {
            width: 18px;
            margin-right: 5px;
          }

          span {
            display: inline-block;
            // width: 70px;
            width: 100%;
            // flex: 1;
            // background: #5386F6;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 14px;
            font-family: PingFang SC;
            font-weight: 400;
            // color: #333333;
            color: #5386f6;
            cursor: pointer;
          }
        }

        // .med-name-bg:hover {
        //     background: #D8D8D8;
        // }

        .med-name:hover {
          background: #d8d8d8;
        }

        .med-btns {
          div {
            width: 34px;
            height: 20px;
            background: #5386f6;
            border-radius: 2px;
            color: #fff;
            font-size: 12px;
            font-family: PingFang SC;
            font-weight: 400;
            cursor: pointer;
            color: #ffffff;
          }

          .bg-yellow {
            background: #ffae45;
            margin-left: 10px;
          }
        }
      }
    }
  }

  .active {
    color: #5386f6 !important;
  }
}
.pre-steps::v-deep .el-step__icon.is-text {
  border: 0;
}

.collapse::v-deep .el-collapse-item__header {
  padding: 0 0 0 10px;
  border-bottom: 1px dashed #ebeef5;
  font-size: 14px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #333333;
}

.body-msg {
  span {
    font-size: 16px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #333333;
    margin-bottom: 5px;
  }
}

.collapse ::v-deep .el-collapse-item__content {
  padding-bottom: 5px;
}

.c-m-table::v-deep .el-table .cell {
  text-align: center;
}

.table-show::v-deep .el-table .cell {
  text-align: center;
}

.c-m-table::v-deep .el-select input {
  padding: 0 15px 0 5px;
}

.table-show ::v-deep .el-select input {
  padding: 0 15px 0 5px;
}

.t_dose::v-deep .el-input__inner {
  // text-align: left;
  padding: 0 5px !important;
}

.city::v-deep .el-select input {
  padding: 0 20px 0 10px;
  // height: 32px;
}

.xuewei::v-deep .el-select {
  width: 100%;
}

// 滚动条位置
.prescribing ::v-deep .__bar-is-vertical {
  right: -1px !important;
}

// 隐藏横向滚动条
.prescribing ::v-deep .__bar-is-horizontal {
  display: none !important;
}

.table-left-body::v-deep .el-table__empty-text {
  color: #fff;
}
</style>
<style lang="scss" scoped>
@import "../../style/media/diagnosis/prescribing.scss";

/* 西医诊断搜索样式 - scoped 穿透 */
.prescribing ::v-deep .his-item .value:has(.western-disease-input-wrapper) {
  width: auto;
  min-width: 200px;
  flex: 1;
}

.prescribing ::v-deep .western-disease-input-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 2px 4px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  min-height: 28px;
  cursor: text;

  .el-tag {
    margin: 2px 4px 2px 0;
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .el-autocomplete {
    flex: 1;
    min-width: 80px;
  }

  .el-input {
    border: none !important;
    background: transparent !important;
  }

  .el-input__wrapper {
    border: none !important;
    background: transparent !important;
    box-shadow: none !important;
    padding: 0 !important;
  }

  .el-input__inner {
    border: none !important;
    padding: 0 4px;
    height: 24px;
    line-height: 24px;
    background: transparent !important;
    box-shadow: none !important;
  }

  .el-input__suffix {
    display: flex;
    align-items: center;
  }

  &:hover {
    border-color: #c0c4cc;
  }

  &:focus-within {
    border-color: #409eff;
  }

  &.view-mode {
    cursor: default;
    background: #f5f7fa;

    .el-tag {
      background-color: #f0f2f5;
      border-color: #e4e7ed;
      color: #909399;
    }
  }
}

.autocomplete-disabled {
  color: #999 !important;
  cursor: not-allowed !important;
  pointer-events: none;
}

</style>
<style lang="scss">
.reasonable-safe-medicines-wrapper {
  .item {
    .label {
      margin: 12px 0 6px;
      font-size: 16px;
      font-weight: 700;
    }

    .value {
      line-height: 1.75;

      span {
        &:first-of-type {
          color: #5386f6;
        }

        &:last-of-type {
          color: #333;
        }
      }
    }

    .highlight {
      color: #ff4d4f !important;
    }
  }
}

.message-rational-safe-use-wrapper {
  align-items: flex-start;
  max-height: 80vh;
  overflow-y: auto;

  &.el-message-box {
    overflow-y: hidden;

    .el-message-box__content {
      max-height: calc(80vh - 45px - 48px);
      overflow: auto;
    }
  }

  .title {
    font-size: 16px;
    font-weight: 700;
  }

  .content {
    margin: 12px 0;

    > div {
      margin: 8px 0;
    }
  }

  .el-message__content {
    width: 100%;
    color: #333;
  }
  .reasonable-safe-medicines-wrapper {
    padding-bottom: 8px;
  }
}

</style>