<template>
  <page-layer>
    <template #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" @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="Date" 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">搜索患者</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-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>
    </template>
    <template #aside>
      <el-table ref="asideTable" :data="overview" :height="tableHeight" stripe highlight-current-row @row-click="fetchSheetInfo">
        <el-table-column prop="bedNo" label="床" width="30"></el-table-column>
        <el-table-column label="姓名" width="70">
          <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="80">
          <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="45"></el-table-column>
      </el-table>
    </template>
    <template #main>
      <div style="display: flex">
        <div :style="mainInfo" id="scrollWrapper">
          <div id="page0">
            <h3 style="width: 100%; font-size: 17px; text-align: center">住 院 病 案 首 页</h3>
            <div style="width: 100%; height: 32px; line-height: 32px; font-size: 15px; text-align: center">
              医疗机构: <span style="font-weight: 700">长沙泰和医院</span> （组织机构代码: <span style="font-weight: 700">43010150145</span>）
            </div>
            <div style="height: 25px; line-height: 25px; display: flex">
              <div>
                医疗付费方式:
                <select v-model="patient.payMethod" style="width: 180px">
                  <option v-for="(item, index) in dics.getPayMethod" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&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>
              姓名: <input id="name" v-model="patient.name" style="width: 70px" />
              性别:
              <select id="sex" v-model="patient.sex">
                <option v-for="(item, index) in dics.getSexCode" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              出生日期: <input id="birthDate" v-model="patient.birthDate" style="width: 130px" /> 年龄:
              <input id="age" v-model="patient.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>
            </div>
            <div>
              （年龄不足 1 周岁的）年龄:
              <input id="ageDays" type="number" v-model="patient.ageDays" style="width: 50px" />天 新生儿出生体重:
              <input id="newBornWeight" type="number" v-model="patient.newBornWeight" style="width: 70px" />克 新生儿入院体重:
              <input id="newBornAdmissWeight" type="number" v-model="patient.newBornAdmissWeight" style="width: 70px" />克
            </div>
            <div>
              出生地:
              <input id="birthPlaceName" v-model="patient.birthPlaceName" style="width: 230px" @click="showSearchData('birth')" />
              籍贯:
              <input id="nativePlaceName" v-model="patient.nativePlaceName" 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>
              身份证号:
              <input id="socialNo" v-model="patient.socialNo" style="width: 160px" maxlength="18" />
              职业:
              <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.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div id="livePlace">
              现住址:
              <span id="livePlace1">
                  <el-cascader v-model="patient.standardAddress" :options="regions" placeholder="省/市/区" style="width:230px"></el-cascader>
                </span>
              <input id="livePlace2" v-model="patient.livePlace" style="width: 300px" placeholder="街道/小区/乡镇" />
            </div>
            <div>
              电话:
              <input id="phone" v-model="patient.phone" style="width: 90px" />
              邮编:
              <input id="addrZipCode" v-model="patient.addrZipCode" style="width: 70px" maxlength="6" />
            </div>
            <div>
              户口地址:
              <input id="hkPlaceName" v-model="patient.hkPlaceName" style="width: 300px" @click="showGoSearchBtn1 = true" @blur="dismissShowSearch(1)" />
              <el-button icon="Search" type="primary" v-show="showGoSearchBtn1" @click="showSearchData('hk')"> 前往搜索 </el-button>
              邮编:
              <input id="hkZipCode" v-model="patient.hkZipCode" style="width: 70px" maxlength="6" />
            </div>
            <div>
              工作单位及地址:
              <input id="unitName" v-model="patient.unitName" style="margin-right: 0; width: 145px" />
              /<input id="unitPlace" v-model="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" maxlength="6" />
            </div>
            <div>
              联系人姓名: <input id="contactName" v-model="patient.contactName" style="width: 90px" />
              联系人关系:
              <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: 300px" @click="showGoSearchBtn2 = true" @blur="dismissShowSearch(2)" />
              <el-button icon="Search" type="primary" v-show="showGoSearchBtn2" @click="showSearchData('contact')">前往搜索 </el-button>
              联系人电话: <input id="contactPhone" v-model="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.name }}&nbsp;&nbsp;</option>
              </select>
              是否手术:
              <select id="hasSurgery" v-model="patient.hasSurgery" @change="hasSurgeryChanged(patient.hasSurgery)">
                <option v-for="itm in operations" :key="itm.code" :value="itm.code">{{ itm.name }}</option>
              </select>
            </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="patient.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">
              门（急）诊诊断:
              <input v-model="patient.clinicDiagStr" readonly style="width: 350px" @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">
              <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]" class="not-print" 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]" class="not-print" 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]" class="not-print" 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="patient.hurtReasonName" style="width: 300px" @click="showSearchData('hurt')" />
              疾病编码:
              <input id="hurtReasonCode" v-model="patient.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="patient.pathologicDiagStr" style="width: 300px" @click="showSearchData('pathologic')" />
              病理编码:
              <input id="pathologicDiagCode" v-model="patient.pathologicDiagCode" style="width: 90px" readonly />
              病理号: <input id="blh" v-model="patient.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.name }}&nbsp;&nbsp;</option>
              </select>
              ，过敏药物:
              <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.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              输血前四项: HbsAg
              <select id="hbsAg" v-model="patient.hbsAg">
                <option v-for="(item, index) in dics.getHbsag" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              HCV-Ab
              <select id="hcvAb" v-model="patient.hcvAb" style="margin-left: 8px">
                <option v-for="(item, index) in dics.getHbsag" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              HIV-Ab
              <select id="hivAb" v-model="patient.hivAb" style="margin-left: 8px">
                <option v-for="(item, index) in dics.getHbsag" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              TP-Ab
              <select id="tpAb" v-model="patient.tpAb" style="margin-left: 8px">
                <option v-for="(item, index) in dics.getHbsag" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </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.name }}&nbsp;&nbsp;</option>
              </select>
              Rh:
              <select id="rh" v-model="patient.rh">
                <option v-for="(item, index) in dics.getHbsag" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              科室主任:
              <input id="deptLeaderName" style="width: 70px" v-model="patient.deptLeaderName" @click="showSearchData('deptleader')" />
              主任(副主任)医师:
              <input id="leaderDoctorName" style="width: 70px" v-model="patient.leaderDoctorName" @click="showSearchData('leaderdoctor')" />
              主治医师:
              <input id="mainDoctorName" style="width: 70px" v-model="patient.mainDoctorName" @click="showSearchData('maindoctor')" />
              住院医师:
              <input id="admissDoctorName" style="width: 70px" v-model="patient.admissDoctorName" @click="showSearchData('admissdoctor')" />
            </div>
            <div>
              责任护士:
              <input id="dutyNurseName" style="width: 70px" v-model="patient.dutyNurseName" @click="showSearchData('dutynurse')" />
              进修医师:
              <input id="studyDoctorName" style="width: 70px" v-model="patient.studyDoctorName" @click="showSearchData('studydoctor')" />
              实习医师:
              <input id="internshipDoctorName" style="width: 70px" v-model="patient.internshipDoctorName" @click="showSearchData('internshipdoctor')" />
              编码员:
              <input 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.name }}&nbsp;&nbsp;</option>
              </select>
              质控医师:
              <input id="qualityControlDoctorName" style="width: 70px" v-model="patient.qualityControlDoctorName" @click="showSearchData('qualitycontroldoctor')" />
              质控护士:
              <input style="width: 70px" 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: 1px solid black; border-collapse: collapse; width: 100%">
              <tr>
                <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 5" :key="n">
                <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]" class="not-print" 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 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>
                  <input v-model="patient.surgeryList[n - 1].code" style="border: none !important; width: 70px" readonly />
                </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">
                  <input style="border: none !important; width: 40px" v-model="patient.surgeryList[n - 1].assistantOneName" @click="showSearchSurgerior('assistantone', n)" />
                </td>
                <td style="width: 50px">
                  <input style="border: none !important; width: 40px" v-model="patient.surgeryList[n - 1].assistantTwoName" @click="showSearchSurgerior('assistanttwo', n)" />
                </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>
                  <input style="border: none !important; width: 40px" v-model="patient.surgeryList[n - 1].anaesthesiaorName" @click="showSearchSurgerior('anaesthesiaor', n)" />
                </td>
              </tr>
            </table>
            <div>
              离院方式:
              <select id="zyDismissWay" v-model="patient.zyDismissWay" @change="onDismissWayChanged">
                <option v-for="(item, index) in dics.getZyDismissWay" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              ，拟接收医疗机构名称:
              <input id="dismissDestination" v-model="patient.dismissDestination" style="width: 210px" />
            </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.name }}&nbsp;&nbsp;</option>
              </select>
              ，目的:
              <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
                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 />
            </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>
              诊断符合情况: 门诊与出院
              <select id="diagConform1" v-model="patient.diagConform1" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getDiagConform" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              入院与出院
              <select id="diagConform2" v-model="patient.diagConform2">
                <option v-for="(item, index) in dics.getDiagConform" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              术前与术后
              <select id="diagConform3" v-model="patient.diagConform3" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getDiagConform" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              临床与病理
              <select id="diagConform4" v-model="patient.diagConform4" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getDiagConform" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              放射与病理
              <select id="diagConform5" v-model="patient.diagConform5">
                <option v-for="(item, index) in dics.getDiagConform" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              抢救情况: 抢救
              <input id="rescueTimes" v-model="patient.rescueTimes" type="number" style="width: 90px" />次， 成功
              <input id="rescueSuccessTimes" v-model="patient.rescueSuccessTimes" type="number" style="width: 90px" />次
            </div>
            <div>
              病例分型:
              <select id="caseClassification" v-model="patient.caseClassification" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getCaseClassification" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              实施重症监护:
              <select id="hasIcu" v-model="patient.hasIcu" @change="handleSelectIcu">
                <option v-for="(item, index) in haveOrNot" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              ，监护总时间:
              <input id="icuDays" v-model="patient.icuDays" style="width: 30px" />天 <input id="icuHours" v-model="patient.icuHours" style="width: 30px" />小时
            </div>
            <div>
              单病种管理:
              <select id="monopathyManagement" v-model="patient.monopathyManagement" style="margin-right: 12px">
                <option v-for="(item, index) in yesOrNo" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              实施临床路径管理:
              <select id="clinicalPathwayManagement" v-model="patient.clinicalPathwayManagement" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getClinicalPathwayManagement" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              实施DRGs管理:
              <select id="drgsManagement" v-model="patient.drgsManagement">
                <option v-for="(item, index) in dics.getDrgsManagement" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              抗生素使用:
              <select id="useAntibiotic" v-model="patient.useAntibiotic" style="margin-right: 12px">
                <option v-for="(item, index) in yesOrNo" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              细菌培养标本送检:
              <select id="bacilliculture" v-model="patient.bacilliculture" style="margin-right: 12px">
                <option value="1">&nbsp;&nbsp;是&nbsp;&nbsp;</option>
                <option value="2">&nbsp;&nbsp;否&nbsp;&nbsp;</option>
              </select>
              法定传染病:
              <select id="statutoryEpidemic" v-model="patient.statutoryEpidemic">
                <option v-for="(item, index) in dics.getStatutoryEpidemic" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
            </div>
            <div>
              肿瘤分期: T
              <select id="tumorLevelT" v-model="patient.tumorLevelT" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getTumorLevelT" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              N
              <select id="tumorLevelN" v-model="patient.tumorLevelN" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getTumorLevelN" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              M
              <select id="tumorLevelM" v-model="patient.tumorLevelM" style="margin-right: 12px">
                <option v-for="(item, index) in dics.getTumorLevelM" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              分期
              <select id="tumorLevel" v-model="patient.tumorLevel" style="margin-right: 18px">
                <option v-for="(item, index) in dics.getTumorLevel" :key="index" :value="item.code">&nbsp;&nbsp;{{ item.name }}&nbsp;&nbsp;</option>
              </select>
              新生儿Apgar评分: <input style="margin-right: 0; width: 50px" v-model="patient.xxeApgar" />分
            </div>
          </div>
        </div>

        <span class="m-drawer">
            <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>
          </span>
        <div class="rightside-btn" @click="showMessageDrawer = !showMessageDrawer">首页保存 / 打印校验结果</div>
      </div>
      <div id="headpage" style="opacity: 0; position: fixed">
        <HeadPage :patient="patient" :dics="dics" />
      </div>
      <div id="tailpage" style="opacity: 0; position: fixed">
        <TailPage :patient="patient" :dics="dics" />
      </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="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 placeholder="在此搜索诊断" style="width: 160px" v-model="ybDiag.name" @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>
  </page-layer>
