<template>
  <div class="layout_container fill-sheet">
    <header class="round-header">
      <el-select
        v-model="currentWard"
        @change="handleWardChange"
        style="width: 120px"
        filterable
      >
        <el-option
          v-for="item in userWards"
          :key="item.code"
          :value="item.code"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-select
        v-model="inOutStatus"
        style="width: 80px; margin-right: 8px"
        @change="changeInOutStatus"
      >
        <el-option
          v-for="item in inOutOptions"
          :key="item.code"
          :value="item.code"
          :label="item.name"
        ></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="Clock"
        v-show="inOutStatus === 2"
        @click="showSelectDateRange = true"
      >
        日期范围
      </el-button>
      <el-divider direction="vertical"></el-divider>
      <el-input
        v-model="inpatientNo"
        style="width: 110px"
        placeholder="住院号"
        clearable
      ></el-input>
      <el-button
        type="primary"
        icon="Search"
        @click="searchPatient"
        style="margin-left: 8px"
        >搜索患者
      </el-button>
      <el-divider direction="vertical"></el-divider>
      <el-button
        type="primary"
        icon="Edit"
        @click="openYbDiag"
        v-if="inOutStatus === 1"
        >医保诊断
      </el-button>
      <el-button type="primary" icon="Upload" @click="saveVerify(1)"
        >保存首页
      </el-button>
      <el-dropdown
        trigger="click"
        type="primary"
        @command="sheetQualityVerification"
        style="margin: 0 8px"
      >
        <el-button icon="DataLine" type="primary"
          >病案质控<i class="el-icon-arrow-down el-icon--right"></i
        ></el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="applyVerification"
              >申请审核
            </el-dropdown-item>
            <el-dropdown-item command="verificationRecord"
              >审核记录
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button type="success" icon="Printer" @click="beforePrint(1)"
        >打印正面
      </el-button>
      <el-button type="success" icon="Printer" @click="beforePrint(2)"
        >打印反面
      </el-button>
      <el-button
        type="primary"
        icon="PieChart"
        @click="setlUplaodClick"
        v-if="inOutStatus === 2"
      >
        结算清单质控
      </el-button>
      <el-button type="danger" icon="Download" @click="showExportPanel"
        >历史病案导出
      </el-button>
    </header>
    <div class="layout_main layout_container layout-horizontal">
      <aside class="layout_el-table">
        <el-table
          ref="asideTable"
          :data="cptOverviews"
          stripe
          highlight-current-row
          @row-click="handleClickOverview"
        >
          <el-table-column
            prop="bedNo"
            label="床号"
            width="40"
          ></el-table-column>
          <el-table-column label="姓名" width="75">
            <template #default="scope">
              <img
                class="sex-icon"
                :src="scope.row.sex === 1 ? maleIcon : femaleIcon"
              />
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="住院号-次数" width="85">
            <template #default="scope">
              <span style="font-weight: bold; color: black">
                {{ scope.row.bah }}
              </span>
              -{{ scope.row.times }}
            </template>
          </el-table-column>
          <el-table-column prop="doctorName" label="医生" width="90">
            <template #header>
              <span style="margin-right: 8px">医生</span>
              <el-checkbox v-model="onlyShowMyPatients">我的</el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </aside>
      <div
        style="
        opacity: 1;
          min-width: 800px;
          padding: 0 20px 0 35px;
          overflow-y: scroll;
          position: relative;
        "
        id="scrollWrapper"
      >
        <div style="position: absolute; top: 20px; left: 20px">
          <span
            v-if="patient.auditState === 'NONE'"
            class="audit-state audit-state_none"
          >
            病案质控未申请
          </span>
          <span
            v-else-if="patient.auditState === 'INITIAL'"
            class="audit-state audit-state_initial"
          >
            病案质控未审核
          </span>
          <span
            v-else-if="patient.auditState === 'APPROVED'"
            class="audit-state audit-state_approved"
          >
            病案质控已通过
          </span>
          <span
            v-else-if="patient.auditState === 'REJECTED'"
            class="audit-state audit-state_rejected"
            @click="sheetQualityVerification('verificationRecord')"
          >
            病案质控已驳回
          </span>
        </div>
        <div>
          <h3 style="width: 100%; font-size: 17px; text-align: center">
            住 院 病 案 首 页
          </h3>
          <div style="width: 100%; font-size: 15px; text-align: center">
            医疗机构:
            <span style="font-weight: 700">{{ env.VITE_HOSPITAL_NAME }}</span>
            （ 组织机构代码:
            <span style="font-weight: 700">{{ env.VITE_UNIFIED_SOCIAL_CREDIT_CODE_CODE }}</span
            >）
          </div>
          <div style="height: 25px; line-height: 25px; display: flex">
            <div>
              医疗付费方式:
              <select
                id="payMethod"
                v-model="patient.payMethod"
                style="width: 180px"
              >
                <option
                  v-for="item in 9"
                  :key="item"
                  :value="item"
                >
                  &nbsp;&nbsp;{{ item }}&nbsp;&nbsp;
                </option>
              </select>
            </div>
            <div style="width: 120px; margin-left: 12px">
              住院次数: {{ patient.healthCardNo }}
            </div>
            <div style="width: 100px">
              第&nbsp;{{ patient.admissTimes }}&nbsp;次住院
            </div>
            <div style="width: 130px">病案号: {{ patient.bah }}</div>
          </div>
        </div>
        <div id="page1" style="border: 1px solid black; padding: 5px">
          <div style="display: flex;align-items: end">
            姓名:
            <input id="name" v-model="patient.name" style="width: 130px" />
            性别:
            <select id="sex" v-model="patient.sex">
              <option
                v-for="item in sexList"
                :key="item"
                :value="item"
              >
                &nbsp;&nbsp;{{ item }}&nbsp;&nbsp;
                
              </option>
            </select>
            1.男&nbsp;2.女&nbsp;9.未说明的性别&nbsp;&nbsp;&nbsp;
            <span style="margin-left: 12px">出生日期</span>
            <div id="birthDate" style="display: flex;align-items: end">
              <input
                  v-model="patientTransformData.birthYear"
                  style="width: 35px;padding-left: 5px"
              />
              年
              <input
                  v-model="patientTransformData.birthMonth"
                  style="width: 20px;padding-left: 5px"
              />
              月
              <input
                  v-model="patientTransformData.birthDay"
                  style="width: 20px;padding-left: 5px"
              />
              日
            </div>
          </div>
          <div>
            年龄:
            <input
              id="age"
              v-model="patientTransformData.age"
              type="number"
              style="width: 30px"
            />
            国籍:
            <select id="country" v-model="patient.country">
              <option
                v-for="(item, index) in dics.getCountry"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;
              </option>
            </select>
            （年龄不足 1 周岁的）年龄:
            <input
              id="ageDays"
              v-model="patientTransformData.infAge"
              style="width: 50px"
            />月
            （新生儿年龄≤28天）年龄:
            <input
              id="ageDays"
              v-model="patientTransformData.ageDays"
              style="width: 50px"
            />天
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            新生儿出生体重 （一孩
            <input
                id="newBornWeight1"
                v-model="patientTransformData.newBornWeight1"
                style="width: 40px;padding-left: 5px"
            />克
            <span style="margin-left: 12px">二孩</span>
            <input
                id="newBornWeight2"
                v-model="patientTransformData.newBornWeight2"
                style="width: 40px;padding-left: 5px"
            />克）
            <span style="margin-left: 12px">
              新生儿入院体重
            </span>
            <input
                id="newBornAdmissWeight"
                v-model="patientTransformData.newBornAdmissWeight"
                style="width: 50px;padding-left: 5px"
            />克
          </div>
          
          <div>
            身份证件类型:
            <select id="occupation" v-model="patient.psnCertificateType">
              <option
                v-for="(item, index) in dics.getPsnCertType"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            证件号:
            <input
              id="socialNo"
              v-model="patient.socialNo"
              style="width: 160px"
              maxlength="18"
            />
            
            
          </div>
          <div>
            身份证件不详的具体原因:
            <select id="occupation" v-model="patient.noCertReason">
              <option
                v-for="(item, index) in noCertReasons"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="(item,index) in noCertReasons">
              <template v-if="index > 0">{{ item.code }}.{{ item.name }}</template>
            </span>
            其他:
            <input
              id="socialNo"
              v-model="patient.noCertReasonInput"
              style="width: 160px"
            />
          </div>
          <div>
            出生地:
            <input
              id="birthPlaceName"
              v-model="patient.birthPlaceName"
              style="width: 230px"
            />
            <el-button
              icon="Search"
              type="primary"
              @click="showSearchData('birth')"
            >
            </el-button>
            籍贯:
            <input
              id="nativePlaceName"
              v-model="patient.nativePlaceName"
              readonly
              style="width: 170px"
              @click="showSearchData('native')"
            />
            民族:
            <select id="nation" v-model="patient.nation">
              <option
                v-for="(item, index) in dics.getNation"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;
              </option>
            </select>
          </div>
          <div>
            职业:
            <select id="occupation" v-model="patient.occupation">
              <option
                v-for="(item, index) in dics.getOccupation"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;
              </option>
            </select>
            婚姻:
            <select id="marriage" v-model="patient.marriage">
              <option
                v-for="(item, index) in dics.getMarriageCode"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="item in dics.getMarriageCode">
              {{ item.code }}.{{ item.name }}
            </span>
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            <div id="livePlace">
              现住址
              <input
                  id="livePlace"
                  v-model="patient.livePlace"
                  style="width: 350px;padding-left: 5px"
              />
              <el-button
              icon="Search"
              type="primary"
              @click="showSearchData('livePlace')"
            >
            </el-button>
            </div>
            <span style="margin-left: 12px">电话</span>
            <input id="phone" v-model="patient.phone" style="width: 90px;padding-left: 5px"/>
            <span style="margin-left: 12px">邮编</span>
            <input
                id="addrZipCode"
                v-model="patient.addrZipCode"
                style="width: 70px;padding-left: 5px"
                maxlength="6"
            />
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            <div id="hkPlace">
              户口地址
              <input
                  id="hkPlaceName"
                  v-model="patient.hkPlaceName"
                  style="width: 480px;padding-left: 5px"
              />
              <el-button
                icon="Search"
                type="primary"
                @click="showSearchData('hk')"
              >
              </el-button>
            </div>
            <span style="margin-left: 12px">邮编</span>
            <input
                id="hkZipCode"
                v-model="patient.hkZipCode"
                style="width: 70px;padding-left: 5px"
                maxlength="6"
            />
          </div>
          <div>
            工作单位及地址:
            <input
              id="unitName"
              v-model="patient.unitName"
              style="margin-right: 0; width: 145px"
            />
            /
            <input
              id="unitPlace"
              v-model.trim="patient.unitPlace"
              style="width: 145px"
            />
            单位电话:
            <input
              id="unitPhone"
              v-model="patient.unitPhone"
              style="width: 80px"
            />
            邮编:
            <input
              id="unitZipCode"
              v-model="patient.unitZipCode"
              style="width: 50px"
            />
          </div>
          <div>
            联系人姓名:
            <input
              id="contactName"
              v-model="patient.contactName"
              style="width: 200px"
            />
            联系人关系:
            <select id="contactRelation" v-model="patient.contactRelation">
              <option
                v-for="(item, index) in dics.getRelations"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;
              </option>
            </select>
          </div>
          <div>
            联系人地址:
            <input
              id="contactAddrName"
              v-model="patient.contactAddrName"
              style="width: 420px"
            />
            <el-button
                icon="Search"
                type="primary"
                @click="showSearchData('contact')"
              >
              </el-button>
            联系人电话:
            <input
              id="contactPhone"
              v-model.trim="patient.contactPhone"
              style="width: 90px"
            />
          </div>
          <div>
            入院途径:
            <select id="zyAdmissWay" v-model="patient.zyAdmissWay">
              <option
                v-for="(item, index) in dics.getAdmissWay"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
              
            </select>
            <span v-for="item in dics.getAdmissWay">
              {{ item.code }}.{{ item.name }}
            </span>&nbsp;&nbsp;&nbsp;&nbsp;
          </div>
          <div>
            入院时间:<input
              id="admissDate"
              v-model="patient.admissDate"
              readonly
              style="width: 135px"
            />
            入院科别:<input
              v-model="patient.admissDept"
              readonly
              style="width: 120px"
            />
            病房:<input
              v-model="patient.admissWard"
              readonly
              style="width: 80px"
            />
            转科科别:<input
              v-model="patientTransformData.transDept"
              readonly
              style="width: 120px"
            />
          </div>
          <div>
            出院时间:<input
              id="dismissDate"
              v-model="patient.dismissDate"
              readonly
              style="width: 135px"
            />
            出院科别:<input
              v-model="patient.dismissDept"
              readonly
              style="width: 120px"
            />
            病房:<input
              v-model="patient.dismissWard"
              readonly
              style="width: 80px"
            />
            住院天数:<input
              id="admissDays"
              v-model="patient.admissDays"
              style="width: 70px"
            />
          </div>
          <div id="clinicDiag" style="display: flex; align-items: center">
            门（急）诊诊断:
            <input
              v-model="patient.clinicDiagStr"
              readonly
              style="width: 280px"
              @click="showSearchData('clinicdiag')"
            />
            疾病编码:
            <input
              v-model="patient.clinicDiagCode"
              readonly
              style="width: 110px"
              @click="showSearchData('clinicdiag')"
            />
            
          </div>
          
          <div
            id="diagTable"
            style="
              height: max-content;
              display: flex;
              width: 720px;
              margin-top: 2px;
            "
          >
            <div style="width: 360px">
              <table
                style="
                  width: 100%;
                  border: 1px solid black;
                  border-collapse: collapse;
                "
              >
                <tr>
                  <th>主要诊断</th>
                  <th>疾病编码</th>
                  <th>入院病情</th>
                  <th>治疗转归</th>
                </tr>
                <tr>
                  <td>
                    <input
                      id="disdiagMain"
                      style="border: none !important; width: 170px"
                      v-model="patient.disdiagList[0].name"
                      @click="onSearchDiagFocus(0)"
                      readonly
                    />
                    <div
                      v-show="showDel[0]"
                      style="width: 100%; text-align: center"
                    >
                      <el-button
                        type="primary"
                        icon="Edit"
                        @click="showSearch = true"
                        >修改
                      </el-button>
                    </div>
                  </td>
                  <td style="text-align: center">
                    <input
                      style="border: none !important; width: 100px"
                      v-model="patient.disdiagList[0].code"
                      readonly
                    />
                  </td>
                  <td>
                    <select
                      id="disdiagMainAdmStatus"
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[0].admissStatus"
                    >
                      <option
                        v-for="(item, index) in dics.getDisAdmissStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp; {{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                  <td>
                    <select
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[0].dismissStatus"
                      @change="handleSelectCybq"
                    >
                      <option
                        v-for="(item, index) in dics.getDisdiagStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp; {{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                </tr>
                <tr>
                  <th colspan="4">其他诊断</th>
                </tr>
                <tr v-for="n in 11" :key="n">
                  <td>
                    <input
                      style="
                        border: none !important;
                        text-align: left;
                        padding-left: 5px;
                      "
                      v-model="patient.disdiagList[n].name"
                      @click="onSearchDiagFocus(n)"
                      readonly
                    />
                    <div
                      v-show="showDel[n]"
                      style="width: 100%; text-align: center"
                    >
                      <el-button
                        type="primary"
                        circle
                        icon="Edit"
                        @click="showSearch = true"
                      ></el-button>
                      <el-button
                        type="danger"
                        circle
                        icon="Delete"
                        @click="deleteDisdiag(n)"
                      ></el-button>
                      <el-button
                        type="success"
                        circle
                        icon="Plus"
                        @click="insertDisdiag(n)"
                      ></el-button>
                    </div>
                  </td>
                  <td>
                    <input
                      style="border: none !important; width: 90px"
                      v-model="patient.disdiagList[n].code"
                      readonly
                    />
                  </td>
                  <td>
                    <select
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[n].admissStatus"
                    >
                      <option
                        v-for="(item, index) in dics.getDisAdmissStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                  <td>
                    <select
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[n].dismissStatus"
                      @change="handleSelectCybq"
                    >
                      <option
                        v-for="(item, index) in dics.getDisdiagStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                </tr>
              </table>
            </div>
            <div style="width: 360px">
              <table style="border: 1px solid black; border-collapse: collapse">
                <tr v-for="n in 14" :key="n">
                  <td>
                    <input
                      style="border: none !important; width: 170px"
                      v-model="patient.disdiagList[n + 11].name"
                      @click="onSearchDiagFocus(n + 11)"
                      readonly
                    />
                    <div
                      v-show="showDel[n + 11]"
                      style="width: 100%; text-align: center"
                    >
                      <button circle @click="showSearch = true">
                        <i class="el-icon-edit"></i>
                      </button>
                      <button circle @click="deleteDisdiag(n + 11)">
                        <i class="el-icon-delete"></i>
                      </button>
                      <button circle @click="insertDisdiag(n + 11)">
                        <i class="el-icon-upload"></i>
                      </button>
                    </div>
                  </td>
                  <td>
                    <input
                      style="border: none !important; width: 100px"
                      v-model="patient.disdiagList[n + 11].code"
                      readonly
                    />
                  </td>
                  <td>
                    <select
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[n + 11].admissStatus"
                    >
                      <option
                        v-for="(item, index) in dics.getDisAdmissStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                  <td>
                    <select
                      style="border: none !important; width: 30px"
                      v-model="patient.disdiagList[n + 11].dismissStatus"
                      @change="handleSelectCybq"
                    >
                      <option
                        v-for="(item, index) in dics.getDisdiagStatus"
                        :key="index"
                        :value="item.code"
                      >
                        &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
                      </option>
                    </select>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div style="border-bottom: 1px solid black; font-size: 12px">
            备注：
            <span>入院病情：</span>1.有，2.临床未确定，3.情况不明，4.无
            <span style="margin-left: 10px">出院病情：</span
            >1.治愈，2.好转，3.未愈，4.死亡，9.其他
          </div>
          <div>
            损伤、中毒的外部原因:
            <input
              id="hurtReasonName"
              v-model="patientTransformData.hurtReasonName"
              readonly
              style="width: 360px"
              @click="showSearchData('hurt')"
            />
            疾病编码:
            <input
              id="hurtReasonCode"
              v-model="patientTransformData.hurtReasonCode"
              style="width: 110px"
              readonly
            />
            &nbsp;&nbsp;<el-button
              type="danger"
              circle
              icon="Delete"
              @click="clearLine('hurtReason')"
            ></el-button>
          </div>
          <div>
            病理诊断:
            <input
              id="pathologicDiagStr"
              v-model="patientTransformData.pathologicDiagStr"
              readonly
              style="width: 300px"
              @click="showSearchData('pathologic')"
            />
            病理编码:
            <input
              id="pathologicDiagCode"
              v-model="patientTransformData.pathologicDiagCode"
              style="width: 90px"
              readonly
            />
            病理号:
            <input id="blh" v-model="patientTransformData.blh" style="width: 70px" />
            &nbsp;&nbsp;<el-button
              type="danger"
              circle
              icon="Delete"
              @click="clearLine('pathologicDiag')"
            ></el-button>
          </div>
          <div>
            药物过敏:
            <select
              id="allergy"
              v-model="patient.allergy"
              @change="onAllergyChanged"
            >
              <option
                v-for="(item, index) in haveOrNot"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            1.无&nbsp;2.有&nbsp;&nbsp;&nbsp;
            过敏药物:
            <input
              id="allergicMedicine"
              v-model="patient.allergicMedicine"
              style="width: 110px"
            />
            死亡患者尸检:
            <select id="autopsy" v-model="patient.autopsy">
              <option
                v-for="(item, index) in autopsies"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            1.是&nbsp;2.否&nbsp;&nbsp;&nbsp;
          </div>
          <div>
            血型:
            <select
              id="bloodType"
              v-model="patient.bloodType"
              @change="handleSelectBloodType"
            >
              <option
                v-for="(item, index) in dics.getBloodType"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="item in dics.getBloodType">
              {{ item.code }}.{{ item.name }}
            </span>&nbsp;&nbsp;&nbsp;&nbsp;
            Rh:
            <select id="rh" v-model="patient.rh">
              <option
                v-for="(item, index) in dics.getHbsag"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="item in dics.getHbsag">
              {{ item.code }}.{{ item.name }}
            </span>&nbsp;&nbsp;&nbsp;&nbsp;
          </div>
          <div>
            科室主任:
            <input
              id="deptLeaderName"
              readonly
              style="width: 70px"
              v-model="patient.deptLeaderName"
              @click="showSearchData('deptleader')"
            />
            主任(副主任)医师:
            <input
              id="leaderDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.leaderDoctorName"
              @click="showSearchData('leaderdoctor')"
            />
            主治医师:
            <input
              id="mainDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.mainDoctorName"
              @click="showSearchData('maindoctor')"
            />
            住院医师:
            <input
              id="admissDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.admissDoctorName"
              @click="showSearchData('admissdoctor')"
            />
          </div>
          <div>
            责任护士:
            <input
              id="dutyNurseName"
              readonly
              style="width: 70px"
              v-model="patient.dutyNurseName"
              @click="showSearchData('dutynurse')"
            />
            进修医师:
            <input
              id="studyDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.studyDoctorName"
              @click="showSearchData('studydoctor')"
            />
            实习医师:
            <input
              id="internshipDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.internshipDoctorName"
              @click="showSearchData('internshipdoctor')"
            />
            编码员:
            <input
              id="coderName"
              readonly
              style="width: 70px"
              v-model="patient.coderName"
              @click="showSearchData('coder')"
            />
          </div>
          <div>
            病案质量:
            <select
              id="qualityControlLevel"
              v-model="patient.qualityControlLevel"
            >
              <option
                v-for="(item, index) in dics.getQualityLevel"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="item in dics.getQualityLevel">
              {{ item.code }}.{{ item.name }}
            </span>&nbsp;&nbsp;&nbsp;&nbsp;
            质控医师:
            <input
              id="qualityControlDoctorName"
              readonly
              style="width: 70px"
              v-model="patient.qualityControlDoctorName"
              @click="showSearchData('qualitycontroldoctor')"
            />
            质控护士:
            <input
              style="width: 70px"
              readonly
              v-model="patient.qualityControlNurseName"
              @click="showSearchData('qualitycontrolnurse')"
            />
            质控日期:
            <input
              id="qualityControlDate"
              style="width: 170px"
              type="date"
              v-model="patient.qualityControlDate"
            />
          </div>
        </div>
        <div id="page2" style="border: 1px solid black; padding: 5px">
          <table
            id="surgeryTable"
            style="border-collapse: collapse; width: 100%; margin-left: -25px"
          >
            <tr>
              <th rowspan="2" style="border: none"></th>
              <th rowspan="2">手术及操作编码</th>
              <th rowspan="2" style="width: 70px">手术及操作日期</th>
              <th rowspan="2" style="width: 10px">手术级别</th>
              <th rowspan="2">手术及操作名称</th>
              <th colspan="3">手术及操作医师</th>
              <th rowspan="2" style="width: 30px">切口愈合等级</th>
              <th rowspan="2">麻醉方式</th>
              <th rowspan="2">麻醉医师</th>
            </tr>
            <tr>
              <th>术者</th>
              <th>I助</th>
              <th>II助</th>
            </tr>
            <tr v-for="n in defaultSurgerySize" :key="n">
              <td style="border: none; width: 25px">
                <div v-if="patient.surgeryList[n - 1].name">
                  <div
                    v-if="n > 1"
                    class="order-arrow"
                    @click="changeSurgeryOrder(n - 1, n - 2)"
                  >
                    ↑
                  </div>
                  <div
                    v-if="n < defaultSurgerySize && patient.surgeryList[n].name"
                    class="order-arrow"
                    style="margin-top: 5px"
                    @click="changeSurgeryOrder(n - 1, n)"
                  >
                    ↓
                  </div>
                  <div
                    v-if="n === defaultSurgerySize"
                    class="order-arrow"
                    style="margin-top: 4px"
                    @click="addSurgeSize"
                  >
                    +
                  </div>
                </div>
              </td>
              <td>
                <input
                  v-model="patient.surgeryList[n - 1].code"
                  style="border: none !important; width: 70px"
                  readonly
                />
              </td>
              
              <td style="padding: 3px">
                <textarea
                  style="border: none !important; width: 70px"
                  v-model="patient.surgeryList[n - 1].date"
                  rows="3"
                  @click="showPickSurgeryDatetime(n - 1)"
                  readonly
                ></textarea>
              </td>
              <td style="text-align-last: center">
                <select
                  style="border: none !important; width: 30px"
                  v-model="patient.surgeryList[n - 1].level"
                >
                  <option
                    v-for="(item, index) in dics.getOperateScale"
                    :key="index"
                    :value="item.code"
                  >
                    &nbsp;&nbsp;{{ item.code }}
                  </option>
                </select>
              </td>
              <td style="padding: 3px">
                <textarea
                  id="surgeryMain"
                  style="border: none !important; width: 90px"
                  rows="3"
                  v-model="patient.surgeryList[n - 1].name"
                  @click="onSearchSurgeryFocus(n - 1)"
                  readonly
                ></textarea>
                <div
                  v-show="showDel[n - 1]"
                  style="width: 100%; text-align: center"
                >
                  <el-button
                    type="primary"
                    circle
                    icon="Edit"
                    @click="onEditSurgeryClick(n - 1)"
                  ></el-button>
                  <el-button
                    type="danger"
                    circle
                    icon="Delete"
                    @click="deleteSurgery(n - 1)"
                  ></el-button>
                </div>
              </td>
              <td>
                <input
                  style="border: none !important; width: 40px"
                  v-model="patient.surgeryList[n - 1].operatorName"
                  @click="showSearchSurgerior('operator', n)"
                />
              </td>
              <td style="width: 50px">
                <div style="position: relative">
                  <input
                    style="border: none !important; width: 40px"
                    v-model="patient.surgeryList[n - 1].assistantOneName"
                    @click="showSearchSurgerior('assistantone', n)"
                  />
                  <div
                    v-if="patient.surgeryList[n - 1].assistantOneName"
                    style="position: absolute; top: -20px; right: 0"
                  >
                    <el-button
                      type="danger"
                      circle
                      icon="Delete"
                      @click="deleteAssistantOne(n - 1)"
                    ></el-button>
                  </div>
                </div>
              </td>
              <td style="width: 50px">
                <div style="position: relative">
                  <input
                    style="border: none !important; width: 40px"
                    v-model="patient.surgeryList[n - 1].assistantTwoName"
                    @click="showSearchSurgerior('assistanttwo', n)"
                  />
                  <div
                    v-if="patient.surgeryList[n - 1].assistantTwoName"
                    style="position: absolute; top: -20px; right: 0"
                  >
                    <el-button
                      type="danger"
                      circle
                      icon="Delete"
                      @click="deleteAssistantTwo(n - 1)"
                    ></el-button>
                  </div>
                </div>
              </td>
              <td style="text-align-last: center">
                <select
                  v-model="patient.surgeryList[n - 1].cutHeal"
                  style="border: none !important"
                >
                  <option
                    v-for="(item, index) in dics.getCutHealGrade"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.code }}
                  </option>
                </select>
              </td>
              <td>
                <select
                  v-model="patient.surgeryList[n - 1].anaesthesia"
                  style="border: none !important"
                >
                  <option
                    v-for="(item, index) in dics.getAnaesthesia"
                    :key="index"
                    :value="item.code"
                  >
                    &nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;
                  </option>
                </select>
              </td>
              <td>
                <div style="position: relative">
                  <input
                    style="border: none !important; width: 40px"
                    v-model="patient.surgeryList[n - 1].anaesthesiaorName"
                    @click="showSearchSurgerior('anaesthesiaor', n)"
                  />
                  <div
                    v-if="patient.surgeryList[n - 1].anaesthesiaorName"
                    style="position: absolute; top: -20px; right: 0"
                  >
                    <el-button
                      type="danger"
                      circle
                      icon="Delete"
                      @click="deleteAnestor(n - 1)"
                    ></el-button>
                  </div>
                </div>
              </td>
            </tr>
          </table>
          <div>
            离院方式:
            <select
              id="zyDismissWay"
              v-model="patient.zyDismissWay"
            >
              <option
                v-for="(item, index) in dics.getZyDismissWay"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="item in dics.getZyDismissWay">
              {{ item.code }}.{{ item.name }}
            </span>&nbsp;&nbsp;
          </div>
          <div>
            拟接收医疗机构名称:
            <input
              id="dismissDestination"
              v-model="patient.dismissDestination"
              style="width: 250px"
            />
          </div>
          <div v-if="patient.zyDismissWay === '3' ">
            非医嘱离院原因：
            <input id="fyzlyyy"
              v-model="patient.fyzlyyy"
              style="width: 530px"
            />
          </div>
          <div>
            是否有出院31天内再住院计划:
            <select
              id="admissAgainInOneMonth"
              v-model="patient.admissAgainInOneMonth"
              @change="onAdmissAgainChanged"
            >
              <option
                v-for="(item, index) in haveOrNot"
                :key="index"
                :value="item.code"
              >
                &nbsp;&nbsp;{{ item.code }}&nbsp;&nbsp;
              </option>
            </select>
            <span v-for="t in haveOrNot">
              {{ t.code }}.{{ t.name }}
            </span>&nbsp;&nbsp;&nbsp;&nbsp;
            目的:
            <input
              id="admissAgainPurpose"
              v-model="patient.admissAgainPurpose"
              style="width: 300px"
            />
          </div>
          <div>
            颅脑损伤患者昏迷时间: 入院前
            <input
              id="comaDaysBeforeAdmiss"
              v-model="patient.comaDaysBeforeAdmiss"
              style="width: 30px"
            />天
            <input
              id="comaHoursBeforeAdmiss"
              v-model="patient.comaHoursBeforeAdmiss"
              style="width: 30px"
            />小时
            <input
              id="comaMinutesBeforeAdmiss"
              v-model="patient.comaMinutesBeforeAdmiss"
              style="width: 30px"
            />分钟 入院后
            <input
              id="comaDaysAfterAdmiss"
              v-model="patient.comaDaysAfterAdmiss"
              style="width: 30px"
            />天
            <input
              id="comaHoursAfterAdmiss"
              v-model="patient.comaHoursAfterAdmiss"
              style="width: 30px"
            />小时
            <input
              id="comaMinutesAfterAdmiss"
              v-model="patient.comaMinutesAfterAdmiss"
              style="width: 30px"
            />分钟
          </div>
          <div>
            住院费用（元）: 总费用
            <input v-model="patient.totalCost" style="width: 110px" readonly />
            (自付金额:
            <input v-model="patient.selfPay" style="width: 110px" readonly />)
          </div>
          <div>
            1.综合医疗服务类: (1)一般医疗服务费:
            <input
              v-model="patient.generalMedicalServiceFee"
              style="width: 70px"
              readonly
            />
            (2)一般治疗操作费:
            <input
              v-model="patient.generalTreatmentOperatingFee"
              style="width: 70px"
              readonly
            />
            (3)护理费:
            <input v-model="patient.careFee" style="width: 50px" readonly />
          </div>
          <div>
            (4)其他费用:
            <input v-model="patient.elseFee" style="width: 70px" readonly />
          </div>
          <div>
            2.诊断类: (5)病理诊断费:
            <input
              v-model="patient.pathologicDiagFee"
              style="width: 70px"
              readonly
            />
            (6)实验室诊断费:
            <input
              v-model="patient.experimentDiagFee"
              style="width: 70px"
              readonly
            />
            (7)影像学诊断费:
            <input v-model="patient.ctDiagFee" style="width: 70px" readonly />
          </div>
          <div>
            (8)临床诊断项目费:
            <input
              v-model="patient.clinicalDiagFee"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            3.治疗类: (9)非手术治疗项目费:
            <input
              v-model="patient.notSurgicalFee"
              style="width: 70px"
              readonly
            />
            (临床物理治疗费:
            <input
              v-model="patient.clinicalPhysicalFee"
              style="width: 70px"
              readonly
            />)
          </div>
          <div>
            (10)手术治疗费:
            <input v-model="patient.surgicalFee" style="width: 70px" readonly />
            (麻醉费:
            <input
              v-model="patient.anesthetizeFee"
              style="width: 70px"
              readonly
            />
            &nbsp;&nbsp;手术费:
            <input v-model="patient.surgeryFee" style="width: 70px" readonly />)
          </div>
          <div>
            4.康复类: (11)康复费:
            <input v-model="patient.recoverFee" style="width: 70px" readonly />
          </div>
          <div>
            5.中医类: (12)中医治疗费:
            <input
              v-model="patient.tcmTreatmentFee"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            6.西药类: (13)西药费:
            <input
              v-model="patient.westMedicineFee"
              style="width: 70px"
              readonly
            />
            （抗菌药物费用：
            <input
                v-model="patient.kjywFee"
                style="width: 70px;padding-left: 5px"
                readonly
            />
            ）
          </div>
          <div>
            7.中药类: (14)中成药费:
            <input
              v-model="patient.chinesePatentMedicineFee"
              style="width: 70px"
              readonly
            />
            (15)中草药费:
            <input
              v-model="patient.chineseHerbalMedicineFee"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            8.血液和血液制品类: (16)血费:
            <input v-model="patient.bloodFee" style="width: 50px" readonly />
            (17)白蛋白类制品费:
            <input
              v-model="patient.albuminProductsFee"
              style="width: 50px"
              readonly
            />
            (18)球蛋白类制品费:
            <input
              v-model="patient.globulinProductsFee"
              style="width: 50px"
              readonly
            />
          </div>
          <div>
            (19)凝血因子类制品费:
            <input
              v-model="patient.coagulationFactorProductsFee"
              style="width: 70px"
              readonly
            />
            (20)细胞因子类制品费:
            <input
              v-model="patient.cytokineProductsFee"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            9.耗材类: (21)检查用一次性医用材料费:
            <input
              v-model="patient.costOfDisposableMedicalMaterialsForExamination"
              style="width: 70px"
              readonly
            />
            (22)治疗用一次性医用材料费:
            <input
              v-model="patient.costOfDisposableMedicalMaterialsForTreatment"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            (23)手术用一次性医用材料费:
            <input
              v-model="patient.costOfDisposableMedicalMaterialsForOperation"
              style="width: 70px"
              readonly
            />
          </div>
          <div>
            10.其他类: (24)其他费:
            <input v-model="patient.otherFees" style="width: 70px" readonly />
          </div>
          <!-- <div>
            主要诊断治愈好转情况:
            <span style="border-bottom: 1px solid black; padding: 0 5px">
              {{ filterDismissStatus(patient.disdiagList[0].dismissStatus) }}
            </span>
          </div> -->
          <div style="display: flex;align-items: end;margin-top: 4px">
            <table style="border-collapse: collapse; width: calc(100% - 25px)">
              <thead>
              <tr>
                <th>重症监护室名称</th>
                <th>进入重症监护室时间（ 年 月 日 时 分）</th>
                <th>转出重症监护室时间（ 年 月 日 时 分）</th>
              </tr>
              </thead>
              <tbody>
              <tr v-for="n in 3">
                <td>
                  <div style="height: 26px;line-height: 26px;padding-left: 5px" @click="clickIcuInfo('icuName',n)">
                    {{ patient.icuInfoList[n - 1].name }}
                  </div>
                </td>
                <td>
                  <div style="height: 26px;line-height: 26px;padding-left: 5px"  class="datetime-container" @click="clickDate(n,1)">
                    {{ patient.icuInfoList[n - 1].startTime }}
                    <el-date-picker
                    :id="`pickerDateE${n}`"
                        v-model="patient.icuInfoList[n - 1].startTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;cursor: pointer;z-index: 10;"
                      ></el-date-picker>
                  </div>
                </td>
                <td>
                  <div style="height: 26px;line-height: 26px;padding-left: 5px"  class="datetime-container" @click="clickDate(n,1)">
                    {{ patient.icuInfoList[n - 1].endTime }}
                    <el-date-picker
                    :id="`pickerDateS${n}`"
                        v-model="patient.icuInfoList[n - 1].endTime"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;cursor: pointer;z-index: 10;"
                      ></el-date-picker>
                  </div>

                  
                  
                </td>
                <el-button
                    v-if="patient.icuInfoList[n - 1].endTime"
                    type="danger"
                    circle
                    icon="Delete"
                    @click="clearLine('icuInfo')"
                  ></el-button>
              </tr>
              
              </tbody>
            </table>
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            危重病例：
            <select v-model="patient.wzbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
            <span style="margin-left: 12px">疑难病例：</span>
            <select v-model="patient.ynbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
            <span style="margin-left: 12px">MDT病历：</span>
            <select v-model="patient.mdtbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            单病种病例：
            <select v-model="patient.dbzbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
            <span style="margin-left: 12px">日间手术病例：</span>
            <select v-model="patient.rjssbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
            <span style="margin-left: 12px">教学查房病历：</span>
            <select v-model="patient.jxcfbl" style="width: 60px">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
            </select>
            0.否&nbsp;1.是&nbsp;&nbsp;&nbsp;
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            诊断符合情况: 1.门诊与住院
            <select
                id="mzycy"
                v-model="patient.mzycy"
                style="margin-right: 12px"
            >
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
              <option value="2">&nbsp;&nbsp;2&nbsp;&nbsp;</option>
              <option value="3">&nbsp;&nbsp;3&nbsp;&nbsp;</option>
            </select>
            2.入院与出院
            <select id="ryycy" v-model="patient.ryycy">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
              <option value="2">&nbsp;&nbsp;2&nbsp;&nbsp;</option>
              <option value="3">&nbsp;&nbsp;3&nbsp;&nbsp;</option>
            </select>
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            3.术前与术后
            <select
                id="sqysh"
                v-model="patient.sqysh"
                style="margin-right: 12px"
            >
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
              <option value="2">&nbsp;&nbsp;2&nbsp;&nbsp;</option>
              <option value="3">&nbsp;&nbsp;3&nbsp;&nbsp;</option>
            </select>
            4.临床与病理
            <select
                id="lcybl"
                v-model="patient.lcybl"
                style="margin-right: 12px"
            >
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
              <option value="2">&nbsp;&nbsp;2&nbsp;&nbsp;</option>
              <option value="3">&nbsp;&nbsp;3&nbsp;&nbsp;</option>
            </select>
            5.放射与病理
            <select id="fsybl" v-model="patient.fsybl">
              <option value="0">&nbsp;&nbsp;0&nbsp;&nbsp;</option>
              <option value="1">&nbsp;&nbsp;1&nbsp;&nbsp;</option>
              <option value="2">&nbsp;&nbsp;2&nbsp;&nbsp;</option>
              <option value="3">&nbsp;&nbsp;3&nbsp;&nbsp;</option>
            </select>
            （0.未做&nbsp;1.符合&nbsp;2.不符合&nbsp;3.不确定&nbsp;）&nbsp;&nbsp;
          </div>
          <div style="display: flex;align-items: end;margin-top: 4px">
            抢救情况: 抢救
            <input
                id="rescueTimes"
                v-model="patient.rescueTimes"
                type="number"
                style="width: 90px;padding-left: 5px"
            />次， 成功
            <input
                id="rescueSuccessTimes"
                v-model="patient.rescueSuccessTimes"
                type="number"
                style="width: 90px;padding-left: 5px"
            />次
          </div>
          <div style="display: flex;align-items: center;margin-top: 6px">
            同城互认：
            1.无
            <el-checkbox true-value="1" false-value="0" v-model="patient.tchrw"></el-checkbox>
            <span style="margin-left: 12px">2.影像检查</span>
            
            <el-checkbox true-value="1" false-value="0" v-model="patient.tchryxjc"></el-checkbox>
            <span style="margin-left: 12px">3.检验检查</span>
            <el-checkbox true-value="1" false-value="0" v-model="patient.tchrjyjc"></el-checkbox>
            <span style="margin-left: 12px">4.病理检查</span>
            <el-checkbox true-value="1" false-value="0" v-model="patient.tchrbljc"></el-checkbox>

            <span style="margin-left: 12px">9.其他</span>
            <el-checkbox true-value="1" false-value="0" v-model="patient.tchrqt"></el-checkbox>
          </div>
          <div style="display: flex;align-items: center;margin-top: 6px">
            临床路径管理
            <select
                id="pathwayMng"
                v-model="patient.pathwayMng"
                style="width: 80px"
            >
              <option value="1">&nbsp;&nbsp;1</option>
              <option value="2">&nbsp;&nbsp;2</option>
              <option value="3">&nbsp;&nbsp;3</option>
              <option value="4">&nbsp;&nbsp;4</option>
            </select>
            1.完成&nbsp;2.变异&nbsp;3.退出&nbsp;4.未入&nbsp;&nbsp;&nbsp;
          </div>
          
          <div style="width: 800px;box-sizing: border-box;">
            <span>说明：（一）医疗付费方式&nbsp;&nbsp;1.城镇职工基本医疗保险&nbsp;&nbsp;2.城镇居民基本医疗保险&nbsp;&nbsp;3.新型农村合作医疗&nbsp;&nbsp;4.贫困救助
              &nbsp;&nbsp;5.商业医疗保险&nbsp;&nbsp;6.全公费&nbsp;&nbsp;7.全自费&nbsp;&nbsp;8.其他社会保险&nbsp;&nbsp;9.其他
            </span>
          </div>
          <div style="width: 800px;box-sizing: border-box;">
            <span>说明：（二）身份证件类型</span>
            <span v-for="item in dics.getPsnCertType">
              {{ item.code }}.{{ item.name }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div id="headpage" style="opacity: 0; position: fixed">
    <HeadPage :patient="headPagePatient" :dics="dics" />
  </div>
  <div id="tailpage" style="opacity: 0; position: fixed">
    <TailPage :patient="tailpagePatient" :dics="dics" />
  </div>

  <el-drawer
    v-model="showMessageDrawer"
    title="首页保存/打印校验结果"
    size="260px"
    modal-class="modal-class"
  >
    <div class="page-inner">
      <div
        v-if="forceVerifies.length === 0 && adviceVerifies.length === 0"
        class="no-verify-message"
      >
        暂无校验内容
      </div>
      <div
        v-show="forceVerifies.length > 0"
        style="padding: 8px 0 4px 0; font-weight: bold"
      >
        以下条目为强制要求，请完善。
      </div>
      <div
        v-for="(item, index) in forceVerifies"
        :key="index"
        class="message-item"
        :style="messageColor(index)"
        @click="handleClickMessage(item.code, index)"
      >
        {{ index + 1 }}、{{ item.name }}
      </div>
      <div
        v-show="adviceVerifies.length > 0"
        style="padding: 8px 0 4px 0; font-weight: bold"
      >
        以下条目为建议执行，不做强制要求。
      </div>
      <div
        v-for="(item, index) in adviceVerifies"
        :key="index"
        style="
          padding: 6px;
          margin-bottom: 6px;
          border-radius: 4px;
          background: #eea7a752;
          color: #ff2b2b;
        "
      >
        {{ index + 1 }}、{{ item.name }}
      </div>
    </div>
  </el-drawer>
  <div class="rightside-btn" @click="showMessageDrawer = !showMessageDrawer">
    首页保存 / 打印校验结果
  </div>

  <el-dialog
    v-model="showSelectDateRange"
    title="出院日期"
    width="320px"
    draggable
  >
    <div style="height: 20px"></div>
    请选择出院日期范围：
    <div style="height: 10px"></div>
    <el-date-picker
      v-model="dateRange"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :shortcuts="shortcuts"
      style="width: 260px"
    ></el-date-picker>
    <div style="margin: 20px 0 10px 0; width: 100%; text-align: right">
      <el-button type="primary" icon="Check" @click="confirmDateRange"
        >确定
      </el-button>
    </div>
  </el-dialog>
  <el-dialog
    v-model="showDateTimePicker"
    title="时间日期选择"
    width="320px"
    draggable
  >
    <div style="height: 20px"></div>
    请选择日期时间：
    <div style="height: 10px"></div>
    <el-date-picker
      v-model="showDateTimePickerData"
      type="datetime"
      style="width: 260px"
    ></el-date-picker>
    <div style="margin: 20px 0 10px 0; width: 100%; text-align: right">
      <el-button type="primary" icon="Check" @click="confirmDateTimePickerData"
        >确定
      </el-button>
    </div>
  </el-dialog>

  <el-dialog
    v-model="showYbDiag"
    title="医保出院诊断"
    width="70%"
    top="30px"
    draggable
  >
    <div
      style="
        width: 100%;
        height: 30px;
        line-height: 30px;
        background: rgb(252, 160, 23);
        margin-bottom: 8px;
        border-radius: 8px;
        padding-left: 8px;
        color: white;
      "
    >
      <strong>主要诊断病种分值：{{ diseFamilyGrade }}</strong>
    </div>
    <el-tag type="info">医保诊断录入</el-tag>
    <el-tag style="margin-left: 12px">患者：{{ patient.name }}</el-tag>
    <el-tag style="margin-left: 8px"
      >医疗类别：{{ patient.medTypeName }}
    </el-tag>
    <el-tag style="margin-left: 8px">险种类型：{{ patient.insutype }}</el-tag>
    <div style="height: 5px"></div>
    <el-input
      v-model="ybDiag.name"
      placeholder="在此搜索诊断"
      readonly
      style="width: 160px"
      @click="showSearchData('ybDiag')"
    ></el-input>
    <el-input
      placeholder="诊断编码"
      disabled
      style="width: 100px"
      v-model="ybDiag.code"
    ></el-input>
    <el-select
      v-model="ybDiag.siDiagType"
      style="width: 100px"
      placeholder="诊断类别"
    >
      <el-option
        v-for="item in diagTypes"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      v-model="ybDiag.admissCond"
      style="width: 100px"
      placeholder="入院病情"
    >
      <el-option
        v-for="item in admissConds"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-select
      v-model="ybDiag.cyzg"
      style="width: 120px"
      placeholder="出院转归"
    >
      <el-option
        v-for="item in cyzgs"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      ></el-option>
    </el-select>
    <el-divider direction="vertical"></el-divider>
    <el-button type="primary" icon="Plus" @click="addToYbDiags">添加</el-button>
    <el-button type="success" icon="Upload" @click="saveYbDiags"
      >保存
    </el-button>
    <el-table :data="ybDiags" stripe :height="200">
      <el-table-column type="index" label="序号" width="45"></el-table-column>
      <el-table-column prop="code" label="诊断编码"></el-table-column>
      <el-table-column prop="name" label="诊断名称"></el-table-column>
      <el-table-column
        prop="siDiagType"
        label="诊断类别"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="admissCond"
        label="入院病情"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="cyzg"
        label="出院转归"
        width="80"
      ></el-table-column>
      <el-table-column
        prop="operId"
        label="录入人"
        width="70"
      ></el-table-column>
      <el-table-column prop="opDate" label="录入日期"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="danger"
            icon="Delete"
            @click="deleteYbDiag(scope.$index)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 12px"></div>
    <el-tag type="info">病案首页诊断信息</el-tag>
    <el-table :data="filterDisDiagList" stripe :height="200">
      <el-table-column type="index" label="序号" width="45"></el-table-column>
      <el-table-column prop="code" label="诊断编码"></el-table-column>
      <el-table-column prop="name" label="诊断名称"></el-table-column>
      <el-table-column label="出院病情">
        <template #default="scope">
          {{ filterDismissStatus(scope.row.dismissStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            icon="Link"
            title="添加到医保诊断"
            circle
            @click="syncronizeWithSiDiagnose(scope.row.code)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <el-dialog v-model="showSearch" title="数据搜索" width="730px" draggable>
    检索依据：
    <el-select v-model="searchMethod" style="width: 100px">
      <el-option
        v-for="item in searchMethods"
        :key="item.code"
        :label="item.name"
        :value="item.code"
      ></el-option>
    </el-select>
    &nbsp;&nbsp;&nbsp;&nbsp; 搜索内容：
    <el-input
      ref="searchInput"
      v-model="searchContent"
      prefix-icon="Search"
      placeholder="请输入搜索内容"
      style="width: 160px"
      clearable
      @input="executeSearch"
    ></el-input>
    <div
      v-if="showSurgeryRecommand"
      style="padding: 12px 0 4px 4px; color: gray"
    >
      根据患者主诊断
      <el-tag
        >{{ patient.disdiagList[0].code }}
        <span style="color: blue">{{ patient.disdiagList[0].name }}</span>
      </el-tag>
      ，推荐以下手术操作：
    </div>
    <el-table
      :data="searchResults"
      height="400"
      stripe
      highlight-current-row
      @row-click="handleSelectSearch"
    >
      <el-table-column prop="code" label="编码" width="130"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column
        v-if="searchUrl === 'employee'"
        prop="deptName"
        label="科室"
      ></el-table-column>
      <el-table-column
        v-if="searchUrl === 'employee'"
        prop="ybCode"
        label="医保赋码"
      ></el-table-column>
      <el-table-column
        v-if="showSurgeryRecommand"
        prop="ssfz"
        label="手术分值"
        width="60"
      ></el-table-column>
    </el-table>
    <div style="margin-top: 15px; width: 100%; text-align: right">
      <el-button
        type="primary"
        icon="ArrowLeft"
        @click="lastPage"
        :disabled="showSurgeryRecommand || currentSRPage === 1"
      >
        上一页
      </el-button>
      <el-button
        type="primary"
        icon="ArrowRight"
        @click="nextPage"
        :disabled="
          showSurgeryRecommand ||
          (currentSRPage > 1 && searchResults.length < 10)
        "
      >
        下一页
      </el-button>
    </div>
  </el-dialog>
  <el-dialog
    v-model="showSurgeryDatetime"
    title="请选择手术时间"
    width="330px"
    draggable
  >
    <div style="height: 12px"></div>
    <el-date-picker
      v-model="surgeryDatetime"
      type="datetime"
      placeholder="手术开始时间"
    ></el-date-picker>
    <div style="height: 12px"></div>
    <el-date-picker
      v-model="opEndDate"
      type="datetime"
      placeholder="手术结束时间"
    ></el-date-picker>
    <div style="margin: 12px 0 8px 0; font-size: 14px; color: red">
      提示：有麻醉（局麻除外）的患者需要填写麻醉时间，否则最终校验无法通过！
    </div>
    <el-date-picker
      v-model="anstStartDate"
      type="datetime"
      placeholder="麻醉开始时间"
    ></el-date-picker>
    <div style="height: 12px"></div>
    <el-date-picker
      v-model="anstEndDate"
      type="datetime"
      placeholder="麻醉结束时间"
    ></el-date-picker>
    <template #footer>
      <div>
        <el-button type="primary" icon="Success" @click="confirmSurgeryDatetime"
          >确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="FillCaseFrontSheet">
import {
  autopsies,
  clone,
  filterDismissStatus,
  haveOrNot,
  initShowDel,
  searchMethods,
  yesOrNo,
  noCertReasons
} from "./common";
import { operations } from "@/data";
import { getLodop, initLodop } from "@/utils/c-lodop";
import {
  doSaveYbDiags,
  executePrintVerify,
  executeSaveVerify,
  fetchAuditCount,
  fetchOutPatients,
  fetchSsfz,
  getAllDictionary,
  getPatientOverview,
  getSheetInfo,
  getSsfzSurgeriesByIcd,
  getUserWards,
  getYbDiags,
  increaseDiagWeight,
  isMedinsSetl,
  selectSiDiagByBaDiag,
  sheetSearch,
  submitQualityVerification,
} from "@/api/case-front-sheet";
import maleIcon from "@/assets/male-icon.png";
import femaleIcon from "@/assets/female-icon.png";
import {ElMessage, ElMessageBox} from "element-plus";
import { shortcuts } from "@/data/shortcuts";
import {
  formatDate,
  formatDatetime,
  getDatetime,
  getOneMonthOffset,
} from "@/utils/date";
import HeadPage from "../../../components/inpatient/frontsheet-printpage/HeadPage.vue";
import TailPage from "../../../components/inpatient/frontsheet-printpage/TailPage.vue";
import router from "@/router/index";
import Sleep from "@/utils/sleep";
import { smoothScrollTableColumn } from "@/utils/el-table-scroll";
import { regions } from "@/data/region";
import { CyMessageBox } from "@/utils/cy-message-box";
import { xcMessage } from "@/utils/xiaochan-element-plus";
import AuditHistory from "@/components/inpatient/frontsheet-printpage/AuditHistory.vue";
import { useUserStore } from "@/pinia/user-store";
import HistorySheetExport from "@/views/hospitalization/case-front-sheet/component/HistorySheetExport.vue";
import { useDialog } from "@/components/cy/CyDialog/index";
import env from "../../../utils/setting";
import {isNumeric} from "@/utils/validate.js";

const userStore = useUserStore();
const userWards = ref([]);
const currentWard = ref("");
const inOutStatus = ref(1);
const inOutOptions = initInOutOptions();
const inpatientNo = ref("");
const onlyShowMyPatients = ref(false);
const overview = ref([]);
const patient = ref({
  disdiagList: [
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
  ],
  surgeryList: [{}, {}, {}, {}, {}],
  icuInfoList: [{}, {}, {}],
  supplement: {},
});
const defaultSurgerySize = ref(5);
const dics = ref({});
const headPagePatient = ref({
  disdiagList: [
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
  ],
  surgeryList: [{}, {}, {}, {}, {}],
  icuInfoList: [{}, {}, {}],
  supplement: {},
});
const tailpagePatient = ref({
  disdiagList: [
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
    {},
  ],
  surgeryList: [{}, {}, {}, {}, {}],
  icuInfoList: [{}, {}, {}],
  supplement: {},
});
const patientTransformData = ref({});
const sexList = ref([1,2,9]);
const showGoSearchBtn1 = ref(false);
const showGoSearchBtn2 = ref(false);
const showDel = initShowDel();
const asideTable = ref(null);
const showDateTimePicker = ref(false);
const showDateTimePickerData = ref(null);

function addSurgeSize() {
  patient.value.surgeryList.push({});
  defaultSurgerySize.value += 1;
}

const cptOverviews = computed(() => {
  return overview.value.filter(item => {
    if (onlyShowMyPatients.value) {
      return item.doctorCode === userStore.userInfo.code;
    }
    return true;
  });
});

const filterDisDiagList = computed(() => {
  return patient.value.disdiagList.filter(item => {
    return item.code && item.name;
  });
});
const clickShowDateTimePickerVisible = (key1,key2,key3) =>{
  console.log("params",)
  patient.value[key1][key2] = showDateTimePickerData
}
const searchPatient = () => {
  if (!inpatientNo.value || inpatientNo.value.trim().length < 1) {
    ElMessage({
      message: "请输入要搜索的住院号",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }

  const patientIndex = overview.value.findIndex(item => {
    return item.bah === inpatientNo.value.trim();
  });
  if (patientIndex === -1) {
    ElMessage({
      message: "未找到住院号【" + inpatientNo.value.trim() + "】的患者信息",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
  } else {
    const currentPatient = overview.value[patientIndex];
    handleClickOverview(currentPatient);
    smoothScrollTableColumn(asideTable.value, patientIndex, currentPatient);
  }
};
const changeDate = () => {
  console.log("changeDate",v  )
};
const clickDate = (v,t) => {

  
  if (t == 1) {
    document.getElementById(`pickerDateS${v}`).focus();
  } else {
    document.getElementById(`pickerDateE${v}`).focus();
  }
};
const handleWardChange = () => {
  if (inOutStatus.value === 1) {
    fetchOverview();
  } else {
    confirmDateRange();
  }
};

const dateRange = ref([]);
const showSelectDateRange = ref(false);
const changeInOutStatus = () => {
  if (inOutStatus.value === 1) {
    fetchOverview();
  } else {
    if (!dateRange.value || dateRange.value.length < 2) {
      const oneMonth = getOneMonthOffset();
      dateRange.value[0] = oneMonth.start;
      dateRange.value[1] = oneMonth.end;
    }
    showSelectDateRange.value = true;
  }
};
const confirmDateRange = () => {
  if (!dateRange.value || dateRange.value.length < 2) {
    ElMessage({
      message: "请选择时间范围",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  const param = {
    ward: currentWard.value,
    start: formatDate(dateRange.value[0]),
    end: formatDate(dateRange.value[1]),
  };
  fetchOutPatients(param).then(res => {
    overview.value = res;
    showSelectDateRange.value = false;
  });
};

const confirmDateTimePickerData = () => {
  showDateTimePicker.value=false
  showDateTimePickerData.value=null
}; 

const clickIcuInfo = (name,n) => {
  if (name == "icuName") {
    patient.value.icuInfoList[n - 1].icuName = "ICU"
  }
};

const fetchOverview = () => {
  getPatientOverview(currentWard.value).then(res => {
    overview.value = res;
  });
};

const currentRow = ref({});

const handleClickOverview = row => {
  currentRow.value = {}
  currentRow.value = row;
  fetchSheetInfo(row);
};

const fetchSheetInfo = row => {
  if (
    row.bah !== patient.value.bah ||
    row.times !== patient.value.admissTimes
  ) {
    forceVerifies.value = [];
    adviceVerifies.value = [];
  }
  row.inOutFlag = inOutStatus.value;
  getSheetInfo(row).then(res => {
    patient.value = res;
    let s = res.surgeryList.length;
    defaultSurgerySize.value = s > 5 ? s : 5;
    patient.value.bedNo = row.bedNo;
    patient.value.sex = row.sex;

    initSheetInfoLine(patient);
    if(patient.value.age == null){
      console.log("initSheetInfoLine0",patient.value.age)
      // patientTransformData.value.age = '-'
    } else {
      patient.value.infAge == null?patientTransformData.value.infAge = '-':false;
      patient.value.ageDays == null?patientTransformData.value.ageDays = '-':false;
      patient.value.newBornWeight1 == null?patientTransformData.value.newBornWeight1 = '-':false;
      patient.value.newBornWeight2 == null?patientTransformData.value.newBornWeight2 = '-':false;
      patient.value.newBornAdmissWeight == null?patientTransformData.value.newBornAdmissWeight = '-':false;
      
    }
    if(patient.value.birthDate != null){
      patientTransformData.value.birthYear = patient.value.birthDate.slice(0,4);
      patientTransformData.value.birthMonth = patient.value.birthDate.slice(5,7);
      patientTransformData.value.birthDay = patient.value.birthDate.slice(8,10);
    } 
    
    patient.value.noCertReason == null?patient.value.noCertReason = "-":false;
    patient.value.noCertReason == null?patient.value.noCertReason = "-":false;
    patient.value.autopsy == null?patient.value.autopsy = "-":false;
    patient.value.transDept == null?patientTransformData.value.transDept = "-":false;
    patient.value.hurtReasonName == null?patientTransformData.value.hurtReasonName = "-":false;
    patient.value.hurtReasonCode == null?patientTransformData.value.hurtReasonCode = "-":false;
    if (patient.value.pathologicDiagCode == null || patient.value.pathologicDiagCode== "-") {
      patientTransformData.value.pathologicDiagStr = "-"
      patientTransformData.value.pathologicDiagCode = "-"
    }
    
    if (patient.value.internshipDoctor == null || patient.value.internshipDoctor== "-") {
      patient.value.internshipDoctor = "-"
      patient.value.internshipDoctorName = "-"
    }
    if (patient.value.studyDoctorName == null || patient.value.studyDoctorName== "-") {
      patient.value.studyDoctorName = "-"
      patient.value.studyDoctorNameName = "-"
    }
    patient.value.blh == null?patientTransformData.value.blh = "-":false;
    patient.value.transDept == null?patientTransformData.value.transDept = "-":false;

    //初始化其他诊断横线
    for (let i = 1; i < patient.value.disdiagList.length; i++) {
      if(patient.value.disdiagList[i].name == '-' || patient.value.disdiagList[i].name == '' || patient.value.disdiagList[i].name == null){
        patient.value.disdiagList[i].name = '-'
        break;
      }
    }
    console.log("patient.value.disdiagList",patient.value.disdiagList)
    //初始化手术横线
    for (let i = 0; i < patient.value.surgeryList.length; i++) {
      if(patient.value.surgeryList[i].name == '-' || patient.value.surgeryList[i].name == null){
        patient.value.surgeryList[i].name = '-'
        break;
      }
    }
    //初始化重症监护室横线
    for (let i = 0; i < patient.value.icuInfoList.length; i++) {
      if(patient.value.icuInfoList[i].name == '-' || patient.value.icuInfoList[i].name == null){
        patient.value.icuInfoList[i].name = '-'
        break;
      }
    }
    
    patient.value.surgeryList[0].name == null?patient.value.surgeryList[0].name = '-':false;

    
    // 为工作单位相关字段设置默认短横线
    if (!patient.value.unitName || patient.value.unitName.trim() === '') {
      patient.value.unitName = '-';
    }
    if (!patient.value.unitPlace || patient.value.unitPlace.trim() === '') {
      patient.value.unitPlace = '-';
    }
    if (!patient.value.unitPhone || patient.value.unitPhone.trim() === '') {
      patient.value.unitPhone = '-';
    }
    if (!patient.value.unitZipCode || patient.value.unitZipCode.trim() === '') {
      patient.value.unitZipCode = '-';
    }

    mergePrintHeadpage()
    // console.log("fdsfds",headPagePatient)
    mergePrintTailpage()
  });
};

const initSheetInfoLine=(data)=>{
  for (const key in data.value) {
    if (Object.prototype.hasOwnProperty.call(data.value, key)) {
      patientTransformData.value[key] = data.value[key]
      
    }
  }
  console.log("initSheetInfoLine",patientTransformData.value)
}

const currentSRPage = ref(1);
const showSearch = ref(false);
const insertDiag = ref(false);
watchEffect(() => {
  if (showSearch.value) {
    searchResults.value = [];
    setTimeout(() => {
      showDel.value = initShowDel();
      searchInput.value.focus();
    }, 300);
  } else {
    insertDiag.value = false;
  }
});
const searchInput = ref(null);
const searchUrl = ref("");
const searchTargetCode = ref("");
const searchTargetName = ref("");
const searchContent = ref("");
const lastPage = () => {
  currentSRPage.value--;
  fetchSearchData();
};
const nextPage = () => {
  currentSRPage.value++;
  fetchSearchData();
};
const fetchSearchData = () => {
  const param = {
    patNo: patient.value.bah,
    times: patient.value.admissTimes,
    method: searchMethod.value,
    target: searchUrl.value,
    content: searchContent.value,
    medType: patient.value.medType,
    page: currentSRPage.value,
  };
  sheetSearch(param).then(res => {
    searchResults.value = res;
  });
};
const executeSearch = () => {
  showSurgeryRecommand.value = false;
  if (
    mainSurgeryFocused.value &&
    searchContent.value === "" &&
    patient.value.disdiagList[0].code
  ) {
    getSsfzSurgeriesByIcd(
      patient.value.bah,
      patient.value.admissTimes,
      patient.value.disdiagList[0].code
    ).then(res => {
      searchResults.value = res;
      showSurgeryRecommand.value = true;
    });
    return;
  }
  if (searchContent.value.length < 2) return;
  currentSRPage.value = 1;
  fetchSearchData();
};

const showYbDiag = ref(false);
const openYbDiag = () => {
  if (nullPatient()) {
    return;
  }
  if (!patient.value.medType) {
    ElMessage({
      message: "自费病人无需填写医保诊断",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  getYbDiags(patient.value.bah, patient.value.admissTimes).then(res => {
    ybDiags.value = res;
    showYbDiag.value = true;
  });
};

const searchMethod = ref("alpha");
const searchResults = ref([]);
const showSearchData = flag => {
  mainSurgeryFocused.value = false;
  showSurgeryRecommand.value = false;
  searchUrl.value = "place";
  if (flag === "birth") {
    searchTargetCode.value = "birthPlace";
    searchTargetName.value = "birthPlaceName";
  } else if (flag === "birthPlace") {
    searchTargetCode.value = "birthPlace";
    searchTargetName.value = "birthPlaceName";
  } else if (flag === "livePlace") {
    searchTargetCode.value = "addrZipCode";
    searchTargetName.value = "livePlace";
  } else if (flag === "native") {
    searchTargetCode.value = "nativePlace";
    searchTargetName.value = "nativePlaceName";
  } else if (flag === "hk") {
    searchTargetCode.value = "hkZipCode";
    searchTargetName.value = "hkPlaceName";
  } else if (flag === "contact") {
    searchTargetCode.value = "contactAddr";
    searchTargetName.value = "contactAddrName";
  } else if (flag === "hurt") {
    searchUrl.value = "hurtReason";
    searchTargetCode.value = "hurtReasonCode";
    searchTargetName.value = "hurtReasonName";
  } else if (flag === "pathologic") {
    searchUrl.value = "pathologicDiag";
    searchTargetCode.value = "pathologicDiagCode";
    searchTargetName.value = "pathologicDiagStr";
  } else if (flag === "deptleader") {
    searchUrl.value = "employee";
    searchTargetCode.value = "deptLeader";
    searchTargetName.value = "deptLeaderName";
  } else if (flag === "leaderdoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "leaderDoctor";
    searchTargetName.value = "leaderDoctorName";
  } else if (flag === "maindoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "mainDoctor";
    searchTargetName.value = "mainDoctorName";
  } else if (flag === "admissdoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "admissDoctor";
    searchTargetName.value = "admissDoctorName";
  } else if (flag === "dutynurse") {
    searchUrl.value = "employee";
    searchTargetCode.value = "dutyNurse";
    searchTargetName.value = "dutyNurseName";
  } else if (flag === "studydoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "studyDoctor";
    searchTargetName.value = "studyDoctorName";
  } else if (flag === "internshipdoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "internshipDoctor";
    searchTargetName.value = "internshipDoctorName";
  } else if (flag === "coder") {
    searchUrl.value = "employee";
    searchTargetCode.value = "coder";
    searchTargetName.value = "coderName";
  } else if (flag === "qualitycontroldoctor") {
    searchUrl.value = "employee";
    searchTargetCode.value = "qualityControlDoctor";
    searchTargetName.value = "qualityControlDoctorName";
  } else if (flag === "qualitycontrolnurse") {
    searchUrl.value = "employee";
    searchTargetCode.value = "qualityControlNurse";
    searchTargetName.value = "qualityControlNurseName";
  } else if (flag === "ybDiag") {
    searchUrl.value = "diag";
    searchTargetCode.value = "ybDiagCode";
  } else if (flag === "clinicdiag") {
    searchUrl.value = "clinicdiag";
    searchTargetCode.value = "clinicDiagCode";
    searchTargetName.value = "clinicDiagStr";
  } else if (flag === "admdiag") {
    searchUrl.value = "clinicdiag";
    searchTargetCode.value = "admDiagCode";
    searchTargetName.value = "admDiagStr";
  }
  showSearch.value = true;
  console.log("handleSelectSearch")
};

const showSurgeryDatetime = ref(false);
const surgeryDatetime = ref(null);
const opEndDate = ref(null);
const anstStartDate = ref(null);
const anstEndDate = ref(null);
const currentSurgeryDatetimeIndex = ref(null);
const showPickSurgeryDatetime = index => {
  currentSurgeryDatetimeIndex.value = index;
  let surgery = patient.value.surgeryList[index];
  surgeryDatetime.value = surgery.date;
  opEndDate.value = surgery.opEndDate;
  anstStartDate.value = surgery.anstStartDate;
  anstEndDate.value = surgery.anstEndDate;
  showSurgeryDatetime.value = true;
};
const confirmSurgeryDatetime = () => {
  if (!surgeryDatetime.value) {
    ElMessage({
      message: "手术开始时间不能为空！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  if (!opEndDate.value) {
    ElMessage({
      message: "手术结束时间不能为空！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  patient.value.surgeryList[currentSurgeryDatetimeIndex.value].date =
    formatDatetime(surgeryDatetime.value);
  patient.value.surgeryList[currentSurgeryDatetimeIndex.value].opEndDate =
    formatDatetime(opEndDate.value);
  patient.value.surgeryList[currentSurgeryDatetimeIndex.value].anstStartDate =
    formatDatetime(anstStartDate.value);
  patient.value.surgeryList[currentSurgeryDatetimeIndex.value].anstEndDate =
    formatDatetime(anstEndDate.value);
  showSurgeryDatetime.value = false;
};

const showSearchSurgerior = (flag, index) => {
  mainSurgeryFocused.value = false;
  showSurgeryRecommand.value = false;
  if (flag === "operator") {
    searchTargetCode.value = "surgeryOperatorCode" + (index - 1);
    searchTargetName.value = "surgeryOperatorName" + (index - 1);
  } else if (flag === "assistantone") {
    searchTargetCode.value = "surgeryAssistantOneCode" + (index - 1);
    searchTargetName.value = "surgeryAssistantOneName" + (index - 1);
  } else if (flag === "assistanttwo") {
    searchTargetCode.value = "surgeryAssistantTwoCode" + (index - 1);
    searchTargetName.value = "surgeryAssistantTwoName" + (index - 1);
  } else {
    searchTargetCode.value = "surgeryAnaesthesiaorCode" + (index - 1);
    searchTargetName.value = "surgeryAnaesthesiaorName" + (index - 1);
  }
  searchUrl.value = "employee";
  showSearch.value = true;
};

const diseFamilyGrade = ref(null);
const ybDiag = reactive({});
const cyzgs = initCyzgs();
const admissConds = initAdmissConds();
const diagTypes = initDiagTypes();
const handleSelectSearch = item => {
  if (searchTargetCode.value.startsWith("surgery")) {
    let offset = defaultSurgerySize.value > 10 ? 2 : 1;
    let no = searchTargetCode.value.substr(
      searchTargetCode.value.length - offset
    );
    if (!isNumeric(no)) {
      offset = 1
      no = searchTargetCode.value.substr(
          searchTargetCode.value.length - offset
      );
    }
    switch (
      searchTargetCode.value.substr(0, searchTargetCode.value.length - offset)
    ) {
      case "surgeryCode":
        if (no > 0) {
          patient.value.surgeryList[no] = clone(
            patient.value.surgeryList[no - 1]
          );
        }
        patient.value.surgeryList[no].no = no;
        patient.value.surgeryList[no].name = item.name;
        patient.value.surgeryList[no].code = item.code;
        patient.value.surgeryList[no].level = item.opScale;
        break;
      case "surgeryOperatorCode":
        patient.value.surgeryList[no].operator = item.code;
        patient.value.surgeryList[no].operatorName = item.name;
        break;
      case "surgeryAssistantOneCode":
        patient.value.surgeryList[no].assistantOne = item.code;
        patient.value.surgeryList[no].assistantOneName = item.name;
        break;
      case "surgeryAssistantTwoCode":
        patient.value.surgeryList[no].assistantTwo = item.code;
        patient.value.surgeryList[no].assistantTwoName = item.name;
        break;
      case "surgeryAnaesthesiaorCode":
        patient.value.surgeryList[no].anaesthesiaor = item.code;
        patient.value.surgeryList[no].anaesthesiaorName = item.name;
        break;
    }
  } else if (searchTargetCode.value.startsWith("disdiags")) {
    let no = Number(searchTargetCode.value.replace("disdiagsCode", ""));
    if (insertDiag.value) {
      for (let i = 26; i > no; i--) {
        patient.value.disdiagList[i] = clone(patient.value.disdiagList[i - 1]);
      }
      patient.value.disdiagList.splice(27);
      insertDiag.value = false;
    }
    patient.value.disdiagList[no].code = item.code;
    patient.value.disdiagList[no].name = item.name;
    patient.value.disdiagList[no].no = no;
    patient.value.disdiagList[no].admissStatus = patient.value.disdiagList[
      no
    ].dismissStatus = "1";
    patient.value.disdiagList[no].opIdCode = userStore.userInfo.code;
    increaseDiagWeight(item.code);
  } else if (searchTargetCode.value === "ybDiagCode") {
    ybDiag.code = item.code;
    ybDiag.name = item.name;
    ybDiag.cyzg = 0;
    ybDiag.siDiagType = 1;
    if (!ybDiags.value || ybDiags.value.length === 0) {
      fetchSsfz(item.code, patient.value.bah, patient.value.admissTimes).then(
        res => {
          diseFamilyGrade.value = res;
        }
      );
    }
  } else if (searchTargetCode.value === "clinicDiagCode") {
    patientTransformData.value.clinicDiagCode = item.code;
    patientTransformData.value.clinicDiagStr = item.name;
  } else if (searchTargetCode.value === "admDiagCode") {
    patientTransformData.value.supplement.admDiagCode = item.code;
    patientTransformData.value.supplement.admDiagName = item.name;
  } else {
    if (needDorSiCode.indexOf(searchTargetCode.value) > -1) {
      if (!item.ybCode.startsWith("D")) {
        ElMessage({
          message: "医师医保编码首字母为D，请重新选择。",
          type: "warning",
          showClose: true,
          duration: 2500,
        });
        return;
      }
    }
    if (searchTargetCode.value === "dutyNurse") {
      if (!item.ybCode.startsWith("N")) {
        ElMessage({
          message: "护士医保编码首字母为N，请重新选择。",
          type: "warning",
          showClose: true,
          duration: 2500,
        });
        return;
      }
    }
    patient.value[searchTargetCode.value] = item.code;
      patient.value[searchTargetName.value] = item.name;
    console.log("searchTargetName",searchTargetCode.value,searchTargetName.value)
    if(searchTargetCode.value == "hurtReasonCode" || searchTargetCode.value == "hurtReasonName" ||
      searchTargetCode.value == "pathologicDiagStr" || searchTargetCode.value == "pathologicDiagCode"
    ){
      patientTransformData.value[searchTargetCode.value] = item.code;
      patientTransformData.value[searchTargetName.value] = item.name;
    } else {
      patient.value[searchTargetCode.value] = item.code;
      patient.value[searchTargetName.value] = item.name;
    }
    if (searchTargetCode.value === "birthPlace") {
      patient.value.nativePlace = item.code;
      patient.value.nativePlaceName = item.name;
    }
  }
  searchContent.value = "";
  showSearch.value = false;
};

const needDorSiCode = [
  "deptLeader",
  "leaderDoctor",
  "mainDoctor",
  "admissDoctor",
];

const syncronizeWithSiDiagnose = code => {
  selectSiDiagByBaDiag(code).then(res => {
    ybDiag.code = res.code;
    ybDiag.name = res.name;
    ybDiag.cyzg = 0;
    ybDiag.siDiagType = 1;
    if (!ybDiags.value || ybDiags.value.length === 0) {
      fetchSsfz(res.code, patient.value.bah, patient.value.admissTimes).then(
        res2 => {
          diseFamilyGrade.value = res2;
        }
      );
    }
  });
};

const clearLine = option => {
  switch (option) {
    case "hurtReason":
      patient.value.hurtReasonName = null;
      patient.value.hurtReasonCode = null;
      patientTransformData.value.hurtReasonName = null;
      patientTransformData.value.hurtReasonCode = null;
      break;
    case "pathologicDiag":
      patient.value.pathologicDiagStr = null;
      patient.value.pathologicDiagCode = null;
      patient.value.blh = null;
      patientTransformData.value.pathologicDiagStr = null;
      patientTransformData.value.pathologicDiagCode = null;
      patientTransformData.value.blh = null;
      break;
    case "icuInfo":
      patient.value.icuInfoList.forEach(item => {
        item.icuName = null
        item.startTime = null
        item.endTime = null
      });
      break;
  }
};

const ybDiags = ref([]);
const addToYbDiags = () => {
  if (!ybDiag.siDiagType) {
    ElMessage({
      message: "请选择诊断类别！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  if (!ybDiag.admissCond) {
    ElMessage({
      message: "请选择入院病情！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  const temp = clone(ybDiag);
  temp.diagType = 13;
  temp.operId = userStore.userInfo.code;
  temp.opDate = getDatetime();
  temp.bzfx = "普通";
  ybDiags.value.push(temp);
  ybDiag.code = ybDiag.name = ybDiag.cyzg = "";
};
const deleteYbDiag = index => {
  ybDiags.value.splice(index, 1);
};
const saveYbDiags = () => {
  const param = {
    bah: patient.value.bah,
    times: patient.value.admissTimes,
    ybDiags: ybDiags.value,
  };
  doSaveYbDiags(param).then(() => {
    ElMessage({
      message: "保存成功",
      type: "success",
      duration: 2500,
      showClose: true,
    });
  });
};

const onSearchDiagFocus = n => {
  mainSurgeryFocused.value = false;
  showSurgeryRecommand.value = false;
  if (n > 0 && !patient.value.disdiagList[n - 1].code) {
    ElMessage({
      message: "请按顺序填写",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  searchUrl.value = "normalDiag";
  searchTargetCode.value = "disdiagsCode" + n;
  searchTargetName.value = "disdiagsName" + n;
  if (!patient.value.disdiagList[n].code) {
    showSearch.value = true;
  } else {
    showDel.value[n] = true;
  }
};

const showSurgeryRecommand = ref(false);
const mainSurgeryFocused = ref(false);
const onSearchSurgeryFocus = n => {
  if (n > 0 && !patient.value.surgeryList[n - 1].code) {
    ElMessage({
      message: "请按顺序填写",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  mainSurgeryFocused.value = false;
  showSurgeryRecommand.value = false;
  searchUrl.value = "surgery";
  searchTargetCode.value = "surgeryCode" + n;
  searchTargetName.value = "surgeryName" + n;
  if (!patient.value.surgeryList[n].code) {
    if (n === 0 && patient.value.disdiagList[0].code) {
      mainSurgeryFocused.value = true;
      getSsfzSurgeriesByIcd(
        patient.value.bah,
        patient.value.admissTimes,
        patient.value.disdiagList[0].code
      ).then(res => {
        searchResults.value = res;
        showSurgeryRecommand.value = true;
      });
    }
    showSearch.value = true;
  } else {
    showDel.value[n] = true;
  }
};

const onEditSurgeryClick = n => {
  showSearch.value = true;
  if (n === 0 && patient.value.disdiagList[0].code) {
    mainSurgeryFocused.value = true;
    getSsfzSurgeriesByIcd(
      patient.value.bah,
      patient.value.admissTimes,
      patient.value.disdiagList[0].code
    ).then(res => {
      searchResults.value = res;
      showSurgeryRecommand.value = true;
    });
  } else {
    mainSurgeryFocused.value = false;
    showSurgeryRecommand.value = false;
  }
};

const hasSurgeryChanged = val => {
  if (val === "0") {
    patient.value.diagConform3 = 0;
  }
};

const deleteDisdiag = index => {
  showDel.value[index] = false;
  while (index < 26) {
    patient.value.disdiagList[index] = patient.value.disdiagList[index + 1];
    index++;
  }
  patient.value.disdiagList[26] = {};
  patient.value.disdiagList.splice(27);
};

const insertDisdiag = index => {
  mainSurgeryFocused.value = false;
  showSurgeryRecommand.value = false;
  insertDiag.value = true;
  searchUrl.value = "normalDiag";
  searchTargetCode.value = "disdiagsCode" + index;
  searchTargetName.value = "disdiagsName" + index;
  showSearch.value = true;
};

function changeSurgeryOrder(currentIndex, newIndex) {
  let temp = patient.value.surgeryList[currentIndex];
  patient.value.surgeryList[currentIndex] = patient.value.surgeryList[newIndex];
  patient.value.surgeryList[newIndex] = temp;
}

const deleteSurgery = index => {
  showDel.value[index] = false;
  while (index < defaultSurgerySize.value - 1) {
    patient.value.surgeryList[index] = patient.value.surgeryList[index + 1];
    index++;
  }
  patient.value.surgeryList[defaultSurgerySize.value - 1] = {};
  patient.value.surgeryList.splice(defaultSurgerySize.value);
  if (defaultSurgerySize.value > 5) {
    defaultSurgerySize.value -= 1;
  }
};

const deleteAssistantOne = index => {
  patient.value.surgeryList[index].assistantOne = "";
  patient.value.surgeryList[index].assistantOneName = "";
};

const deleteAssistantTwo = index => {
  patient.value.surgeryList[index].assistantTwo = "";
  patient.value.surgeryList[index].assistantTwoName = "";
};

const deleteAnestor = index => {
  patient.value.surgeryList[index].anaesthesiaor = "";
  patient.value.surgeryList[index].anaesthesiaorName = "";
};

const nullPatient = () => {
  if (!patient.value.bah) {
    ElMessage({
      message: "请先选择患者！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return true;
  }
  return false;
};

const forceVerifies = ref([]);
const adviceVerifies = ref([]);
const currentMessageIndex = ref(null);
const messageColor = id => {
  return currentMessageIndex.value === id
    ? {
        background: "#ff2b2b",
        color: "white",
      }
    : {
        background: "#eea7a752",
        color: "#ff2b2b",
      };
};
const scrollWrapper = ref(null);
const handleClickMessage = (id, index) => {
  currentMessageIndex.value = index;
  let ele = document.getElementById(id);
  scrollWrapper.value.scrollTop = ele.offsetTop - 260;

  let i = 0;
  let timer = setInterval(() => {
    ele.style.background = i % 2 === 0 ? "rgb(238, 98, 5)" : "transparent";
    i++;
    if (i > 7) {
      clearInterval(timer);
    }
  }, 500);
};

const showMessageDrawer = ref(false);
const setlUplaodClick = () => {
  if (nullPatient()) return;
  isMedinsSetl(patient.value.bah, patient.value.admissTimes).then(() => {
    router.push(
      "/inpatient/casefrntsht/drgCoding/" +
        patient.value.bah +
        "/" +
        patient.value.admissTimes
    );
  });
};

const saveVerifyFillBlank = (data) => {
  patient.value.birthDate = patientTransformData.value.birthYear+'-'+patientTransformData.value.birthMonth+'-'+patientTransformData.value.birthDay
  if(patientTransformData.value.age == null || patientTransformData.value.age == "-" || patientTransformData.value.age == ""){
    // data.age = null
    
  } else {
    patientTransformData.value.infAge == null || patientTransformData.value.infAge == "-"?data.infAge = null:data.infAge = patientTransformData.value.infAge;
    patientTransformData.value.ageDays == null || patientTransformData.value.ageDays == "-"?data.ageDays = null:data.ageDays = patientTransformData.value.ageDays;
    patientTransformData.value.newBornWeight1 == null || patientTransformData.value.newBornWeight1 == "-"?data.newBornWeight1 = null:data.newBornWeight1 = patientTransformData.value.newBornWeight1;
    patientTransformData.value.newBornWeight2 == null || patientTransformData.value.newBornWeight2 == "-"?data.newBornWeight2 = null:data.newBornWeight2 = patientTransformData.value.newBornWeight2;
    patientTransformData.value.newBornAdmissWeight == null || patientTransformData.value.newBornAdmissWeight == "-"?data.newBornAdmissWeight = null:data.newBornAdmissWeight = patientTransformData.value.newBornAdmissWeight;
  }


  data.unitPlace == null && data.unitName == null?data.unitPlace = '-':false;
  patientTransformData.value.transDept == null || patientTransformData.value.transDept == "-"?data.transDept = null:data.transDept = patientTransformData.value.transDept;


  patientTransformData.value.hurtReasonName == null || patientTransformData.value.hurtReasonName == "-"?data.hurtReasonName = '-':data.hurtReasonName = patientTransformData.value.hurtReasonName;
  patientTransformData.value.hurtReasonCode == null || patientTransformData.value.hurtReasonCode == "-"?data.hurtReasonCode = '-':data.hurtReasonCode = patientTransformData.value.hurtReasonCode;
  patientTransformData.value.pathologicDiagStr == null || patientTransformData.value.pathologicDiagStr == "-"?data.pathologicDiagStr = '-':data.pathologicDiagStr = patientTransformData.value.pathologicDiagStr;
  patientTransformData.value.pathologicDiagCode == null || patientTransformData.value.pathologicDiagCode == "-"?data.pathologicDiagCode = '-':data.pathologicDiagCode = patientTransformData.value.pathologicDiagCode;
  patientTransformData.value.blh == null || patientTransformData.value.blh == "-"?data.blh = '-':data.blh = patientTransformData.value.blh;

  data.surgeryList[0].name == '-'?data.surgeryList[0].name = null:false;
  //去除初始化其他诊断横线
    for (let index = 1; index < patient.value.disdiagList.length; index++) {
      if(patient.value.disdiagList[index].name == '-'){
        patient.value.disdiagList[index].name = null
        break;
      }
    }
    //去除初始化手术横线
    for (let index = 0; index < patient.value.surgeryList.length; index++) {
      if(patient.value.surgeryList[index].name == '-'){
        patient.value.surgeryList[index].name = null
        break;
      }
    }
    //去除初始化重症监护室横线
    for (let index = 0; index < patient.value.icuInfoList.length; index++) {
      if(patient.value.icuInfoList[index].name == '-'){
        patient.value.icuInfoList[index].name = null
        break;
      }
    }
  // console.log("patient.value",data.internshipDoctorName)
  // data.internshipDoctorName == null?data.internshipDoctorName = '-':false;
  if(data.internshipDoctor  == null){
    data.internshipDoctor = '-'
    data.internshipDoctorName = '-'
  }
  if(data.studyDoctor  == null){
    data.studyDoctor = '-'
    data.studyDoctorName = '-'
  }

  console.log("data.surgeryList0",patient.value.surgeryList[0].name)
  patient.value.surgeryList[0].name == '-'?patient.value.surgeryList[0].name = null:false;
  console.log("data.surgeryList1",patient.value.surgeryList[0].name)
  
  data.noCertReasonInput == null?data.noCertReasonInput = '-':false;
  data.dismissDestination == null?data.dismissDestination = '-':false;
  data.admissAgainInOneMonth == null?data.admissAgainInOneMonth = '-':false;
  data.admissAgainPurpose == null?data.admissAgainPurpose = '-':false;
  data.comaDaysBeforeAdmiss == null?data.comaDaysBeforeAdmiss = '-':false;
  data.comaHoursBeforeAdmiss == null?data.comaHoursBeforeAdmiss = '-':false;
  data.comaMinutesBeforeAdmiss == null?data.comaMinutesBeforeAdmiss = '-':false;
  data.comaDaysAfterAdmiss == null?data.comaDaysAfterAdmiss = '-':false;
  data.comaHoursAfterAdmiss == null?data.comaHoursAfterAdmiss = '-':false;
  data.comaMinutesAfterAdmiss == null?data.comaMinutesAfterAdmiss = '-':false;
}

const saveVerifyValidate = () => {
  if (patient.value.livePlace) {
    if(patient.value.livePlace.includes("省") && (patient.value.livePlace.includes("市") || patient.value.livePlace.includes("县"))){
      return true
    } else {
      xcMessage.error("患者现住址请完整填写行政地区！");
      return false
    }
  } else {
    xcMessage.error("患者现住址请完整填写行政地区！");
    return false
  }


}


const saveVerify = opType => {
  if (!saveVerifyValidate(patient.value)) {
    return
  }
  // saveVerifyFillFromTransformData(patientTransformData.value)
  saveVerifyFillBlank(patient.value)
  console.log("patient.value",patient.value)
  if (nullPatient()) return;
  fetchAuditCount({
    patNo: patient.value.bah,
    times: patient.value.admissTimes,
  }).then(res => {
    if (res.approved > 0) {
      xcMessage.error("此患者病案首页质控审核已通过，无法保存。");
      return;
    }
    executeSaveVerify({
      opType,
      sheet: patient.value,
    })
      .then(() => {
        ElMessage({
          message: "操作成功。",
          type: "success",
          duration: 2500,
          showClose: true,
        });
        handleClickOverview(currentRow.value)
      })
      .catch(e => {
        forceVerifies.value = e.data;
        showMessageDrawer.value = true;
      });
  });
};

function sheetQualityVerification(command) {
  if (command === "applyVerification") {
    beforeSubmitAudit();
  } else {
    useDialog(AuditHistory, {
      dialogProps: { title: "质控记录" },
      showFooter: false,
      params: {
        patinfo: {
          patNo: patient.value.bah,
          times: patient.value.admissTimes,
        },
      },
    });
  }
}

function beforeSubmitAudit() {
  if (nullPatient()) {
    return;
  }
  fetchAuditCount({
    patNo: patient.value.bah,
    times: patient.value.admissTimes,
  }).then(res => {
    if (res.approved > 0) {
      xcMessage.error("此患者的质控审核已通过，无需再次申请。");
      return;
    }
    if (res.initial > 0) {
      xcMessage.error("此患者有未被处理的质控审核，请勿重复提交。");
      return;
    }
    executePrintVerify({
      sheet: patient.value,
    })
      .then(() => {
        submitAuditConfirm();
      })
      .catch(e => {
        forceVerifies.value = e.data.force;
        adviceVerifies.value = e.data.advice;
        showMessageDrawer.value = true;
        if (e.data.force.length === 0) {
          submitAuditConfirm();
        }
      });
  });
}

function submitAuditConfirm() {
  CyMessageBox.confirm({
    type: "warning",
    title: "提示",
    message: `质控审核通过后，病案将进入锁定状态，无法再次修改。确定要提交质控审核吗？`,
  })
    .then(() => {
      executeSubmitAudit();
    })
    .catch(() => {});
}

function executeSubmitAudit() {
  const params = {
    patNo: patient.value.bah,
    times: patient.value.admissTimes,
    patName: patient.value.name,
    patGender: filterPatGender(),
    disDeptCode: patient.value.dismissDeptCode,
    disDeptName: patient.value.dismissDept,
  };
  submitQualityVerification(params).then(() => {
    xcMessage.success("提交成功");
    if (inOutStatus === 2) {
      CyMessageBox.confirm({
        type: "warning",
        title: "提示",
        message: "是否申请医保结算清单质控？",
      }).then(() => {
        setlUplaodClick();
      });
    }
  });
}

function filterPatGender() {
  if (patient.value.sex === 1 || patient.value.sex === "1") {
    return "MALE";
  }
  if (patient.value.sex === 2 || patient.value.sex === "2") {
    return "FEMALE";
  }
  return "UNKNOWN";
}

const dismissShowSearch = flag => {
  setTimeout(() => {
    if (flag === 1) {
      showGoSearchBtn1.value = false;
    } else {
      showGoSearchBtn2.value = false;
    }
  }, 100);
};

const mergePrintHeadpage = () => {
  headPagePatient.value = {
    disdiagList: [],
    surgeryList: [{}, {}, {}, {}, {}],
    icuInfoList: [{}, {}, {}],
    supplement: {}
  }
  for (const key in patient.value) {
    if (Object.prototype.hasOwnProperty.call(patient.value, key)) {
      headPagePatient.value[key] = patient.value[key];
    }
  }
  for (const key in patientTransformData.value) {
    if (Object.prototype.hasOwnProperty.call(patientTransformData.value, key)) {
      if (patientTransformData.value[key]) {
        headPagePatient.value[key] = patientTransformData.value[key];
      }
    }
  }
  console.log("headPagePatient.value",headPagePatient.value)
};
const mergePrintTailpage = () => {
  tailpagePatient.value = {
    disdiagList: [],
    surgeryList: [{}, {}, {}, {}, {}],
    icuInfoList: [{}, {}, {}],
    supplement: {}
  }
  for (const key in patient.value) {
    if (Object.prototype.hasOwnProperty.call(patient.value, key)) {
      tailpagePatient.value[key] = patient.value[key];
    }
  }
  for (const key in patientTransformData.value) {
    if (Object.prototype.hasOwnProperty.call(patientTransformData.value, key)) {
      if (patientTransformData.value[key]) {
        tailpagePatient.value[key] = patientTransformData.value[key];
      }
    }
  }
};

const beforePrint = page => {
  
  if (nullPatient()) return;
  fetchAuditCount({
    patNo: patient.value.bah,
    times: patient.value.admissTimes,
  }).then(res => {
    execPrint(page)
    // if (res.approved > 0) {
    //   execPrint(page);
    // } else {
    //   ElMessageBox.confirm('病案首页质控审核未通过，是否继续打印？', '提示', {
    //     type: "warning",
    //   }).then(() => {
    //     execPrint(page)
    //   }).catch(() => {})
    // }
  });
};

const execPrint = page => {
  
  const LODOP = getLodop();
  const prntStyle = `<style>*{font-size:10pt} table,th,td {border: 1px solid black;border-collapse: collapse;} td,th {height: 24px;padding-left: 4px;}</style>`;
  let prntContent;
  if(page === 1){
    mergePrintHeadpage()
    prntContent = document.getElementById("headpage").innerHTML
  } else {
    mergePrintTailpage()
    prntContent = document.getElementById("tailpage").innerHTML
  }
  // const prntContent =
  //   page === 1
  //     ? document.getElementById("headpage").innerHTML
  //     : document.getElementById("tailpage").innerHTML;
  let pagePrint = prntStyle + "<body>" + prntContent + "</body>";
  LODOP.PRINT_INIT("casefrontsheet");
  LODOP.SET_PRINT_PAGESIZE(1, "210mm", "297mm", "");
  LODOP.SET_PRINT_MODE("FULL_WIDTH_FOR_OVERFLOW", true); // 整宽不变形
  LODOP.ADD_PRINT_HTM("2mm", "5mm", "100%", "100%", pagePrint);
  LODOP.SET_PRINT_STYLE("ItemType", 3);
  LODOP.PREVIEW();
};

onActivated(async () => {
  const params = router.currentRoute.value.query;
  if (params && params.patNo && params.deptCode) {
    await Sleep(300);
    if (params.times && params.disdate) {
      dateRange.value[0] = params.disdate;
      dateRange.value[1] = params.disdate;
      inOutStatus.value = 2;
    } else {
      inOutStatus.value = 1;
    }
    inpatientNo.value = params.patNo;
    currentWard.value = params.deptCode;
    handleWardChange();
    await Sleep(500);
    searchPatient();
  }
});

function showExportPanel() {
  useDialog(HistorySheetExport, {
    dialogProps: {
      title: "历史病案导出",
      width: "600px",
    },
    confirmText: "导出",
  });
}

onMounted(() => {
  scrollWrapper.value = document.getElementById("scrollWrapper");
  initLodop();
  getAllDictionary().then(res => {
    res.getOperations = operations;
    res.getYesOrNo = yesOrNo;
    res.getHaveOrNot = haveOrNot;
    res.getAutopsies = autopsies;
    res.noCertReasons = noCertReasons;
    dics.value = res;
  });
  getUserWards().then(res => {
    userWards.value = res;
    if (res.length > 0) {
      currentWard.value = res[0].code;
      fetchOverview();
    }
  });
});

function initInOutOptions() {
  return [
    { code: 1, name: "在院" },
    { code: 2, name: "出院" },
  ];
}

function initCyzgs() {
  return [
    { code: 0, name: "好转/治愈" },
    { code: 1, name: "未愈" },
    { code: 2, name: "转院（医院要求）" },
    { code: 3, name: "转院（病人要求）" },
    { code: 4, name: "转科" },
    { code: 5, name: "无效" },
    { code: 6, name: "死亡" },
    { code: 7, name: "双向转诊" },
    { code: 9, name: "其他" },
  ];
}

function initAdmissConds() {
  return [
    { code: 1, name: "有" },
    { code: 2, name: "临床未确定" },
    { code: 3, name: "情况不明" },
    { code: 4, name: "无" },
  ];
}

function initDiagTypes() {
  return [
    { code: 1, name: "西医诊断" },
    { code: 2, name: "中医主病诊断" },
    { code: 3, name: "中医主症诊断" },
  ];
}
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding-top: 8px;
}

:deep(.el-drawer) {
  border: 1px solid orange;
}

:deep(.el-drawer .el-icon) {
  font-size: 20px;
  color: orangered;
}

:deep(.el-drawer__header) {
  margin-bottom: 8px;
}

:deep(.el-dialog__header) {
  padding-bottom: 4px;
}

:deep(.el-checkbox__label) {
  padding-left: 2px;
}

:deep(.el-checkbox ) {
  margin-right: 0;
}

select,
input {
  outline: none;
  border: none;
  height: 20px;
  line-height: 20px;
  border-radius: 0;
  background: transparent;
  border-bottom: 1px solid #333333;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}



input[type="number"] {
  -moz-appearance: textfield;
}

select ::-ms-expand {
  display: none;
}

textarea {
  outline: none;
  border: none;
  background-color: transparent;
}

table th {
  border: 1px solid black;
  text-align: center;
}

table td {
  border: 1px solid black;
}

.page-inner {
  padding: 0 20px 10px 26px;
  border-radius: 12px;
  text-align: justify;
}

.message-item {
  padding: 6px;
  margin-bottom: 6px;
  border-radius: 4px;
}

.message-item:hover {
  cursor: pointer;
}

.rightside-btn {
  display: flex;
  align-items: center;
  text-align: center;
  color: white;
  border-radius: 4px;
  width: 20px;
  height: 185px;
  position: fixed;
  background: rgb(238, 98, 5);
  top: 260px;
  right: 10px;
  cursor: pointer;
}

.no-verify-message {
  width: 100%;
  text-align: center;
  margin-top: 50px;
  font-size: 18px;
  color: gray;
}

:deep(.m-drawer .el-overlay) {
  right: 0;
  left: calc(100vw - 260px);
  background: transparent !important;
}

:deep(#livePlace .el-input__wrapper) {
  background: transparent;
  border: none;
  box-shadow: none;
  border-radius: 0;
  border-bottom: 1px solid black;
  color: black;
}

:deep(#livePlace .el-input__inner) {
  color: black;
}

.audit-state {
  font-weight: bold;
  font-size: 16px;
}

.audit-state_approved {
  color: green;
}

.audit-state_rejected {
  color: red;
  text-decoration: underline;
  cursor: pointer;
}

.audit-state_initial {
  color: #777777;
}

.audit-state_none {
  color: #e8b600;
}

.order-arrow {
  font-size: 16px;
  cursor: pointer;
}

.order-arrow:hover {
  color: #0a84fd;
}
.hidden-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0; 
  cursor: pointer;
  z-index: 10; /* 确保在按钮上方 */
}
.datetime-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: inline-block;
}
</style>