</template>

<script setup name="FillCaseFrontSheet">
import { yesOrNo, haveOrNot, searchMethods, autopsies, initShowDel, filterDismissStatus, clone } from './common'
import store from '@/store'
import { operations } from '@/data'
import { initLodop, getLodop } from '@/utils/c-lodop'
import {
  doSaveYbDiags,
  executePrintVerify,
  executeSaveVerify,
  fetchOutPatients,
  fetchSsfz,
  getAllDictionary,
  getPatientOverview,
  getSheetInfo,
  getUserWards,
  getYbDiags,
  sheetSearch,
  getSsfzSurgeriesByIcd,
  increaseDiagWeight,
  selectSiDiagByBaDiag,
  frontsheetQualityCheck,
  isMedinsSetl,
} from '@/api/case-front-sheet'
import maleIcon from '@/assets/male-icon.png'
import femaleIcon from '@/assets/female-icon.png'
import { ElMessage, ElNotification } 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 PageLayer from "@/layout/PageLayer";

const userWards = ref([])
const currentWard = ref('')
const inOutStatus = ref(1)
const inOutOptions = initInOutOptions()
const inpatientNo = ref('')
const windowSize = store.state.app.windowSize
const tableHeight = windowSize.h - 45
const overview = ref([])
const patient = ref({
  disdiagList: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}],
  surgeryList: [{}, {}, {}, {}, {}],
})
const mainInfo = {
  height: windowSize.h - 45 + 'px',
  width: '753px',
  overflowX: 'hidden',
  padding: '0 20px',
  overflowY: 'scroll',
}
const dics = ref({})
const showGoSearchBtn1 = ref(false)
const showGoSearchBtn2 = ref(false)
const showDel = initShowDel()
const asideTable = ref(null)

const filterDisDiagList = computed(() => {
  return patient.value.disdiagList.filter(item => {
    return item.code && item.name
  })
})

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]
    fetchSheetInfo(currentPatient)
    smoothScrollTableColumn(asideTable.value, patientIndex, currentPatient)
  }
}

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 fetchOverview = () => {
  getPatientOverview(currentWard.value).then((res) => {
    overview.value = res
  })
}

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
    patient.value.bedNo = row.bedNo
    patient.value.sex = row.sex
    beforePrintSet.value = false
  })
}

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 = false
  if (mainSurgeryFocused && 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 = 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 = false
  showSurgeryRecommand = false
  searchUrl.value = 'place'
  if (flag === 'birth') {
    searchTargetCode.value = 'birthPlace'
    searchTargetName.value = 'birthPlaceName'
  } else if (flag === 'native') {
    searchTargetCode.value = 'nativePlace'
    searchTargetName.value = 'nativePlaceName'
  } else if (flag === 'hk') {
    searchTargetCode.value = 'hkPlace'
    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'
  }
  showSearch.value = true
}

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 = false
  showSurgeryRecommand = 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 no = searchTargetCode.value.charAt(searchTargetCode.value.length - 1)
    switch (searchTargetCode.value.substr(0, searchTargetCode.value.length - 1)) {
      case 'surgeryCode':
        if (no > 0 && no < 5) {
          patient.value.surgeryList[no] = clone(patient.value.surgeryList[no - 1])
        }
        patient.value.surgeryList[no].name = item.name
        patient.value.surgeryList[no].code = item.code
        patient.value.surgeryList[no].no = no
        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 = store.state.user.info.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') {
    patient.value.clinicDiagCode = item.code
    patient.value.clinicDiagStr = 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
    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
      break;
    case 'pathologicDiag':
      patient.value.pathologicDiagStr = null
      patient.value.pathologicDiagCode = null
      patient.value.blh = 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 = store.state.user.info.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 = false
  showSurgeryRecommand = 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
  }
}

let showSurgeryRecommand = $ref(false)
let 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 = false
  showSurgeryRecommand = 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 = true
      getSsfzSurgeriesByIcd(patient.value.bah, patient.value.admissTimes, patient.value.disdiagList[0].code).then((res) => {
        searchResults.value = res
        showSurgeryRecommand = true
      })
    }
    showSearch.value = true
  } else {
    showDel.value[n] = true
  }
}

const onEditSurgeryClick = (n) => {
  showSearch.value = true
  if (n === 0 && patient.value.disdiagList[0].code) {
    mainSurgeryFocused = true
    getSsfzSurgeriesByIcd(patient.value.bah, patient.value.admissTimes, patient.value.disdiagList[0].code).then((res) => {
      searchResults.value = res
      showSurgeryRecommand = true
    })
  } else {
    mainSurgeryFocused = false
    showSurgeryRecommand = 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 = false
  showSurgeryRecommand = false
  insertDiag.value = true
  searchUrl.value = 'normalDiag'
  searchTargetCode.value = 'disdiagsCode' + index
  searchTargetName.value = 'disdiagsName' + index
  showSearch.value = true
}

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

const beforePrintSet = ref(false)
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',
      }
}
let scrollWrapper = $ref(null)
const handleClickMessage = (id, index) => {
  currentMessageIndex.value = index
  let ele = document.getElementById(id)
  scrollWrapper.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)
}

let showMessageDrawer = $ref(false)
const setlUplaodClick = () => {
  if (nullPatient()) return
  isMedinsSetl(patient.value.bah, patient.value.admissTimes).then(() => {
    router.push({
      name: 'SetSheetUpload',
      query: {
        patNo: patient.value.bah,
        times: patient.value.admissTimes,
      }
    })
  })
}

const saveVerify = (opType) => {
  if (nullPatient()) return
  beforePrintSet.value = false
  const param = {
    opType,
    sheet: patient.value,
  }
  executeSaveVerify(param)
    .then(() => {
      ElMessage({
        message: '操作成功。',
        type: 'success',
        duration: 2500,
        showClose: true,
      })
    })
    .catch((e) => {
      forceVerifies.value = e.data
      showMessageDrawer = true
    })
}
const dismissShowSearch = (flag) => {
  setTimeout(() => {
    if (flag === 1) {
      showGoSearchBtn1.value = false
    } else {
      showGoSearchBtn2.value = false
    }
  }, 100)
}
const beforePrint = (page) => {
  if (nullPatient()) return
  const param = {
    opType: 4,
    sheet: patient.value,
    page: page
  }
  executePrintVerify(param)
    .then(() => {
      execPrint(page)
    })
    .catch((e) => {
      forceVerifies.value = e.data.force
      adviceVerifies.value = e.data.advice
      showMessageDrawer = true
      if (e.data.force.length === 0) {
        execPrint(page)
      }
    })
}
const execPrint = (page) => {
  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>`
  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()
  }
})

onMounted(() => {
  ElNotification({
    title: '提示',
    type: 'warning',
    message: '据国家卫健委要求，数据中如有空项，应保留为空，不得以“—”、“-”、“/”等内容代表空项。',
    duration: 5000,
  })
  scrollWrapper = document.getElementById('scrollWrapper')
  initLodop()
  getAllDictionary().then((res) => {
    res.getOperations = operations
    res.getYesOrNo = yesOrNo
    res.getHaveOrNot = haveOrNot
    res.getAutopsies = autopsies
    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;
}

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;
}
</style>
