<template>
  <div>
    <!--组件主体-->
    <div style="display: flex">
      <div :style="'width:' + (window.pageWidth - 110 - 20) + 'px;'">
        <!--查询条件-->
        <div style="position: absolute;top:28px;left:140px;display: flex;">
          <div v-show="checkPagePriv(pagePriv.privs, '查找')">
            <PatientRegisterEditQuery />
          </div>
          <div style="display: flex;margin-left: 5px;">
            <div v-show="checkPagePriv(pagePriv.privs, '职业病')">
              <el-button @click="btnOcc" class="commonbutton" style="width:60px;">职业病</el-button>
            </div>
            <div style="margin-left: 5px;" v-show="checkPagePriv(pagePriv.privs, '读身份证')">
              <el-button @click="peopleIcCard" class="commonbutton" style="width:70px;">读身份证</el-button>
            </div>
            <div style="margin-left: 5px;" v-show="checkPagePriv(pagePriv.privs, '拍照')">
              <el-button type="primary" class="commonbutton" @click="photoGrah" style="width:60px;">拍照</el-button>
            </div>
            <div style="margin-left: 5px;" v-show="checkPagePriv(pagePriv.privs, '个人预约')">
              <el-button type="primary" class="commonbutton" @click="btnWebBooking" style="width:70px;">个人预约</el-button>
            </div>
            <div style="margin-left: 5px;">
              <el-button type="primary" class="commonbutton" @click="btnWebBookingMzak"
                style="width:70px;">人寿预约</el-button>
            </div>
            <div style="margin-left: 5px;" v-show="checkPagePriv(pagePriv.privs, '同步团检预约')">
              <el-button type="primary" class="commonbutton" @click="btnDownOrg"
                :disabled="(form.customerOrgId == dict.personOrgId) || !form.id">同步团检预约</el-button>
            </div>
            <div style="margin-left: 5px;" v-show="checkPagePriv(pagePriv.privs, '分诊排队')">
              <el-button type="primary" class="commonbutton" @click="fnQueue(form)"
                :disabled="!form.id">分诊排队</el-button>
            </div>
          </div>
        </div>
        <div>
          <el-form ref="form" :model="form" label-width="80px" :rules="rules" size="medium">
            <el-row>
              <el-col :span="5">
                <el-form-item label="单位名称" prop="customerOrgName">
                  <el-input placeholder="请选择单位" v-model="form.customerOrgName" size="small" disabled>
                    <el-button slot="append" icon="el-icon-search" @click="dialogOrg = true" style="font-size: 20px;"
                      :disabled="(form.completeFlag == '3' || isDoctor != '1') ? true : false"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="条码号" prop="patientRegisterNo">
                  <el-input v-model="form.patientRegisterNo" disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="档案号" prop="patientNo">
                  <el-input v-model="form.patientNo" disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="体检次数" prop="medicalTimes">
                  <el-input v-model="form.medicalTimes" disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="性别" prop="sexId" label-width="50px">
                  <el-select v-model="form.sexId" placeholder="请选择" size="small" filterable
                    :style="'width:' + Math.floor((window.pageWidth - 630) / 8) + 'px;'">
                    <el-option v-for="item in dict.sex" :key="item.id" :label="item.displayName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="姓名" prop="patientName">
                  <el-input id="patientName" v-model="form.patientName" @change="changePatientName" size="small"
                    autocomplete="off"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="身份证号" prop="idNo">
                  <el-input v-model="form.idNo" placeholder="身份证号" @change="changeIdNo" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="出生日期" prop="birthDate">
                  <!-- 
                  <input type="date" v-model="form.birthDate" size="small" 
                    :style="'border-radius: 4px;border: 1px solid #DCDFE6;height: 32px;line-height: 32px;padding-left: 2px;width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'"/>
                  -->
                  <el-date-picker v-model="form.birthDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                    placeholder="出生日期" :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'"
                    @change="changeBirthDate" prefix-icon="" size="small" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="年龄" prop="age">
                  <el-input v-model="form.age" size="small" @change="changeAge"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="婚姻" prop="maritalStatusId" label-width="50px">
                  <el-select v-model="form.maritalStatusId" placeholder="请选择" size="small" filterable
                    :style="'width:' + Math.floor((window.pageWidth - 630) / 8) + 'px;'">
                    <el-option v-for="item in dict.maritalStatus" :key="item.id" :label="item.displayName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3" />
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="手机号" prop="mobileTelephone">
                  <el-input v-model="form.mobileTelephone" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="电话" prop="telephone">
                  <el-input v-model="form.telephone" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="邮编" prop="postalCode">
                  <el-input v-model="form.postalCode" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="籍贯" prop="birthPlaceId" label-width="50px">
                  <el-select v-model="form.birthPlaceId" placeholder="请选择" filterable clearable
                    :style="'width:' + Math.floor((window.pageWidth - 630) / 8) + 'px;'" size="small">
                    <el-option v-for="item in dict.birthPlace" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3" />
            </el-row>
            <el-row>
              <el-col :span="10">
                <el-form-item label="地址" prop="address">
                  <el-input v-model="form.address" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="人员类别" prop="personnelTypeId">
                  <el-select v-model="form.personnelTypeId" placeholder="请选择" filterable clearable
                    :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'" size="small">
                    <el-option v-for="item in dict.personnelType" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="性激素期" prop="sexHormoneTermId">
                  <el-select v-model="form.sexHormoneTermId" placeholder="请选择" filterable clearable size="small"
                    :disabled="isComplete">
                    <el-option v-for="item in dict.sexHormoneTerm" :key="item.id" :label="item.displayName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="民族" prop="nationId" label-width="50px">
                  <el-select v-model="form.nationId" placeholder="请选择" filterable clearable default-first-option
                    :filter-method="filterMethod" :style="'width:' + Math.floor((window.pageWidth - 630) / 8) + 'px;'"
                    size="small">
                    <el-option v-for="item in nation" :key="item.id" :label="item.displayName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3" />
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="体检类别" prop="medicalTypeId">
                  <el-select v-model="form.medicalTypeId" placeholder="请选择" filterable clearable
                    :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'" size="small"
                    @change="changeMedicalTypeId">
                    <el-option v-for="item in dict.medicalType" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="工卡号" prop="jobCardNo">
                  <el-input v-model="form.jobCardNo" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="体检卡号" prop="medicalCardNo">
                  <el-input v-model="form.medicalCardNo" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="职务" prop="jobPost">
                  <el-input v-model="form.jobPost" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="职称" prop="jobTitle" label-width="50px">
                  <el-input v-model="form.jobTitle" size="small"
                    :style="'width:' + Math.floor((window.pageWidth - 630) / 8) + 'px;'" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="介绍人" prop="salesman">
                  <el-input v-model="form.salesman" size="small"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="体检中心" prop="medicalCenterId">
                  <el-select v-model="form.medicalCenterId" placeholder="请选择" filterable
                    :disabled="peisid ? true : false" size="small"
                    :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'">
                    <el-option v-for="item in dict.organization" :key="item.id" :label="item.displayName"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="单位体检次数" prop="isVip" label-width="110px">
                  <el-select :class="form.customerOrgId == dict.personOrgId ? '' : 'enterToTab'"
                    v-model="form.customerOrgRegisterId" placeholder="次数" size="small"
                    :disabled="form.customerOrgId == dict.personOrgId || form.completeFlag == '3'"
                    :style="'width:' + Math.floor((window.pageWidth - 654) / 6) + 'px;'" @change="changeMedicalTimes"
                    value-key="id">
                    <el-option v-for="item in customerOrgRegisterList" :key="item.id" :label="item.medicalTimes"
                      :value="item.id" :disabled="item.isComplete == 'Y'" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="门诊号" prop="hisPatientId">
                  <el-input v-model="form.hisPatientId" size="small" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="电话随访" prop="isPhoneFollow">
                  <!--
                  <el-radio v-model="form.isPhoneFollow" label="Y">是</el-radio>
                  <el-radio v-model="form.isPhoneFollow" label="N">否</el-radio>
                  -->
                  <el-checkbox v-model="form.isPhoneFollow" true-label="Y" false-label="N" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="VIP" prop="isVip" label-width="50px">
                  <!--
                  <el-radio v-model="form.isVip" label="Y">是</el-radio>
                  <el-radio v-model="form.isVip" label="N">否</el-radio>
                  -->
                  <el-checkbox v-model="form.isVip" true-label="Y" false-label="N" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="隐藏姓名" prop="isNameHide">
                  <!--
                  <el-radio v-model="form.isNameHide" label="Y">是</el-radio>
                  <el-radio v-model="form.isNameHide" label="N">否</el-radio>
                  -->
                  <el-checkbox v-model="form.isNameHide" true-label="Y" false-label="N" />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="锁住" prop="isLock" label-width="50px">
                  <!--
                  <el-radio v-model="form.isLock" label="Y">是</el-radio>
                  <el-radio v-model="form.isLock" label="N">否</el-radio>
                   -->
                  <el-checkbox v-model="form.isLock" true-label="Y" false-label="N" />
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="体检开始" prop="isMedicalStart">
                  <el-select v-model="form.isMedicalStart" placeholder="请选择" disabled size="small">
                    <el-option label="是" value="Y" />
                    <el-option label="否" value="N" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="5">
                <el-form-item label="分组" prop="customerOrgGroupId">
                  <el-select v-model="form.customerOrgGroupId" placeholder="请选择" filterable clearable
                    @change="changeCustomerOrgGroupId" :disabled="displayGroup"
                    :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'" size="small">
                    <el-option v-for="item in patientRegister.customerOrgGroup" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="套餐" prop="medicalPackageId">
                  <el-select v-model="form.medicalPackageId" placeholder="请选择" filterable clearable
                    @change="changeMedicalPackageId" :disabled="displayPackage"
                    :style="'width:' + Math.floor((window.pageWidth - 510) / 4.8) + 'px;'" size="small">
                    <el-option v-for="item in dict.medicalPackage" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" :rows="1" placeholder="请输入备注" size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="状态" prop="completeFlag" label-width="50px">
                  <el-select v-model="form.completeFlag" placeholder="请选择"
                    :disabled="(form.completeFlag == '2' || form.completeFlag == '3') ? true : false" size="small">
                    <div v-if="form.completeFlag == '2' || form.completeFlag == '3'">
                      <el-option v-for="item in dict.completeFlag" :key="item.id" :label="item.displayName"
                        :value="item.id">
                      </el-option>
                    </div>
                    <div v-else>
                      <el-option label="预登记" value="0" />
                      <el-option label="正式登记" value="1" />
                    </div>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <!--青藏公司 start-->
            <el-row v-if="LocalConfig.patientRegister.edit == 'qztl'">
              <el-col :span="4">
                <el-form-item label="高原/健康">
                  <el-select v-model="form.qztlType" placeholder="请选择" disabled>
                    <el-option v-for="item in dict.qztlType" :key="item.id" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="普速">
                  <el-checkbox v-model="form.qztlIsCw" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="从业">
                  <el-checkbox v-model="form.qztlIsCy" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="高铁">
                  <el-checkbox v-model="form.qztlIsGt" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="行车">
                  <el-checkbox v-model="form.qztlIsMain" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="职害">
                  <el-checkbox v-model="form.qztlIsWh" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="复检">
                  <el-checkbox v-model="form.qztlIsFj" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="导入">
                  <el-checkbox v-model="form.isQztlImport" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="上传">
                  <el-checkbox v-model="form.uploadQztlFlag" true-label="Y" false-label="N" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="计划" prop="planuserid">
                  <el-input v-model="form.planuserid" size="small" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <!--青藏公司 end-->
            <!--职业病 start-->
            <el-row v-if="form.isPatientOccupationalDisease == 'Y'">
              <el-col :span="4">
                <el-form-item prop="ocCheckTypeId" label="检查类别">
                  <el-select v-model="form.ocCheckTypeId" size="small" @change="changeOccPosionOrCheckType">
                    <el-option v-for="item in dict.occCheckType" :key="item.value" :label="item.displayName"
                      :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="工种" label-width="40px">
                  <el-input v-model="form.jobType" clearable size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14">
                <el-form-item label="接害因素" label-width="65px">
                  <el-select v-model="form.poisonIds" size="small"
                    :style="`width:${Math.floor((window.pageWidth - 242) / 1.714)}px;`" clearable filterable
                    :filter-method="filterMethodPoison" value-key="id" multiple @change="changeOccPosionOrCheckType"
                    :disabled="form.completeFlag == '3' ? true : false">
                    <el-option-group v-for="group in poison" :key="group.poisonTypeName" :label="group.poisonTypeName">
                      <el-option v-for="item in group.poisonDtos" :key="item.id" :label="item.displayName"
                        :value="item.id" />
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="申请号" prop="occupationalDiseaseNumber" label-width="50px">
                  <el-input v-model="form.occupationalDiseaseNumber" clearable size="small"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <!--职业病  end -->
            <el-row>
              <el-col :span="6">
                <el-form-item label="创建人员">
                  <el-input v-model="form.creatorName" disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建时间">
                  <el-input :value="form.creationTime
                    ? moment(form.creationTime).format('yyyy-MM-DD')
                    : ''
                    " disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="修改人员">
                  <el-input v-model="form.lastModifierName" disabled size="small"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="修改时间">
                  <el-input :value="form.lastModificationTime
                    ? moment(form.lastModificationTime).format('yyyy-MM-DD')
                    : ''
                    " disabled size="small"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-image
            :style="'position: absolute;top:70px;right:' + (100 + Math.floor((window.pageWidth - 680) / 24)) + 'px; width: 130px; height: 140px;'"
            :src="peoplePhoto">
            <div slot="placeholder" class="image-slot">
              加载中<span class="dot">...</span>
            </div>
          </el-image>
        </div>
        <!--人员登记组合项目明细 register_check_asbitem-->
        <div>
          <PatientRegisterItem :prForm="form" :prAsbOpraOpts="prAsbOpraOpts" :refreshFormId="refreshFormId" />
        </div>
      </div>
      <div style="margin-left: 10px;">

        <div v-show="checkPagePriv(pagePriv.privs, '新增')">
          <el-button type="primary" class="commonbutton" @click="btnAdd">新增</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '复制新增')" class="btn">
          <el-button type="primary" class="commonbutton" @click="rdCopy">复制新增</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '保存')" class="btn">
          <el-button type="success" class="commonbutton" @click="btnSubmit('form', true)">保存</el-button>
        </div>

        <div v-show="checkPagePriv(pagePriv.privs, '检验单申请')" class="btn">
          <el-button type="primary" class="commonbutton" @click="lisRequest">检验单申请</el-button>
        </div>

        <div v-show="checkPagePriv(pagePriv.privs, '条码打印')" class="btn">
          <el-button type="primary" class="commonbutton" @click="labelPrint(false)"
            :disabled="printing">条码打印</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '条码补打')" class="btn">
          <el-button type="danger" class="commonbutton" @click="btnLabel">条码补打</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '指引单打印')" class="btn">
          <el-button type="primary" class="commonbutton" @click="guidePrint('0001', false)"
            :disabled="printing">指引单打印</el-button>
        </div>
        <!-- 
        <div v-show="checkPagePriv(pagePriv.privs, '指引单预览')" class="btn">
          <el-button type="primary" class="commonbutton" @click="guidePrint('0001', true)">指引单预览</el-button>
        </div>
        -->
        <div v-show="checkPagePriv(pagePriv.privs, '条码合并')" class="btn">
          <el-button type="danger" class="commonbutton" @click="reLisRequest">条码合并</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '手动合并项目')" class="btn">
          <el-button type="danger" class="commonbutton" @click="reMergeAsbitem">手动合并项目</el-button>
        </div>

        <div v-show="checkPagePriv(pagePriv.privs, '全个人支付')" style="margin-top: 30px;">
          <el-button type="primary" class="commonbutton" @click="btnPayTypeFlag('0')">全个人支付</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '全单位支付')" class="btn">
          <el-button type="primary" class="commonbutton" @click="btnPayTypeFlag('1')">全单位支付</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '全赠送')" class="btn">
          <el-button type="primary" class="commonbutton" @click="btnPayTypeFlag('2')">全赠送</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '收费')" class="btn">
          <el-button type="success" class="commonbutton" @click="toCharge(form)" :disabled="!form.id">收费</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '收费申请')" class="btn">
          <el-button type="success" class="commonbutton" @click="chargeRequest(form)"
            :disabled="!form.id">收费申请</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '复制分组')" class="btn">
          <el-button class="commonbutton" @click="btnCopyGroup"
            :disabled="form.isLock == 'Y' || form.completeFlag == '3' ? true : false">复制分组</el-button>
        </div>
        <div v-show="checkPagePriv(pagePriv.privs, '复制套餐')" class="btn">
          <el-button class="commonbutton" @click="btnCopyMedicalPackage"
            :disabled="form.isLock == 'Y' || form.completeFlag == '3' ? true : false">复制套餐</el-button>
        </div>
      </div>
    </div>

    <!--组件弹窗-->
    <div>
      <!-- 人员档案列表 -->
      <el-dialog title="人员档案列表" :visible.sync="dialogVisible" width="800px" :show-close="false"
        :close-on-click-modal="false" :append-to-body="true">
        <el-table :data="patientList" border width="800" height="480" row-key="id" size="small"
          class="el-table__body-wrapper tbody" highlight-current-row @row-click="rowick" @row-dblclick="patientDblclick"
          ref="patientList">
          <el-table-column type="index" width="30" />
          <el-table-column prop="patientNo" label="档案号" />
          <el-table-column prop="lastTime" label="末次体检" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.lastTime">
                {{ moment(scope.row.lastTime).format("yyyy-MM-DD") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="medicalTimes" label="体检次数" />
          <el-table-column prop="displayName" label="姓名" />
          <el-table-column prop="sexId" label="性别">
            <template slot-scope="scope">
              <div>
                {{ dddw(dict.sex, "id", scope.row.sexId, "displayName") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="maritalStatusId" label="婚姻">
            <template slot-scope="scope">
              <div>
                {{ dddw(dict.maritalStatus, "id", scope.row.maritalStatusId, "displayName") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="birthDate" label="出生日期" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.birthDate">
                {{ moment(scope.row.birthDate).format("yyyy-MM-DD") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="nationId" label="民族">
            <template slot-scope="scope">
              <div>
                {{ dddw(dict.nation, "id", scope.row.nationId, "displayName") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="idNo" label="身份证号" />
          <el-table-column prop="telephone" label="电话" />
          <el-table-column prop="mobileTelephone" label="手机号" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button class="commonbutton" @click="dialogVisible = false" style="width:90px;">取消</el-button>
          <el-button class="commonbutton" type="primary" @click="choosePatient" style="width:90px;">确定</el-button>
        </span>
      </el-dialog>

      <el-dialog title="职业病" :visible.sync="dialogWin.OccDisease" width="800px" :close-on-click-modal="false"
        :append-to-body="true">
        <OccDisease />
      </el-dialog>

      <el-dialog title="网上预约" :visible.sync="dialogWin.WebBooking" width="800px" :close-on-click-modal="false"
        :append-to-body="true" :show-close="false" @close="close_dialogWin_WebBooking">
        <WebBooking />
      </el-dialog>

      <el-dialog title="网上预约--人寿" :visible.sync="dialogWin.WebBookingMzak" width="800px" :close-on-click-modal="false"
        :append-to-body="true" :show-close="false" @close="close_dialogWin_WebBookingMzak">
        <WebBookingMzak />
      </el-dialog>

      <!-- checkStrictly: true, expandTrigger: 'hover', -->
      <el-dialog title="选择单位" :visible.sync="dialogOrg" width="800px" :close-on-click-modal="false"
        :append-to-body="true">
        <div style="height: 320px;">
          <el-cascader v-model="form.customerOrgId" :options="patientRegister.customerOrgTreeAll" style="width:400px;"
            filterable popper-class="example" :show-all-levels="false" @change="changeChooseOrgId"
            :props="{ checkStrictly: true, expandTrigger: 'click', ...customerOrg.treeprops, lazyLoad: lazyLoad, lazy: true, leaf: 'isLeaf' }"
            size="small">
          </el-cascader>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="btnOkOrg">确定</el-button>
          <el-button @click="dialogOrg = false">关闭</el-button>
        </span>
      </el-dialog>

      <!-- 拍照（openCamera） 网页模式，已废弃  
    <el-dialog title="拍照" :visible.sync="patientRegister.cameraVisble" width="400" height="600"
      :close-on-click-modal="false" :append-to-body="true">
      <Camera :id="form.id" />    
    </el-dialog>
    -->
      <!-- 合并条码 -->
      <el-dialog title="合并条码" :visible.sync="patientRegister.lisRequestVisble" width="600px" height="400"
        :show-close="false" :close-on-click-modal="false" :append-to-body="true">
        <LisRequest :id="form.id" :brushTimes="brushTimes" />
      </el-dialog>

      <!-- 条码补打 -->
      <el-dialog title="条码补打" :visible.sync="dialogWin.Label" width="800px" height="400" :close-on-click-modal="false"
        :append-to-body="true">
        <el-tabs v-model="tabChoosed" style="height:320px;margin-top: -22px;">
          <!-- 组合项目 -->
          <el-tab-pane label="检验条码" name="1">
            <PatientLisRequest :isDialog="true" />
          </el-tab-pane>
          <el-tab-pane label="检查条码" name="2">
            <PatientPacsRequest :isDialog="true" />
          </el-tab-pane>
        </el-tabs>
      </el-dialog>

      <!-- 手动合并项目 -->
      <el-dialog title="手动合并项目" :visible.sync="patientRegister.mergeAsbitemVisble" width="600px" height="400"
        :show-close="false" :close-on-click-modal="false" :append-to-body="true">
        <MergeAsbitem :id="form.id" :medicalCenterId="form.medicalCenterId" :brushTimes="brushTimes" />
      </el-dialog>

      <!-- 收费 -->
      <el-dialog title="" :visible.sync="dialogWin.charge" :close-on-click-modal="false" :append-to-body="true"
        fullscreen @close="closeDialogCharge">
        <div style="margin-top: -30px;">
          <Charge :patientRegisterNo="chargePatientRegisterNo" />
        </div>
      </el-dialog>

      <!-- 收费申请 -->
      <el-dialog title="收费申请" :visible.sync="dialogWin.AsbChargeRequest" width="800px" :show-close="false"
        :close-on-click-modal="false" :append-to-body="true" @close="closeDialogCharge">
        <AsbChargeRequest :patientRegister="form" />
      </el-dialog>

      <!-- 分诊排队 -->
      <el-dialog title="分诊排队" :visible.sync="dialogWin.queue" width="800px" :append-to-body="true"
        :close-on-click-modal="false">
        <Queue :refParams="queueParams" />
      </el-dialog>

      <!--复制套餐-->
      <el-dialog title="复制体检套餐" :visible.sync="medicalPackageVisble" width="800px" height="500" :show-close="false"
        :close-on-click-modal="false" :append-to-body="true">
        <el-table :data="dict.medicalPackage" border height="350" row-key="id" size="small" highlight-current-row
          @row-click="packageRowClick" @row-dblclick="rowDblclick" ref="patientList">

          <!-- "displayName": "健康体检套餐",
        "price": 20.00,
        "forSexId": "0",
        "isActive": "Y",
        "remark": "2",
        "displayOrder": 1,
        "simpleCode": "JKTJTC",
        "creatorName": "admin",
        "lastModifierName": "users",
        "lastModificationTime": "2023-08-04T16:34:02.94408",
        "lastModifierId": "3a0ca83b-3116-da05-3916-dfd4c0c548cb",
        "creationTime": "2023-07-10T19:53:30.210553",
        "creatorId": "3a0c4180-107c-0c89-b25b-0bd34666dcec",
        "id": "3a0c51d3-2345-38df-ba0b-1862a3c3606f" -->
          <el-table-column type="index" width="50" />
          <el-table-column prop="displayName" label="套餐名称" width="180" />
          <el-table-column prop="price" label="价格" width="80" />
          <el-table-column prop="forSexId" label="适用性别" width="80">
            <template slot-scope="scope">
              <div>
                {{ dddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="100" />
          <el-table-column prop="creatorName" label="创建人员" width="80" />
          <el-table-column prop="creationTime" label="创建日期" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.creationTime">
                {{ moment(scope.row.creationTime).format("yyyy-MM-DD") }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastModifierName" label="修改人员" width="80" />
          <el-table-column prop="lastModificationTime" label="修改日期" width="100">
            <template slot-scope="scope">
              <div v-if="scope.row.lastModificationTime">
                {{ moment(scope.row.lastModificationTime).format("yyyy-MM-DD") }}
              </div>
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button class="commonbutton" type="primary" @click="copyMedicalPackage" style="width:90px;">确定</el-button>
          <el-button class="commonbutton" @click="medicalPackageVisble = false" style="width:90px;">取消</el-button>
        </span>
      </el-dialog>

      <!--复制分组-->
      <el-dialog title="复制单位分组" :visible.sync="groupVisble" width="800px" height="500" :show-close="false"
        :close-on-click-modal="false" :append-to-body="true">
        <div>
          <div style="display: flex">
            <div>
              <span>体检单位：</span>
              <el-select v-model="customerOrgId" placeholder="请选择体检单位" :filter-method="filterMethodOrg"
                default-first-option clearable filterable @clear="customerOrgDisp = deepCopy(customerOrgAll)"
                style="margin-left: 10px" @change="changeCustomerOrg" size="small">
                <el-option v-for="item in customerOrgDisp" :key="item.id" :label="item.displayName" :value="item.id">
                  {{ item.displayName }}
                </el-option>
              </el-select>
            </div>
            <div style="margin-left: 20px">
              <span>单位体检次数：</span>
              <el-select v-model="customerOrgRegister" placeholder="次数" style="width: 60px; margin-left: 10px"
                size="small" @change="changeTimes" value-key="id">
                <el-option v-for="item in customerOrgRegisterList" :key="item.id" :label="item.medicalTimes"
                  :value="item" />
              </el-select>
            </div>
          </div>
          <el-table :data="customerOrgGroups" ref="customerOrgGroups" style="margin-top: 2px" row-key="id" border
            height="450px" size="small" highlight-current-row :row-class-name="handleRowClassName"
            @row-click="groupRowClick" @row-dblclick="groupRowDblclick">
            >
            <el-table-column type="index" label="序号" min-width="50" align="center" />
            <el-table-column prop="displayName" label="名称" min-width="150" />
            <el-table-column prop="price" label="价格" min-width="60" align="center" />
            <el-table-column prop="forSexId" label="适用性别" min-width="60" align="center">
              <template slot-scope="scope">
                {{ dddw(dict.forSex, "id", scope.row.forSexId, "displayName") }}
              </template>
            </el-table-column>
            <el-table-column prop="maritalStatusId" label="适用婚姻状况" min-width="80" align="center">
              <template slot-scope="scope">
                {{
                  dddw(
                    dict.forMaritalStatus,
                    "id",
                    scope.row.maritalStatusId,
                    "displayName"
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column prop="creatorName" label="创建者" min-width="60" align="center" />
            <el-table-column label="创建时间" min-width="150" align="center">
              <template slot-scope="scope">
                {{
                  scope.row.creationTime
                    ? moment(scope.row.creationTime).format("yyyy-MM-DD HH:mm:ss")
                    : ""
                }}
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;margin-top: 10px;">
            <div></div>
            <span slot="footer" class="dialog-footer">
              <el-button class="commonbutton" type="primary" @click="copyGroup" style="width:90px;">确定</el-button>
              <el-button class="commonbutton" @click="groupVisble = false" style="width:90px;">取消</el-button>
            </span>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { getTreeNode } from "../../utlis/tree"

import {
  getPagePriv, checkPagePriv, objCopy, setNull, dddw, checkIDCode, parseID,
  birthdayToAge, ageToBirthday, deepCopy, arrayFilter, arrayReduce, parsIcCardtoLocal,
  reMadeOrgTree, arrayExistObj, isValidMobileNumber
} from "../../utlis/proFunc";
import { getTreePids, madeTree } from "../../utlis/tree";
import { photoParse, savePeoplePhoto, } from "../../utlis/proApi";
import Camera from "./Camera.vue";
import PatientRegisterItem from "./PatientRegisterItem.vue";
import LisRequest from "./LisRequest.vue";
import MergeAsbitem from "./MergeAsbitem.vue";
import AsbChargeRequest from "./AsbChargeRequest.vue";
import Charge from "../../views/charge/charge.vue";
import PatientRegisterEditQuery from "../../components/patientRegister/PatientRegisterEditQuery.vue";
import OccDisease from "../../components/occDisease/OccDisease.vue"
import WebBooking from "../../components/webBooking/WebBooking.vue"
import WebBookingMzak from "../../components/webBooking/WebBookingMzak.vue"
import PatientLisRequest from "../../components/patientRegister/PatientLisRequest.vue";
import PatientPacsRequest from "../../components/patientRegister/PatientPacsRequest.vue";
import Queue from "../../components/queue/Queue.vue";

export default {
  components: {
    Camera,
    LisRequest,
    MergeAsbitem,
    PatientRegisterItem,
    Charge,
    AsbChargeRequest,
    PatientRegisterEditQuery,
    OccDisease,
    PatientLisRequest,
    PatientPacsRequest,
    WebBooking, WebBookingMzak,
    Queue
  },
  // isDoctor: '0:标准人员登记/1:医生诊台登记(可修改单位)' 
  props: ['isDoctor', 'patientRegisterId', 'editTimes', 'refreshRegister', 'refFuncSetData'],
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: 'PatientRegisterEdit', //当前页面归属路由或归属页面权限名称
        privs: [] // 页面权限
      },
      patient_register_occ_check_id: '', // 属于职业病体检类别的ID
      merge_lis_pacs_label: "0", //默认0  检验检查条码合并 0：不合并，1：合并
      LocalConfig: {
        patientRegister: {
          editMode: 'standard', //standard/qztl 人员登记组件版本
          editHeight: 0,  // 相较与标准版，选组合项目组件，减少高度
          immediateToHisCharge: true,  // 人员登记保存后，立即发送收费申请
          findPatientByName: true, // 人员登记，启有人名查询
          printGuideLabel: ["guide", "pacs", "lis"], // 保存后打印指引单与条码
          dispCustomerOrgCode: 'N', // 人员登记列表--单位树是否显示 customerOrgCode
        },
      },
      brushTimes: 0,

      peisid: null,
      peoplePhoto: '',
      preCustomerOrgId: '', // 上一个人的体检单位，只是在本组件点新增时才用到
      form: {
        registerManType: 'customer', //登记人员类型，客服：customer 医生：doctor 支持在医生诊台处理登记人员
        id: "", //id
        photo: '', //照片
        patientId: "00000000-0000-0000-0000-000000000000", //档案号ID 选择了档案就传档案号，未选就传00000-0000...
        patientNo: "", //档案号
        customerOrgId: ["00000000-0000-0000-0000-000000000001"], //单位编号 默认个人 
        customerOrgParentId: "00000000-0000-0000-0000-000000000001",
        customerOrgName: "个人体检",
        customerOrgRegisterId: "00000000-0000-0000-0000-000000000001", //默认单位体检次数
        customerOrgGroupId: null, //分组
        medicalPackageId: null, //套餐
        patientName: "", //姓名
        birthDate: null, //日期型
        sexId: "U", //性别 默认未知U
        age: null, //年龄
        jobCardNo: "", //工卡号
        medicalCardNo: "", //体检卡号
        maritalStatusId: "9", //婚姻状况 默认未知
        medicalTypeId: null, //体检类别
        personnelTypeId: null, //人员类别
        jobPost: "", //职务
        jobTitle: "", //职称
        salesman: "", //介绍人
        sexHormoneTermId: null, //性激素期限
        isNameHide: "N", //隐藏姓名
        isPhoneFollow: "N", //电话随访
        isVip: "N", //vip客户
        remark: "", //
        isLock: "N", //是否锁住
        completeFlag: "1", //完成标志 0:预登记，1：正式登记（未检），2：部份已检，3：已总检  【创建编辑时不操作】
        isMedicalStart: "N", //体检开始标志 【创建编辑时不操作】
        patientRegisterNo: "", //条码号 【创建编辑时不操作】
        medicalTimes: 1, //条码号 【创建编辑时不操作】
        medicalCenterId: null, //体检中心
        address: "", //地址
        email: "", //email
        idNo: "", //身份证号
        telephone: "", //电话
        mobileTelephone: "", //手机号
        nationId: null, //民族编号
        birthPlaceId: null, //籍惯（出生地）
        postalCode: "", //邮编
        creatorId: null,
        creationTime: "",
        lastModificationTime: "",
        lastModifierId: null,
        isMaxMedicalTimes: 'N',
        medicalStartDate: null,
        hisPatientId: '',  //对接 hisid
        registerCheckAsbitems: [], //所选组合项目明细
        // 青藏公司 数据
        qztlType: '0',  // 高原/健康
        qztlIsCw: 'N',  // 普速
        qztlIsCy: 'N',  // 从业
        qztlIsGt: 'N',  // 高铁
        qztlIsMain: 'N',  // 行车
        qztlIsWh: 'N',  // 职害
        qztlIsFj: 'N',  // 复检
        isQztlImport: 'N',  // 导入
        uploadQztlFlag: 'N',  // 上传
        planuserid: '',  // 计划人  

        // 职业病
        ocCheckTypeId: null,  //检查类别
        jobType: '', //工种
        poisonIds: [], // 接害因素IDs（主表不保存此项数据）
        isPatientOccupationalDisease: 'Y', // 是否职业病检查（主表不保存此项数据）
        appointPatientRegisterId: "",
        thirdBookingId: "",
        occupationalDiseaseNumber: "",
      }, //单位 记录 目前新增与更新是一致


      formInit: {}, //表单初始化
      customerOrgRegisterList: [], //单位体检次数列表
      defaultNull: [
        "customerOrgId",
        "customerOrgGroupId",
        "medicalPackageId",
        "birthDate",
        "age",
        "maritalStatusId",
        "medicalTypeId",
        "personnelTypeId",
        "sexHormoneTermId",
        "medicalCenterId",
        "nationId",
        "birthPlaceId",
      ], //一般uuid字段为空时，需设置为null值

      rules: {
        customerOrgId: [
          { required: true, message: "请填写单位", trigger: "blur" },
        ],
        patientName: [
          { required: true, message: "请填写姓名", trigger: "blur" },
        ],
        medicalCenterId: [
          { required: true, message: "请填写体检中心", trigger: "blur" },
        ],
        // mobileTelephone: [
        //   { required: true, message: "请填写手机号", trigger: "blur" },
        //   { validator: validateMobileTelephone, trigger: 'blur' }
        // ],
      },

      dialogVisible: false,
      patientList: [], //人员列表（用于判断人员多次体检）
      patientChoosed: {}, //查重选中的人员


      registerVisible: false,
      patientRegisters: [],
      registerChoosed: {},

      dialogCamera: false, //拍照组件

      chargePatientRegisterNo: '',  //对哪个条码客户收费 

      //人员登记，组合项目明细操作相关参数
      prAsbOpraOpts: {
        formId: '',      //form.id为空时，明细保存取此formId
        copyNew: 0,      //触发复制新增
        payTypeFlag: '', //触发调整支付方式
        prAsbSave: 0, //触发组合项目明细保存
        prAsbQuery: 0,//触发组合项目明细查询，比如收费后，刷新收费状态
        prAsbGroup: 0, //触发分组更换
        prAsbPackage: 0, //触发套餐更换
      },
      nation: [], //
      dialogOrg: false,

      printing: false, // 是否打印中，控制一次只能有一个任务
      completeFlag: '0', // 默认预登记，首次正式登记或者预登记转正式登记，提示打印条码与指引单

      tabChoosed: "1",

      poison: [],
      poisonList: [],

      thirdInterfaceId: '', // 网上预约用到
      queueParams: {}, // 分诊排队参数

      //**复制分组与套餐相关数据
      //控制 复制套餐与分组页面 显示
      medicalPackageVisble: false,
      groupVisble: false,

      customerOrgGroups: [],

      //选中套餐与分组所包含的组合项目
      curPackageId: '',
      curGroupId: '',
      packageAsbitems: [],
      groupAsbitems: [],

      customerOrgId: '',
      customerOrgDisp: [],
      customerOrgAll: [],
      customerOrgRegisterList: [], //当前体检次数集合
      customerOrgRegister: {}, // 当前选择体检次数

      hc_warn_mode: '1',  //0-仅提醒；1-提醒并决择；2-有互斥项目时不允许保存
    };
  },

  created() {
    //获取用户当前页面的权限
    let userPriv = window.sessionStorage.getItem('userPriv')
    if (userPriv) this.pagePriv.privs = deepCopy(getPagePriv(this.pagePriv.routeUrlorPageName))

    try {
      let LocalConfig = JSON.parse(window.localStorage.getItem('LocalConfig'))
      if (LocalConfig && LocalConfig.patientRegister) {
        if (LocalConfig.patientRegister.edit) this.LocalConfig.patientRegister.edit = LocalConfig.patientRegister.edit
        if (LocalConfig.patientRegister.editHeight) this.LocalConfig.patientRegister.editHeight = LocalConfig.patientRegister.editHeight
        if (LocalConfig.patientRegister.immediateToHisCharge) {
          this.LocalConfig.patientRegister.immediateToHisCharge = true
        } else {
          this.LocalConfig.patientRegister.immediateToHisCharge = false
        }
        if (LocalConfig.patientRegister.findPatientByName) {
          this.LocalConfig.patientRegister.findPatientByName = true
        } else {
          this.LocalConfig.patientRegister.findPatientByName = false
        }
        if (LocalConfig.patientRegister.printGuideLabel) this.LocalConfig.patientRegister.printGuideLabel = deepCopy(LocalConfig.patientRegister.printGuideLabel)
        if (LocalConfig.patientRegister.dispCustomerOrgCode) this.LocalConfig.patientRegister.dispCustomerOrgCode = LocalConfig.patientRegister.dispCustomerOrgCode
      }
    } catch (error) {
      console.log("window.localStorage.getItem('LocalConfig')", error)
    }

    this.formInit = deepCopy(this.form)

    // 初始化字典数据
    this.dictInit()
  },

  //挂载完成
  mounted() {
    this.initFormData(this.dataTransOpts.tableS.patient_register.id)
    // 表单中 回车 代替 tab
    this.enterToTab();
  },

  computed: {
    ...mapState(["window", "dialogWin", "dataTransOpts", "dict", "patientRegister", "customerOrg", "projPriv"]),

    //是否总检(已总检则不允许修改套餐与分组)
    isComplete() {
      return this.form.completeFlag == '3' ? true : false;
    },

    // 套餐 disabled 如完成体检亦不允许编辑
    displayPackage() {
      let isPersonOrgId = true
      if (!this.isComplete) {
        if (!this.form.customerOrgId) return false
        if (typeof this.form.customerOrgId == 'string') {
          if (this.form.customerOrgId == this.dict.personOrgId) isPersonOrgId = false
        } else {
          if (this.form.customerOrgId[this.form.customerOrgId.length - 1] == this.dict.personOrgId) isPersonOrgId = false
        }
      }
      return isPersonOrgId
    },

    // 分组 disabled 如完成体检亦不允许编辑
    displayGroup() {
      let isPersonOrgId = true
      if (!this.isComplete) {
        if (!this.form.customerOrgId) return isPersonOrgId
        if (typeof this.form.customerOrgId == 'string') {
          if (this.form.customerOrgId != this.dict.personOrgId) isPersonOrgId = false
        } else {
          if (this.form.customerOrgId[this.form.customerOrgId.length - 1] != this.dict.personOrgId) isPersonOrgId = false
        }
      }
      return isPersonOrgId
    },
  },
  methods: {
    ...mapActions(['getPatientRegisterAbs']),
    dddw, moment, checkPagePriv,

    btnTest() {
      // console.log('form', this.form)
    },

    validateMobileTelephone(rule, value, callback) {
      if (value) {
        if (!isValidMobileNumber(value)) {
          callback(new Error('请填写正确的手机号！'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },

    //数据初始化
    dictInit() {
      // 获取系统参数 -- 职业病 体检类别编号
      let sysParmId = "patient_register_occ_check_id"
      postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId })
        .then(res => {
          if (res.code > -1) this.patient_register_occ_check_id = res.data
        })

      // 获取系统参数 -- 合并检验检查条码
      postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: 'merge_lis_pacs_label' })
        .then(res => {
          if (res.code > -1) {
            this.merge_lis_pacs_label = res.data || "0"
          }
        })

      // 获取系统参数 -- 人员登记必填列
      postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: 'patient_register_required_field' })
        .then(res => {
          if (res.code > -1) {
            try {
              let masterCols = JSON.parse(res.data)
              let cols = Object.keys(masterCols)
              cols.forEach(key => {
                if (!this.rules[key]) {
                  this.rules[key] = [{
                    required: true, message: `请填写${masterCols[key]}`, trigger: "blur"
                  }]
                }
              });
            } catch (error) {
              console.error(error)
            }
          }
        })

      //性别（仅档案用）
      getapi("/api/app/sex").then((res) => {
        if (res.code == 1) {
          this.dict.sex = res.data;
        }
      });

      //适用性别
      getapi("/api/app/for-sex").then((res) => {
        if (res.code == 1) {
          this.dict.forSex = res.data;
        }
      });

      //体检中心
      getapi("/api/app/organization-units/organization-unit-by-is-peis").then(
        (res) => {
          if (res.code == 1) {
            this.dict.organization = res.data;
          }
        }
      );

      //体检单位
      // getapi("/api/app/customer-org/in-filter").then((res) => {
      //   if (res.code == 1) {
      //     this.dict.customerOrg = res.data;
      //   }
      // });

      //体检类别      
      getapi("/api/app/medical-type/in-filter").then((res) => {
        if (res.code > -1) {
          this.dict.medicalType = res.data;
        }
      });

      //人员类别
      getapi("/api/app/personnel-type/in-filter").then((res) => {
        if (res.code > -1) {
          this.dict.personnelType = res.data;
        }
      });

      //婚姻状况
      getapi("/api/app/MaritalStatus/GetMaritalStatusList").then((res) => {
        if (res.code == 1) {
          this.dict.maritalStatus = res.data;
        }
      });

      //性激素期
      getapi("/api/app/sex-hormone-term/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.sexHormoneTerm = res.data;
        }
      });

      //民族
      getapi("/api/app/nation/in-filter").then((res) => {
        if (res.code != -1) {
          this.dict.nation = res.data;
          this.nation = deepCopy(res.data)
        }
      });

      //籍惯 ，出生地
      getapi("/api/app/birth-place/in-filter").then((res) => {
        if (res.code == 1) {
          this.dict.birthPlace = res.data;
        }
      });

      //套餐
      postapi("/api/app/medicalpackage/GetBasicList", {}).then((res) => {
        if (res.code == 1) {
          this.dict.medicalPackage = res.data;
        }
      });

      //支付方式
      getapi("/api/app/pay-mode").then((res) => {
        if (res.code == 1) {
          this.dict.payMode = res.data;
        }
      });

      //职业病检查类别
      postapi("/api/app/OcCheckType/GetList").then((res) => {
        if (res.code > -1) {
          this.dict.occCheckType = res.data;
        }
      });

      //接害因素
      postapi("/api/app/Poison/GetPoisonWithTypeList").then(res => {
        if (res.code > -1) {
          this.poison = res.data;
          this.poisonList = []
          this.poison.forEach(e => {
            e.poisonDtos.forEach(e2 => {
              this.poisonList.push({
                poisonTypeName: e.poisonTypeName,
                id: e2.id,
                displayName: e2.displayName,
                simpleCode: e2.simpleCode
              })
            });
          });
        }
      })



      //项目类别 树结构
      // getapi("/api/app/item-type/by-code-all").then((res) => {
      //   if (res.code != -1) {
      //     this.dict.itemTypeTree = res.data;
      //     tcdate(this.dict.itemTypeTree);
      //   }
      // });

      // postapi("/api/app/asbitem/GetBasicList",{isFilterActive:'Y'}).then((res) => {
      //   if (res.code != -1) {
      //     this.dict.asbItemAll = res.data;
      //   }
      // });

      // // console.log("dict", this.dict);
    },

    changeMedicalTypeId(v) {
      if (this.patient_register_occ_check_id && this.patient_register_occ_check_id == v) {
        this.form.isPatientOccupationalDisease = 'Y'
      } else {
        this.form.isPatientOccupationalDisease = 'N'
      }
    },

    changeChooseOrgId(v) {
      let parentId = null
      if (v) {
        parentId = v[v.length - 1]
        // 已经查询过或无叶子节点的无需再查询
        let lfind = arrayExistObj(this.patientRegister.customerOrgs, 'parentId', parentId)
        if (lfind > -1) return
        lfind = arrayExistObj(this.patientRegister.customerOrgs, 'id', parentId)
        if (lfind > -1 && this.patientRegister.customerOrgs[lfind].isChild == 'N') return
      } else {
        return
      }

      this.getCustomerOrgChild(parentId)
    },

    getCustomerOrgChild(parentId) {
      return new Promise((resolve, reject) => {
        postapi('/api/app/CustomerOrg/GetCustomerOrgByParentId', { parentId })
          .then(res => {
            if (res.code > -1) {
              res.data.forEach(e => {
                e.isLeaf = e.isChild == 'Y' ? false : true
              });
              // console.log('this.patientRegister.customerOrgs', this.patientRegister.customerOrgs)
              let treeData = reMadeOrgTree(deepCopy(res.data), this.LocalConfig.patientRegister.dispCustomerOrgCode);
              treeData.forEach(e => {
                if (arrayExistObj(this.patientRegister.customerOrgs, 'id', e.id) == -1) {
                  this.patientRegister.customerOrgs.push(e)
                }
              });
              this.patientRegister.customerOrgTreeAll = madeTree(this.patientRegister.customerOrgs, 'treeChildren', 'parentId', 'id', null)
              // console.log('this.patientRegister.customerOrgTreeAll', this.patientRegister.customerOrgTreeAll)
              resolve(treeData)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },

    lazyLoad(node, resolve) {
      if (node && node.data && node.data.id) {
        this.getCustomerOrgChild(node.data.id).then(res => {
          resolve(res)
        }).catch(err => {
          resolve([])
        })
      }
    },

    // 确定选中企业
    btnOkOrg() {
      let customerOrgId = ''
      this.changeCustomerOrgId(this.form.customerOrgId)
      if (Array.isArray(this.form.customerOrgId)) {
        this.form.customerOrgParentId = this.form.customerOrgId[0]
        customerOrgId = this.form.customerOrgId[this.form.customerOrgId.length - 1]
      } else {
        this.form.customerOrgParentId = this.form.customerOrgId
        customerOrgId = this.form.customerOrgId
      }
      let node = getTreeNode(this.patientRegister.customerOrgTreeAll, "treeChildren", "id", customerOrgId)
      if (node) this.form.customerOrgName = node.displayName

      this.dialogOrg = false
    },

    // 获取登记信息 初始form表单数据
    initFormData(patientRegisterId) {
      return new Promise((resolve, reject) => {
        this.peisid = window.sessionStorage.getItem('peisid');
        let customerOrgId, customerOrgName, customerOrgParentId
        if (this.patientRegister.query.customerOrgId) {
          customerOrgParentId = this.patientRegister.query.CustomerOrgParentId
          customerOrgId = this.patientRegister.query.customerOrgId
          customerOrgName = this.patientRegister.query.customerOrgName
        } else {
          customerOrgParentId = this.form.customerOrgParentId
          customerOrgId = this.form.customerOrgId
          customerOrgName = this.form.customerOrgName
        }
        this.preCustomerOrgId = this.patientRegister.query.customerOrgId
        if (!patientRegisterId) { //添加
          this.peoplePhoto = '' // 清掉照片
          this.form = Object.assign({}, this.form, this.formInit)
          this.form.registerCheckAsbitems = []
          this.form.medicalCenterId = this.peisid; //体检中收
          this.form.customerOrgId = customerOrgId //体检单位
          this.form.customerOrgParentId = customerOrgParentId //体检父单位
          this.form.customerOrgName = customerOrgName

          // 登记时继承单位的体检类别
          this.getMedicalTypeByOrg(customerOrgId)

          this.completeFlag = '0'
          this.handleFormData().then(() => {
            resolve()
          })

        } else {
          // let res = await getapi(`/api/app/patient-register/${patientRegisterId}`)
          postapi('/api/app/patientregister/getinfoorpatient', { patientRegisterId })
            .then(res => {
              if (res.code > -1) {
                // this.form = res.data  这种方式，会造成 checkbox 值变化不响应，故取消
                this.form = Object.assign({}, this.form, res.data)
                this.completeFlag = this.form.completeFlag
                this.handleFormData().then(() => resolve())
              }
            })
            .catch(() => resolve())
        }
      })
    },

    // 根据体检单位ID，获取体检类别
    getMedicalTypeByOrg(customerOrgId) {
      return new Promise((resolve, reject) => {
        postapi('/api/app/Customerorg/GetMedicalTypeIdByCustomerOrgId', { customerOrgId })
          .then(res => {
            if (res.code > -1) {              
              this.form.medicalTypeId = res.data.medicalTypeId
              this.form.personnelTypeId = res.data.personnelTypeId
            }
          })
      })
    },


    handleFormData() {
      return new Promise((resolve, reject) => {
        // 判断是否职业健康检查
        this.changeMedicalTypeId(this.form.medicalTypeId)
        if (this.form.isPatientOccupationalDisease == 'Y') {
          this.getOccDiseaseData()
        }

        // 处理照片
        this.getPeoplePhoto(this.form.photo)

        // this.dataTransOpts.refresh.register_check_asbitem.D++ //触发所选组合项目刷新 (取消这种触发，减少交互)
        this.dataTransOpts.tableM.register_check_asbitem = this.form.registerCheckAsbitems
        this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
          e.standTotal = e.amount * e.standardPrice
          e.total = e.amount * e.chargePrice
        });

        // 单位/个人 的分组与套餐处理
        this.changeCustomerOrgId(this.form.customerOrgId)
          .then(() => {
            // 刷新明细项目（已登记）
            this.dataTransOpts.refresh.register_check_asbitem.OnlyRefreshAsbitem++
          })
          .finally(() => {
            resolve()
          })
      })
    },


    //快速选择组合项目时，调整可按拼间简码及简称查找
    filterMethod(keyWords) {
      //// console.log('filterMethod',this.asbItemQuick)  
      if (keyWords) {
        this.nation = [];
        this.dict.nation.forEach(item => {
          if (item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
            || item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1) {
            this.nation.push(item);
          }
        });
      } else {
        this.nation = deepCopy(this.dict.nation);
      }
    },

    //选择单位，并返回顶级单位
    changeCustomerOrgId(v) {
      // 始终返回 reslove ，主要用于流程控制
      return new Promise((resolve, reject) => {
        console.log('changeCustomerOrgId', v, this.form.customerOrgParentId)
        let customerOrgId = "", customerOrgParentId = ""
        if (Array.isArray(v) && v.length > 0) {
          customerOrgId = v[v.length - 1]
        } else {
          customerOrgId = v  // 后台顶级单位ID未获取正确（再获取一次）       
        }
        // 保留之前预选的单位 if (!this.preCustomerOrgId) 
        this.preCustomerOrgId = customerOrgId

        this.getParentCustomerOrgId(v)
          .then(res => {
            if (res) {
              customerOrgParentId = res
              // 获取并设置体检次数（个人的固定 "00000000-0000-0000-0000-000000000001" ），单位刷新分组字典
              this.getCustomerOrgRegisterList(customerOrgParentId)
                .then(() => {
                  // 需要触发 修改 分组/套餐  顶级ID 没有变时，不改变套餐与分组   
                  if (customerOrgParentId != this.form.customerOrgParentId) {
                    this.form.customerOrgGroupId = null
                    this.form.medicalPackageId = null
                    // 清除套餐分组标识
                    this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
                      e.isBelongGroupPackage = 'N'
                    });

                    // 如果是个人，则清除分组字典
                    if (customerOrgParentId == this.dict.personOrgId) {
                      this.patientRegister.customerOrgGroup = []
                    }

                    if (this.form.customerOrgParentId == this.dict.personOrgId) {
                      this.changeMedicalPackageId()
                    } else {
                      this.changeCustomerOrgGroupId()
                    }
                  }
                  return resolve(customerOrgParentId)
                })
            } else {
              resolve(customerOrgParentId)
            }
          })
          .catch(() => {
            resolve(customerOrgParentId)
          })
      })
    },

    // 获取顶级单位ID
    getParentCustomerOrgId(v) {
      return new Promise((resolve, reject) => {
        let customerOrgParentId = null
        if (Array.isArray(v) && v.length > 0) {
          customerOrgParentId = v[0]
          return resolve(customerOrgParentId)
        } else {
          if (!v) {
            return resolve(customerOrgParentId)
          } else {
            if (v == this.dict.personOrgId) {
              return resolve(v)  // 等于个人体检时，则直接返回
            } else {
              getapi(`/api/app/customer-org/parent/${v}`)
                .then(res => {
                  if (res.code > -1) customerOrgParentId = res.data
                })
                .finally(() => {
                  return resolve(customerOrgParentId)
                })
            }

          }
        }
      })
    },

    //获取并设置体检次数（个人的固定 "00000000-0000-0000-0000-000000000001" ），单位刷新分组字典
    getCustomerOrgRegisterList(customerOrgParentId) {
      return new Promise((resolve, reject) => {
        if (customerOrgParentId == this.dict.personOrgId) {
          // 个人体检则 固定单位体检次数
          this.form.customerOrgRegisterId = "00000000-0000-0000-0000-000000000001"
          return resolve()
        } else {
          //获取单位体检次数信息
          getapi(`/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${customerOrgParentId}`)
            .then(res => {
              if (res.code > - 1) {
                // console.log('获取单位体检次数', this.form.customerOrgRegisterId, res.data)
                this.customerOrgRegisterList = res.data

                if (!this.form.customerOrgRegisterId || this.form.customerOrgRegisterId == "00000000-0000-0000-0000-000000000001") {
                  let customerOrgRegisterList = arrayFilter(res.data, 'isComplete', 'N')  //不显示已完成的体检次数
                  if (customerOrgRegisterList.length > 0) {
                    this.form.customerOrgRegisterId = customerOrgRegisterList[customerOrgRegisterList.length - 1].id
                  }
                }
                // /api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=${this.form.customerOrgRegisterId}
                this.patientRegister.customerOrgGroup = []
                if (this.form.customerOrgRegisterId && this.form.customerOrgRegisterId != '00000000-0000-0000-0000-000000000001') {
                  //获取单位分组
                  postapi('/api/app/CustomerOrgGroup/GetListForPatentRegisterByFilter', { customerOrgRegisterId: this.form.customerOrgRegisterId })
                    .then(res2 => {
                      if (res2 && res2.code != -1) {
                        this.patientRegister.customerOrgGroup = res2.data;
                      }
                    })
                } return
              }
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    //读取身份证信息
    peopleIcCard() {
      if (!this.$peisAPI) {
        this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
        return
      }
      this.$peisAPI.peopleIcCard().then(res => {
        // console.log('peopleIcCard', res)
        let lres = JSON.parse(res)
        if (lres.code >= -1) {
          let idNos = parsIcCardtoLocal(lres.data, this.dict.sex, this.dict.nation)
          this.form.patientName = idNos.Name
          this.form.birthDate = idNos.birthDate
          this.form.sexId = idNos.sexId
          this.form.age = idNos.age
          this.form.nationId = idNos.nationId
          this.form.idNo = idNos.IDCode
          this.form.address = idNos.Address
          this.peoplePhoto = 'data:image/bmp;base64,' + idNos.Photo
          // this.patientRegister.photo = 'data:image/bmp;base64,' + idNos.Photo

          this.changeIdNo() //  触发身份证查询档案号
        } else {
          this.$message.error({ showClose: true, message: `${lres.message}` })
        }
      })
    },

    // 分诊排队
    fnQueue(row) {
      this.queueParams = {
        patientRegisterId: row.id
      }
      this.dialogWin.queue = true
      this.dataTransOpts.plus.queue++
    },

    //修改单位体检次数
    changeMedicalTimes() {

      this.form.customerOrgGroupId = null
      this.changeCustomerOrgGroupId()

      //获取体检次数下的分组
      this.getCustomerOrgGroup(this.form.customerOrgRegisterId)
    },

    //移除旧分组或套餐的组合项目
    removeGroupPackageAsb() {
      let body = { registerAsbitemIds: [] }
      let registerAsbitemIds = []
      let chargeComplete = ''

      //体检基本信息未保存时，删除所有所选项目
      if (!this.form.id) {
        this.patientRegister.patientRegisterAbs = [];
        return body;
      }

      //删除已选 分组或套餐的组合项目 ，如已收费或 已检时，将 groupPackageId 置为null
      for (let i = 0; i < this.patientRegister.patientRegisterAbs.length; i++) {
        if (!this.patientRegister.patientRegisterAbs[i].id) {
          this.patientRegister.patientRegisterAbs.splice(i, 1)
          i--
          continue
        }
        if (this.patientRegister.patientRegisterAbs[i].isCharge == 'Y' || this.patientRegister.patientRegisterAbs[i].checkCompleteFlag != '0') {
          chargeComplete += this.patientRegister.patientRegisterAbs[i].asbitemName + '，'
          this.patientRegister.patientRegisterAbs[i].groupPackageId = null
        } else {
          //数据库有，才添加到待删除的数组中
          if (this.patientRegister.patientRegisterAbs[i].id) {
            registerAsbitemIds.push(this.patientRegister.patientRegisterAbs[i].id)
          }
          this.patientRegister.patientRegisterAbs.splice(i, 1)
          i--
        }
      }

      if (chargeComplete) {
        this.$message.info({ showClose: true, message: `所选项目：${chargeComplete}已收费或已检，不可删除！` });
      }

      body = { registerAsbitemIds };

      return body;

    },

    //添加新套餐/分组的组合项目
    addGroupPackageAsb(groupPackageAsb, typeFlag, groupPackageId) {

      let payTypeFlag = '0';  //默认个人支付
      let lfind = -1


      if (this.form.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'  //单位支付

      for (let i = 0; i < groupPackageAsb.length; i++) {
        lfind = arrayExistObj(this.patientRegister.patientRegisterAbs, 'asbitemId', groupPackageAsb[i].id)
        if (lfind > - 1) {
          this.patientRegister.patientRegisterAbs[lfind].groupPackageId = groupPackageId
          //editCount++
          continue
        }
        let pojo = {
          asbitemId: groupPackageAsb[i].id,
          asbitemName: groupPackageAsb[i].displayName,
          patientRegisterId: this.form.id,
          standardPrice: groupPackageAsb[i].price,
          chargePrice: typeFlag == 'group' ? groupPackageAsb[i].customerOrgGroupDetailPrice : groupPackageAsb[i].price,
          payTypeFlag,
          discount: typeFlag == 'group' ? groupPackageAsb[i].discount : 100,
          isCharge: "N",
          amount: typeFlag == 'group' ? groupPackageAsb[i].customerOrgGroupDetailAmount : 1,
          groupPackageId: groupPackageId
        }
        this.patientRegister.patientRegisterAbs.push(pojo)
      }
    },

    //获取体检次数下的分组
    getCustomerOrgGroup(customerOrgRegisterId) {
      this.patientRegister.customerOrgGroup = []
      // /api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=${customerOrgRegisterId}`
      postapi('/api/app/CustomerOrgGroup/GetListForPatentRegisterByFilter', { customerOrgRegisterId }).then(res => {
        if (res.code != - 1) {
          this.patientRegister.customerOrgGroup = res.data;
        }
      })
    },

    //修改出生日期
    changeBirthDate() {
      this.form.age = birthdayToAge(this.form.birthDate)
    },

    //修改出生日期
    changeAge() {
      this.form.birthDate = ageToBirthday(this.form.age)
    },

    //修改身份证，生成年龄、出生、性别
    changeIdNo() {
      if (!this.form.idNo) return
      this.Query(this.form.idNo)
      let ret = parseID(this.form.idNo)
      // console.log('changeIdNo',ret)
      if (ret.age != -1) {
        this.form.birthDate = new Date(ret.birthday)
        this.form.age = ret.age
        this.form.sexId = ret.sex
      }
    },

    // 输入名字时，查重
    changePatientName() {
      console.log('this.LocalConfig.patientRegister.findPatientByName', this.LocalConfig.patientRegister.findPatientByName)
      if (this.LocalConfig.patientRegister.findPatientByName) {
        this.Query(this.form.patientName)
      }
    },
    // //分组改变时触发
    changeCustomerOrgGroupId() {
      this.prAsbOpraOpts.prAsbGroup++
    },

    // //套餐改变时触发
    changeMedicalPackageId() {
      this.prAsbOpraOpts.prAsbPackage++
    },

    //根据姓名，身份证号 查询档案信息，用于判断人员多次体检
    Query(param) {
      this.patientChoosed = { id: '' }  // 清空之前的选择
      //编辑的时候不查重
      if (this.form.id || !param) return;

      //// console.log(`/api/app/patient/in-filter?Filter=${param}`)
      let body = {
        filter: param,
        maxResultCount: 500
      }

      this.patientList = []

      postapi('/api/app/patient/getlistinfilter', body).then((res) => {
        if (res.code > -1) {
          // console.log("查重 ", res); //有数据才显示
          if (res.data && res.data.length > 0) {
            this.patientList = res.data;
            this.dialogVisible = true;
          }
        }
      });

    },

    //列表选中
    rowick(row) {
      this.patientChoosed = row;
    },

    patientDblclick(row) {
      this.patientChoosed = row;
      this.choosePatient()
    },

    //确定选择人员
    choosePatient() {
      if (!this.patientChoosed.id) {
        this.$message.warning({ showClose: true, message: '请选择人员档案信息' })
        return;
      }

      this.dialogVisible = false;


      this.form.patientId = this.patientChoosed.id;
      this.form.patientNo = this.patientChoosed.patientNo;
      this.form.medicalTimes = this.patientChoosed.medicalTimes + 1;
      // 考滤录入有值，档案却无值
      if (this.patientChoosed.displayName) this.form.patientName = this.patientChoosed.displayName;
      if (this.patientChoosed.sexId) this.form.sexId = this.patientChoosed.sexId;
      if (this.patientChoosed.birthDate) this.form.birthDate = new Date(this.patientChoosed.birthDate);
      if (this.patientChoosed.nationId) this.form.nationId = this.patientChoosed.nationId;
      if (this.patientChoosed.idNo) this.form.idNo = this.patientChoosed.idNo;

      if (!this.form.maritalStatusId) this.form.maritalStatusId = this.patientChoosed.maritalStatusId;
      if (!this.form.telephone) this.form.telephone = this.patientChoosed.telephone;
      if (!this.form.mobileTelephone) this.form.mobileTelephone = this.patientChoosed.mobileTelephone;


      if (this.form.birthDate) {
        this.form.age = birthdayToAge(this.form.birthDate)
      }

      if (this.form.idNo) {
        let ret = parseID(this.form.idNo)
        this.form.birthDate = new Date(ret.birthday)
        this.form.age = ret.age
        this.form.sexId = ret.sex
      }

    },

    registerRowClick(row) {
      this.registerChoosed = row;
    },
    registerRowDblclick(row) {
      this.registerChoosed = row;
      this.chooseRegister()
    },

    chooseRegister() {
      if (!this.registerChoosed) {
        alert("请选中人员登记信息");
        return;
      }

      objCopy(this.registerChoosed, this.form)
      // this.patientRegister.patientRegisterId = this.registerChoosed.id
      // this.patientRegister.photo = this.registerChoosed.photo
      // this.getPatientRegisterAbs(this.registerChoosed.id)
      this.dataTransOpts.tableS.patient_register.id = this.registerChoosed.id
      setTimeout(() => {
        this.dataTransOpts.refresh.register_check_asbitem.M++
      }, 20);

      this.registerVisible = false

    },

    // 组装基本信息保存的参数体
    madePrBody() {
      //赋值

      let body = deepCopy(this.form);
      // // console.log('this.form',this.form)
      console.log('body', this.form, body)
      if (this.form.birthDate) {
        try {
          body.birthDate = moment(new Date(this.form.birthDate)).format("yyyy-MM-DD")
        } catch (error) {
          // this.form.birthDate != "Invalid date"
          body.birthDate = null
        }
      } else {
        body.birthDate = null
      }
      if (body.birthDate == "Invalid date") body.birthDate = null
      if (isNaN(body.age)) {
        body.age = null
      } else {
        body.age = Number(body.age)
      }
      // // console.log('body',body)
      // Invalid date

      delete body.registerManType;
      delete body.patientRegisterNo;
      delete body.medicalTimes;
      // delete body.completeFlag;
      delete body.isMedicalStart;
      delete body.patientNo;
      delete body.creatorId;
      delete body.creationTime;
      delete body.lastModificationTime;
      delete body.lastModifierId;
      delete body.isVipBox;
      delete body.isNameHideBox;
      delete body.isPhoneFollowBox;
      delete body.isLockBox;
      delete body.photo;

      // if(this.form.registerManType == 'customer') delete body.medicalStartDate;
      if (this.form.id) delete body.medicalStartDate;

      setNull(body, this.defaultNull);

      if (typeof this.form.customerOrgId == 'object') {
        if (this.form.customerOrgId.length > 0) body.customerOrgId = this.form.customerOrgId[this.form.customerOrgId.length - 1]
      }

      //日期转换 日期控件增加格式
      // // console.log("body.birthDate", body.birthDate);
      // if (body.birthDate) {
      //   body.birthDate = moment(new Date(body.birthDate)).format(
      //     "yyyy-MM-DD"
      //   );
      // }
      return body
    },

    // 验证职业病数据合法性
    validateOccData() {
      let err = ''
      if (!this.form.idNo) return "职业健康检查必须填写 身份证号！"
      if (this.form.maritalStatusId == '9') return "职业健康检查 婚姻不允许填未知！"
      if (this.form.sexId == 'U') return "职业健康检查 性别不允许填未知！"
      if (!this.form.ocCheckTypeId) return "职业健康检查必须填写 检查类别！"
      if (!this.form.jobType) return "职业健康检查必须填写 工种！"
      if (this.form.poisonIds == null || this.form.poisonIds.length == 0) return "职业健康检查必须填写 接害因素！"

      return err
    },

    //提交
    btnSubmit(formName, msgTip) {
      //console.log('btnSubmit,formName,form', formName, JSON.stringify(this.form))
      console.log('this.rules', this.rules)
      this.$refs[formName].validate((valid, fields) => {
        // console.log('fields', fields)
        if (!valid) {
          this.$message.warning({ showClose: true, message: fields[Object.keys(fields)[0]][0].message });
          return false
        }
        // 手机号必填时，再验证手机号是否合法
        if (this.rules['mobileTelephone']) {
          if (!isValidMobileNumber(this.form['mobileTelephone'])) {
            this.$message.warning({ showClose: true, message: '请填写正确的手机号！' });
            return false
          }
        }


        //console.log('btnSubmit1', formName)
        if (this.form.customerOrgId != this.dict.personOrgId) {
          if (!this.form.customerOrgRegisterId) {
            this.$message.warning({ showClose: true, message: "请填写单位体检次数！" });
            return false
          }
        }

        if (this.form.idNo && checkIDCode(this.form.idNo) == false) {
          this.$message.warning({ showClose: true, message: "身份证号填写不合法！" });
          return false
        }

        // 如果是职业病，数据验证
        if (this.form.isPatientOccupationalDisease == 'Y') {
          let message = this.validateOccData()
          if (message) {
            this.$message.warning({ showClose: true, message });
            return false
          }
        }

        // console.log('btnSubmit2', formName)

        let body = this.madePrBody()
        // console.log('madePrBody',body)
        body.registerCheckAsbitems = deepCopy(this.dataTransOpts.tableM.register_check_asbitem)

        if (this.form.id) {
          // 更新时，先保存明细，再更新主表
          // this.prAsbOpraOpts.prAsbSave++  //触发组合项目保存
          body.patientRegisterId = body.id;
        } else {
          delete body.id;
        }
        //console.log('btnSubmit3', formName)
        // // console.log(`/api/patientregister/createreturninfo`, body);

        // 保存前，判断是否有互斥项目
        this.checkAsbItemHC()
          .then(() => {
            return postapi(`/api/PatientRegister/CreatePatientRegister`, body)
          })
          .then(async (res) => {
            if (res.code > -1) {
              // 因为 res.data 返回的 isPatientOccupationalDisease 是错误的（因为职业病尚未保存，所以以form里的值为准）
              let isPatientOccupationalDisease = this.form.isPatientOccupationalDisease
              this.form = Object.assign({}, this.form, res.data, { isPatientOccupationalDisease })

              this.dataTransOpts.tableS.patient_register = deepCopy(res.data)

              delete this.dataTransOpts.tableS.patient_register.registerCheckAsbitems

              // 保存成功赋 id 值等
              this.dataTransOpts.tableM.register_check_asbitem = res.data.registerCheckAsbitems
              this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
                e.total = e.amount * e.chargePrice
              });

              //一般读身份证照片时，会出现这种情况
              if (this.peoplePhoto && this.peoplePhoto.indexOf("data:image") > -1) await savePeoplePhoto(res.data.id, this.peoplePhoto);

              // 如果是职业病，则保存职业病相关信息
              // console.log('this.form.isPatientOccupationalDisease', this.form.isPatientOccupationalDisease)
              if (this.form.isPatientOccupationalDisease == 'Y') {
                await this.occUpdate()
              }

              // 保存即发送收费申请 正式登记的才发送申请
              if (this.form.completeFlag != '0' && this.LocalConfig.patientRegister.immediateToHisCharge) {
                await this.immediateToHisCharge(this.form.id)
              }

              // 首次正式登记或者预登记转正式登记，提示打印条码与指引单
              if (this.completeFlag == '0' && this.form.completeFlag != '0') {
                if (Array.isArray(this.LocalConfig.patientRegister.printGuideLabel) && this.LocalConfig.patientRegister.printGuideLabel.length > 0) {
                  this.$confirm("是否打印 指引单、人员条码、检验条码及 Pacs 条码?", "提示", {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning",
                  })
                    .then(() => {
                      return this.labelPrint(false)
                    })
                    .then(res => {
                      return this.guidePrint('0001', false)
                    })
                    .catch((err) => {
                      if (err != "cancel") {
                        console.log(err)
                        this.$message.error({ showClose: true, message: err })
                      }
                    })
                    .finally(() => {
                      this.completeFlag = this.form.completeFlag
                    });
                }
              }
            }
          }
          )
          .catch(err => {
            console.error(err)
          })
          ;
      });
    },

    // 检查项目互斥
    checkAsbItemHC() {
      return new Promise((resolve, reject) => {
        let asbitemIds = []
        //console.log('this.dataTransOpts.tableM.register_check_asbitem',this.dataTransOpts.tableM.register_check_asbitem)
        this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
          asbitemIds.push(e.asbitemId)
        });

        let message = ''
        if (asbitemIds.length == 0) {
          resolve()
        } else {
          postapi('/api/app/AsbitemMutualExclusion/GetAsbitemIsMutualExclusion', { asbitemIds })
            .then(res => {
              if (res.code > -1) {
                if (res?.data?.message) message = res.data.message
              }
            })
            .finally(() => {
              if (message) {
                switch (this.hc_warn_mode) {
                  case '1':''
                    this.$confirm(`${message}  是否继续?`, "提示", {
                      confirmButtonText: "是",
                      cancelButtonText: "  否  ",
                      type: "warning",
                    })
                      .then(() => {
                        resolve()
                      })
                      .catch((err) => {
                        reject(message)
                        // if (err == "cancel") {
                        //   console.log("已取消删除");
                        // }
                      });
                    break;
                  case '2':
                    this.$message.error({ showClose: true, message })
                    reject(message)
                    break;
                  default:
                    this.$message.warning({ showClose: true, message })
                    resolve()
                    break;
                }
              } else {
                resolve()
              }
            })
        }
      })

    },

    // 保存职业病信息
    async occUpdate() {
      // 职业病基本信息
      let lriskFactors = []
      this.form.poisonIds.forEach(e => {
        lriskFactors.push(dddw(this.poisonList, 'id', e, 'displayName'))
      });

      let diseaseBase = {
        patientRegisterId: this.form.id,
        ocCheckTypeId: this.form.ocCheckTypeId,
        jobType: this.form.jobType,
        riskFactors: `${lriskFactors}`,
        occupationalDiseaseNumber: this.form.occupationalDiseaseNumber
      }

      // 职业病接害因素
      let poisons = this.dataTransOpts.tableM.patient_poison.filter(e => {
        return this.form.poisonIds.indexOf(e.poisonId) > - 1
      })
      this.form.poisonIds.forEach(e => {
        if (arrayExistObj(poisons, 'poisonId', e) == -1) {
          poisons.push({
            patientRegisterId: this.form.id,
            poisonId: e,
            occupationalAbnormalId: null
          })
        }
      });

      let patientOccupationalDisease = Object.assign({}, this.dataTransOpts.tableS.patient_occupational_disease || {}, diseaseBase)

      let body = {
        patientRegisterId: this.form.id,
        patientOccupationalDisease,
        patientPoisons: poisons,
        isPatientOccupationalDiseaseUpdate: "Y",  //基本信息
        isPatientPoisonsUpdate: "Y",  //接害因素        
        isPatientPastMedicalHistorysUpdate: "N", // 既往病史
        isPatientOccupationalMedicalHistorysUpdate: "N", // 职业病史
        isPatientOccupationalHistorysUpdate: "N", // 职业史
        isPatientSymptomsUpdate: "N", // 症状                    
      }
      try {
        await postapi('/api/app/OccupationalDisease/CreateOccupationalDiseaseWithDetail', body)
        this.getOccDiseaseData()
      } catch (error) {
        console.log('occUpdate error', error)
      }
    },

    // 获取职业病信息
    getOccDiseaseData() {
      return new Promise((resolve, reject) => {
        let patientRegisterId = this.form.id
        postapi('/api/app/OccupationalDisease/GetOccupationalDiseaseWithDetailByPatientRegisterId', { patientRegisterId })
          .then(res => {
            if (res.code > -1) {
              if (res.data['patientOccupationalDisease'] == null) {
                this.dataTransOpts.tableS.patient_occupational_disease = { patientRegisterId }
              } else {
                this.dataTransOpts.tableS.patient_occupational_disease = deepCopy(res.data['patientOccupationalDisease'])
              }
              this.dataTransOpts.tableM.patient_poison = deepCopy(res.data['patientPoisonDtos'])
              this.form.ocCheckTypeId = this.dataTransOpts.tableS.patient_occupational_disease.ocCheckTypeId
              this.form.jobType = this.dataTransOpts.tableS.patient_occupational_disease.jobType
              this.form.occupationalDiseaseNumber = this.dataTransOpts.tableS.patient_occupational_disease.occupationalDiseaseNumber
              let poisonIds = []  // 接害因素IDs
              this.dataTransOpts.tableM.patient_poison.forEach(e => {
                poisonIds.push(e.poisonId)
              });
              this.form.poisonIds = poisonIds
              resolve('')
            } else {
              reject(res.message)
            }
          })
          .catch(error => {
            reject(error)
          })
      })

    },

    // 列表数据生成 分组 select
    madeSelectGroup(poisonList) {
      let poison = []
      poisonList.forEach(e => {
        let lfind = arrayExistObj(poison, "poisonTypeName", e.poisonTypeName)
        if (lfind == -1) {
          poison.push({ poisonTypeName: e.poisonTypeName, poisonDtos: [{ id: e.id, displayName: e.displayName, simpleCode: e.simpleCode }] })
        } else {
          poison[lfind]['poisonDtos'].push({ id: e.id, displayName: e.displayName, simpleCode: e.simpleCode })
        }
      });
      return poison
    },

    filterMethodPoison(v) {
      // console.log('this.poisonList',v,this.poisonList)
      if (v) {
        let lv = v.toUpperCase()

        let poisonList = this.poisonList.filter(e => {
          return e.poisonTypeName.indexOf(lv) > -1 || e.displayName.indexOf(lv) > -1 || e.simpleCode.indexOf(lv) > -1
        })

        this.poison = this.madeSelectGroup(poisonList)
      } else {
        this.poison = this.madeSelectGroup(this.poisonList)
      }
      console.log('filterMethod', this.poison)
    },

    // 人员新增
    btnAdd() {
      this.dataTransOpts.tableS.patient_register.id = ''
      this.dataTransOpts.refresh.patient_register.S++
    },

    //将现有的数据，复制并展现，但未保存
    rdCopy() {
      if (!this.form.id) {
        this.$message.info({ showClose: true, message: "该信息尚未保存，不可执行此操作！" });
        return;
      }
      this.dataTransOpts.tableS.patient_register.id = ''
      this.peoplePhoto = '/pic/Photo.jpg'
      this.patientRegister.patientRegisterId = '';
      this.form.id = '';
      this.form.patientId = '00000000-0000-0000-0000-000000000000';
      this.form.patientRegisterNo = '';
      this.form.patientNo = '';
      this.form.medicalTimes = 1;
      this.form.patientName = '';
      this.form.photo = '';
      this.form.completeFlag = '1';  //
      this.form.planuserid = '' //清除青藏公司的计划ID

      // this.patientRegister.patientRegisterAbs.forEach(e => {
      //   e.id = '';
      //   e.patientRegisterId = '';
      //   e.isCharge = 'N';
      //   e.checkCompleteFlag = '0'
      //   e.isLock = 'N'
      // });

      // 触发明细项目复制
      // setTimeout(() => {
      //   this.prAsbOpraOpts.copyNew++
      // }, 10);
      this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
        delete e.id
        e.patientRegisterId = ''
        e.isCharge = 'N'
        e.isLock = 'N'
        e.checkCompleteFlag = '0'
      });
      // // console.log('this.patientRegister.patientRegisterAbs',this.patientRegister.patientRegisterAbs)

      this.$message.warning({ showClose: true, message: "操作成功，请记得点保存" });

    },

    //删除
    del() {
      deletapi(
        `/api/app/customer-org/${this.customerOrg.customerOrgRd.id}`
      ).then((res) => {
        // console.log("删除 操作成功");
        this.setData({ key: "customerOrg.customerOrgRd", value: { id: "" } });
        this.getCustomerOrgTree();
      });
    },

    // 同步团检人员网上添加项目信息
    btnDownOrg() {
      postapi("/api/app/ThirdInterface/GetListByThirdInterfaceTypeAsync", { thirdInterfaceType: "07" })
        .then(res => {
          if (res.code > -1 && res.data && Array.isArray(res.data) && res.data.length > 0) {
            this.thirdInterfaceId = res.data[0].id
            return postapi('/api/app/AppointPatientRegister/GetByPatientRegisterId', { thirdInterfaceId: this.thirdInterfaceId, appointPatientRegisterId: '1', patientRegisterId: this.form.id })
          }
        })
        .then(res => {
          if (res && res.code > -1) {
            this.form.appointPatientRegisterId = res.data.appointPatientRegisterId
            return postapi('/api/app/AppointPatientRegister/GetAppointRegisterAsbitemListById', {
              thirdInterFaceId: this.thirdInterfaceId,
              appointPatientRegisterId: res.data.appointPatientRegisterId
            })
          }
        })
        .then(res => {
          if (res && res.code > -1) {
            res.data.forEach(e => {
              e.discount = e.standardPrice == 0 ? 100 : Math.floor(e.chargePrice * 10000 / e.standardPrice) / 100
              if (!e.isBelongGroupPackage) {
                e.isBelongGroupPackage = e.isInMedicalPackage
              }
              // e.standTotal = e.amount * e.standardPrice
              e.total = e.amount * e.chargePrice
            });
            this.dataTransOpts.tableM.register_check_asbitem = deepCopy(res.data)
            this.$message.success({ showClose: true, message: '操作成功！' })
          }
        })
    },
    //拍照（已废弃）
    // openCamera() {
    //   if (!this.form.id) {
    //     alert("请先保存人员信息");
    //     return;
    //   }
    //   this.patientRegister.cameraVisble = true;
    // },

    //拍照（调壳程序）
    photoGrah() {
      if (!this.form.id) {
        alert("请先保存人员信息");
        return;
      }
      if (!this.$peisAPI) {
        this.$message.info({ showClose: true, message: "此功能，需要在壳客户端才可运行！" })
        return
      }
      this.$peisAPI.photoGrah()
        .then(res => {
          // console.log('this.$peisAPI.photoGrah 原始返回结果', res)
          let lres = JSON.parse(res)
          if (lres.code > -1) {
            let uploadPhoto = {
              patientRegisterId: this.form.id,
              photo: lres.data.Photo,
            };
            this.peoplePhoto = `data:image/${lres.data.PhotoFormat == 'jpg' ? 'jpeg' : lres.data.PhotoFormat};base64,${lres.data.Photo}`
            // this.patientRegister.photo = `data:image/${lres.data.PhotoFormat == 'jpg' ? 'jpeg' : lres.data.PhotoFormat};base64,${lres.data.Photo}`
            return postapi(`/api/app/patient-register/up-load-img`, uploadPhoto)
          } else {
            this.$message.error({ showClose: true, message: "上传照片错误" + lres.code })
          }
        }).then(res => {
          if (res && res.code > -1) {
            let body = {
              patientRegisterId: this.form.id,
              photo: res.data,
            };
            // console.log(body);
            return postapi(`/api/app/patient-register/update-photo`, body);
          }
        }).then(res => {
          if (res && res.code > -1) {
            //// console.log('拍照',res.data)
            this.patientRegister.patientRegisterRd.photo = res.data.photo
            // console.log("操作成功");
          }
        }).catch(err => {
          // console.log('this.$peisAPI.photoGrah', err)
          this.$message.error({ showClose: true, message: `照片操作错误 ${err}` })
        })
    },

    getPeoplePhoto(photo) {
      this.peoplePhoto = photoParse(photo)
    },

    // 打印指引单(isPreview)
    guidePrint(ReportCode, isPreview) {
      return new Promise((resolve, reject) => {
        if (!this.form.id) {
          reject("人员信息尚未保存，不可执行此操作！")
        }
        if (this.form.completeFlag == '0') {
          reject("预登记人员，不可执行此操作！")
        }
        if (!this.$peisAPI) {
          reject("此功能，需要在壳客户端才可运行！")
        }

        let token = window.sessionStorage.getItem('token');
        let user = window.sessionStorage.getItem('user');
        let toOutShell = {
          ReportCode, token,
          isBuildImage: 'N',
          IsUploadPdf: 'N',
          preViewCanPrint: 'N',
          BusinessCode: this.form.id,
          Parameters: [
            { Name: 'printer', Value: user },
            { Name: 'hisLog', Value: 'pic/hisLog.jpg' },
            { Name: 'pageFooter', Value: 'pic/peisQrCode.jpg' },
          ],
        };
        console.log('this.$peisAPI.print', JSON.stringify(toOutShell))
        this.printing = true
        if (isPreview) {
          this.$peisAPI.printPre(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                reject(JSON.parse(res).message)
              } else {
                resolve(res)
              }
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else {
          this.$peisAPI.print(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                reject(JSON.parse(res).message)
              } else {
                return postapi('/api/app/patientregister/updatepatientregisterguideprinttimesmany', [this.form.id])
              }
            })
            .then(res => {
              if (res && res.code > -1) {
                let lfind = arrayExistObj(this.patientRegister.prList, 'id', this.form.id)
                if (lfind > -1) {
                  if (this.patientRegister.prList[lfind].guidePrintTimes) {
                    this.patientRegister.prList[lfind].guidePrintTimes = Number(this.patientRegister.prList[lfind].guidePrintTimes) + 1;
                  } else {
                    this.patientRegister.prList[lfind].guidePrintTimes = 1;
                  }
                }
                resolve(res)
              } else {
                reject("更新指引单打印错误")
              }
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        }
      })
    },

    //检验申请
    async lisRequest() {
      this.$message.warning({ showClose: true, message: '此功能已合并到条码打印' });
      /*
      let isPrintLisRequest = false
      let res = null
      if (this.form.id.length < 1) {
        this.$message.info({ showClose: true, message: "人员信息尚未保存，不可执行此操作！"});
        return;
      }
  
      try {
        res = await postapi(`/api/app/lisrequest/setlisrequest?PatientRegisterId=${this.form.id}`);
        // console.log(`/api/app/lisrequest/setlisrequest?PatientRegisterId=${this.form.id}`, res)
      } catch (error) {
        return;
      }
      if (res.code > -1) {
        // this.$message.info("发送检验申请成功！");
        isPrintLisRequest = true;
      }
  
      //重复申请，重打
      if (res.code == -1 && res.message.indexOf('已申请') > -1) {
        isPrintLisRequest = true;
      }
  
      if (!isPrintLisRequest) return;
  
      try {
        await this.$confirm("是否打印检验申请单?", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "info",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        });
      } catch (error) {
        return;
      }
      //打印检验申请单
      this.lisPrint('0003', false);
      */
    },

    //条码打印(lis + pacs)
    labelPrint(isPreview) {
      return new Promise((resolve, reject) => {
        if (!this.form.id) {
          reject("人员信息尚未保存，不可执行此操作！");
        }
        if (this.form.completeFlag == '0') {
          reject("预登记人员，不可执行此操作！");
        }
        if (!this.$peisAPI) {
          reject("此功能，需要在壳客户端才可运行！");
        }

        let token = window.sessionStorage.getItem('token');
        let user = window.sessionStorage.getItem('user');
        let toOutShell = {
          token, // ReportCode, 
          IsMoreLabel: 'Y',
          isBuildImage: 'N',
          IsUploadPdf: 'N',
          BusinessCode: this.form.id,
          Parameters: [
            { Name: 'printer', Value: user },
            { Name: 'hisLog', Value: 'pic/hisLog.jpg' },
            { Name: 'pageFooter', Value: 'pic/peisQrCode.jpg' }
          ],
        };

        this.printing = true
        if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('patient') > -1 && this.LocalConfig.patientRegister.printGuideLabel.indexOf('lis') > -1 && this.LocalConfig.patientRegister.printGuideLabel.indexOf('pacs') > -1) {
          if (this.merge_lis_pacs_label == '1') {
            this.guidePrintEasy('0008', isPreview, toOutShell)
              .then(res => {
                return this.lisPrint('0002', isPreview, toOutShell)
              })
              // .then(res => {
              //   return this.pacsPrint('0004', isPreview, toOutShell)
              // })
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
              .finally(() => {
                this.printing = false
              })
          } else {
            this.guidePrintEasy('0008', isPreview, toOutShell)
              .then(res => {
                return this.lisPrint('0002', isPreview, toOutShell)
              })
              .then(res => {
                return this.pacsPrint('0004', isPreview, toOutShell)
              })
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
              .finally(() => {
                this.printing = false
              })
          }

        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('patient') > -1 && this.LocalConfig.patientRegister.printGuideLabel.indexOf('lis') > -1) {
          this.guidePrintEasy('0008', isPreview, toOutShell)
            .then(res => {
              return this.lisPrint('0002', isPreview, toOutShell)
            })
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('patient') > -1 && this.LocalConfig.patientRegister.printGuideLabel.indexOf('pacs') > -1) {
          this.guidePrintEasy('0008', isPreview, toOutShell)
            .then(res => {
              return this.pacsPrint('0004', isPreview, toOutShell)
            })
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('lis') > -1 && this.LocalConfig.patientRegister.printGuideLabel.indexOf('pacs') > -1) {
          if (this.merge_lis_pacs_label == '1') {
            this.lisPrint('0002', isPreview, toOutShell)
              // .then(res => {
              //   return this.pacsPrint('0004', isPreview, toOutShell)
              // })
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
              .finally(() => {
                this.printing = false
              })
          } else {
            this.lisPrint('0002', isPreview, toOutShell)
              .then(res => {
                return this.pacsPrint('0004', isPreview, toOutShell)
              })
              .then(res => {
                resolve(res)
              })
              .catch(err => {
                reject(err)
              })
              .finally(() => {
                this.printing = false
              })
          }
        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('patient') > -1) {
          this.guidePrintEasy('0008', isPreview, toOutShell)
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('lis') > -1) {
          this.lisPrint('0002', isPreview, toOutShell)
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else if (this.LocalConfig.patientRegister.printGuideLabel.indexOf('pacs') > -1) {
          this.pacsPrint('0004', isPreview, toOutShell)
            .then(res => {
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
            .finally(() => {
              this.printing = false
            })
        } else {
          this.printing = false
          resolve("success")
        }
      })
    },

    // lis条码打印 
    guidePrintEasy(ReportCode, isPreview, toOutShell) {
      return new Promise((resolve, reject) => {
        toOutShell.ReportCode = ReportCode
        console.log('this.$peisAPI.print', JSON.stringify(toOutShell))

        if (isPreview) {
          this.$peisAPI.printPre(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                // this.$message.warning({ showClose: true, message: JSON.parse(lres).message });
                reject(JSON.parse(res).message)
              } else {
                resolve(res)
              }
            })
            .catch(err => {
              reject(err)
            })
        } else {
          this.$peisAPI.print(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                reject(JSON.parse(res).message)
              } else {
                return postapi('/api/app/patientregister/updatepatientregisterguideprinttimesmany', [this.form.id])
              }
            })
            .then(res => {
              if (res && res.code > -1) {
                let lfind = arrayExistObj(this.patientRegister.prList, 'id', this.form.id)
                if (lfind > -1) {
                  if (this.patientRegister.prList[lfind].guidePrintTimes) {
                    this.patientRegister.prList[lfind].guidePrintTimes = Number(this.patientRegister.prList[lfind].guidePrintTimes) + 1;
                  } else {
                    this.patientRegister.prList[lfind].guidePrintTimes = 1;
                  }
                }
                resolve(res)
              } else {
                reject(res.message)
              }
            })
            .catch(err => {
              reject(err)
            })
        }
      })
    },

    // lis条码打印 
    lisPrint(ReportCode, isPreview, toOutShell) {
      return new Promise((resolve, reject) => {
        toOutShell.ReportCode = ReportCode
        console.log('this.$peisAPI.print', JSON.stringify(toOutShell))

        if (isPreview) {
          this.$peisAPI.printPre(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                // this.$message.warning({ showClose: true, message: JSON.parse(lres).message });
                reject(JSON.parse(res).message)
              } else {
                resolve(res)
              }
            })
            .catch(err => {
              reject(err)
            })
        } else {
          this.$peisAPI.print(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                reject(JSON.parse(res).message)
              } else {
                return postapi('/api/app/lisrequest/updatelisrequestisprint', { operateType: 1, patientRegisterId: this.form.id })
              }
            })
            .then(res => {
              if (res && res.code < 0) {
                reject(res.message)
              } else {
                resolve(res)
              }
            })
            .catch(err => {
              reject(err)
            })
        }
      })
    },

    //pacs条码打印
    pacsPrint(ReportCode, isPreview, toOutShell) {
      return new Promise((resolve, reject) => {
        toOutShell.ReportCode = ReportCode
        console.log('this.$peisAPI.print', JSON.stringify(toOutShell))
        if (isPreview) {
          this.$peisAPI.printPre(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                // this.$message.warning({ showClose: true, message: JSON.parse(res).message });
                reject(JSON.parse(res).message)
              } else {
                resolve(res)
              }
            })
            .catch((err) => {
              // console.log('打印pacs条码错误', err)
              this.$message.warning({ showClose: true, message: `${err}` });
              reject(err)
            });
        } else {
          this.$peisAPI.print(JSON.stringify(toOutShell))
            .then(res => {
              if (JSON.parse(res).code < 0) {
                // this.$message.warning({ showClose: true, message: JSON.parse(res).message });
                reject(JSON.parse(res).message)
              } else {
                return postapi("/api/app/lisrequest/updatelisrequestisprint", {
                  operateType: 1,
                  patientRegisterId: this.form.id,
                });
              }
            })
            .then(res => {
              if (res && res.code < 0) {
                // this.$message.error({ showClose: true, message: `${res.message}` });
                reject(res.message)
              } else {
                resolve(res)
              }
            })
            .catch((err) => {
              // console.log('打印pacs条码错误', err)
              // this.$message.error({ showClose: true, message: `${err}` });
              reject(err)
            });
        }
      });
    },

    //补打条码
    reLisRequest() {
      if (!this.form.id) {
        this.$message.info({ showClose: true, message: "人员信息尚未保存，不可执行此操作！" });
        return;
      }
      if (this.form.completeFlag == '0') {
        this.$message.info({ showClose: true, message: "预登记人员，不可执行此操作！" });
        return;
      }
      this.brushTimes++;
      this.patientRegister.lisRequestVisble = true;
    },

    //手动合并项目
    reMergeAsbitem() {
      if (this.form.id.length < 1) {
        this.$message.info({ showClose: true, message: "人员信息尚未保存，不可执行此操作！" });
        return;
      }
      this.brushTimes++;
      this.patientRegister.mergeAsbitemVisble = true;
    },

    btnPayTypeFlag(payTypeFlag) {
      this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
        if (e.isCharge == 'N') e.payTypeFlag = payTypeFlag
      });
    },

    // 刷新登记的检查项目
    getAsb(id) {
      return new Promise((resolve, reject) => {
        getapi(`/api/app/registerasbitem/getlistinpatientregisterid?PatientRegisterId=${id}`)
          .then(res => {
            if (res.code > - 1) {
              this.dataTransOpts.tableM.register_check_asbitem = res.data
              resolve()
            } else {
              reject(res.message)
            }
          })
          .catch(err => {
            reject(err.message)
          })
      })

    },

    // 跳至收费页面
    toCharge(form) {

      if (!form.patientRegisterNo) {
        this.$message.warning({ showClose: true, message: "请先保存人员信息！" })
        return
      }
      if (form.completeFlag == '0') {
        this.$message.warning({ showClose: true, message: "预登记的人员不可执行此操作！" })
        return
      }

      this.getAsb(form.id)
        .then(() => {
          let chargeMoney = Number(0)
          //支付方式,比如是0自费、2免费、1单位支付
          this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
            if (e.payTypeFlag == '0') chargeMoney += Number(e.total)
          });
          if (chargeMoney == 0) {
            this.$message.warning({ showClose: true, message: '没有可收费或退费的记录！' })
          } else {
            //多次重复点击时，刷新处理
            this.chargePatientRegisterNo = form.patientRegisterNo
            //this.dataTransOpts.refresh.charge.S++
            this.dialogWin.charge = true
            this.dataTransOpts.refresh.charge.S++
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },

    // 收费申请
    chargeRequest(form) {
      if (!form.id) {
        this.$message.warning({ showClose: true, message: "请先保存人员信息！" })
        return
      }
      if (form.completeFlag == '0') {
        this.$message.warning({ showClose: true, message: "预登记的人员不可执行此操作！" })
        return
      }


      this.getAsb(form.id)
        .then(() => {
          let chargeMoney = Number(0)
          //支付方式,比如是0自费、2免费、1单位支付
          this.dataTransOpts.tableM.register_check_asbitem.forEach(e => {
            if (e.payTypeFlag == '0') chargeMoney += Number(e.total)
          });

          if (chargeMoney == 0) {
            this.$message.warning({ showClose: true, message: '没有可收费或退费的记录！' })
          } else {
            // 显示
            this.dataTransOpts.refresh.charge.S++
            this.dialogWin.AsbChargeRequest = true
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },

    // 保存立即发送收费申请
    immediateToHisCharge(patientRegisterId) {
      postapi('/api/app/registerasbitem/GetCanChargeAsbitemsByPatientRegisterId', { patientRegisterId })
        .then(res => {
          if (res.code > -1 && res.data.length > 0) {
            let body = {
              patientRegisterId,
              registerCheckAsbitems: []
            }

            res.data.forEach(e => {
              body.registerCheckAsbitems.push({ registerCheckAsbitemId: e.registerCheckAsbitemId })
            });

            // 向 His 或 其他第三方 推送收费申请
            postapi("/api/app/ChargeRequest/Create", body)
              .then(resCharge => {
                if (resCharge.code > -1) {
                  this.dataTransOpts.refresh.patient_register.S++
                }
              })
          }
        })
        .catch(error => {
          this.$message.error({ showClose: true, message: error.message })
        })
    },

    //关闭收费窗口时，刷新收费状态信息
    closeDialogCharge() {
      // this.prAsbOpraOpts.prAsbQuery++
      this.dataTransOpts.refresh.patient_register.S++
      // this.dataTransOpts.refresh.register_check_asbitem.D++
    },


    // 新增保存基本信息产生新的ID，等明细保存后，再更新表单form.id
    refreshFormId() {
      // console.log('refreshFormId', this.prAsbOpraOpts.formId)
      this.form.id = this.prAsbOpraOpts.formId
      this.prAsbOpraOpts.formId = '' //清空

      /**/
      // this.patientRegister.prList.push(res.data);  //列表添加记录
      this.patientRegister.patientRegisterId = this.form.id;
      objCopy(this.form, this.patientRegister.patientRegisterRd);

      //this.patientRegister.query.times++; 不在触发列表查询（换成局部刷新）放在窗口关闭事件中去
      // let curRow = deepCopy(this.patientRegister.patientRegisterRd)
      // curRow.index = this.patientRegister.prList.length
      // this.patientRegister.prList.push(curRow)      
    },

    // 显示职业病
    btnOcc() {
      if (!this.form.id) {
        this.$message.warning({ showClose: true, message: '人员信息尚未保存！' })
        return
      }
      this.dataTransOpts.plus.OccDisease++
      this.dialogWin.OccDisease = true
    },

    // 获取接害因素 + 检查类别 的组合项目 后，刷新当前组合项目 
    changeOccPosionOrCheckType() {
      this.getOccAsbitems().then(res => {
        let lfind = 0
        for (let i = this.dataTransOpts.tableM.register_check_asbitem.length - 1; i >= 0; i--) {
          let e = this.dataTransOpts.tableM.register_check_asbitem[i];
          if (e.isCharge == 'Y' || e.checkCompleteFlag != '0') {
            continue
          } else {
            // 已登记的项目 在 this.occAsbitems 中，则不删除 （如果删除的话，条码会变）
            lfind = arrayExistObj(this.occAsbitems, 'id', e.asbitemId)
            if (lfind == -1) this.dataTransOpts.tableM.register_check_asbitem.splice(i, 1)
          }
        }

        lfind = 0
        let payTypeFlag = '1';  //职业病 默认单位支付
        if (this.form.customerOrgId == this.dict.personOrgId) payTypeFlag = '0'  //个人支付
        this.occAsbitems.forEach(e => {
          lfind = arrayExistObj(this.dataTransOpts.tableM.register_check_asbitem, 'asbitemId', e.id)
          if (lfind == -1) {
            this.dataTransOpts.tableM.register_check_asbitem.push({
              asbitemId: e.id,
              asbitemName: e.displayName,
              patientRegisterId: this.form.id,
              standardPrice: e.price,
              chargePrice: e.ocCheckTypeDetailPrice,
              payTypeFlag,
              isCharge: "N",
              checkCompleteFlag: '0',
              discount: e.price == 0 ? 100 : Math.floor(10000 * e.ocCheckTypeDetailPrice / e.price) / 100,
              amount: e.ocCheckTypeDetailAmount,
              total: e.ocCheckTypeDetailAmount * e.ocCheckTypeDetailPrice,
              standTotal: e.ocCheckTypeDetailAmount * e.price
            })
          }
        });

      })
    },

    // 获取接害因素 + 检查类别 的组合项目
    getOccAsbitems() {
      return new Promise((resolve, reject) => {
        if (!this.form.ocCheckTypeId || this.form.poisonIds.length == 0) {
          this.occAsbitems = []
          resolve(this.occAsbitems)
        } else {
          let body = {
            ocCheckTypeId: this.form.ocCheckTypeId,
            poisonIds: this.form.poisonIds
          }
          postapi('/api/app/OcCheckTypeDetail/GetOcCheckTypeDetailByOcCheckTypeIdAndPoisonId', body).then(res => {
            if (res.code > -1) {
              this.occAsbitems = res.data
              resolve(this.occAsbitems)
            } else {
              reject(res.message)
            }
          })
            .catch(err => {
              reject(err)
            })
        }
      })
    },


    // 显示预约
    btnWebBooking() {

      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []

      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []

      this.dataTransOpts.plus.WebBooking++
      this.dialogWin.WebBooking = true
    },

    // 显示预约
    btnWebBookingMzak() {

      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []

      this.dataTransOpts.tableS.appoint_patient_register = {}
      this.dataTransOpts.tableM.appoint_register_asbitem = []

      this.dataTransOpts.plus.WebBookingMzak++
      this.dialogWin.WebBookingMzak = true
    },

    // 关闭预约窗口
    close_dialogWin_WebBooking() {
      // console.log('this.dataTransOpts.tableS.appoint_patient_register',this.dataTransOpts.tableS.appoint_patient_register)
      // console.log('this.dataTransOpts.tableM.appoint_register_asbitem',this.dataTransOpts.tableM.appoint_register_asbitem)
      // 没有选中网上预约记录，直接返回，不做任何处理
      let appoint_patient_register = this.dataTransOpts.tableS.appoint_patient_register
      if (!appoint_patient_register.appointPatientRegisterId) return



      // 新增 (个人预约只登记个人的)
      this.dataTransOpts.tableS.patient_register.id = ''
      this.preCustomerOrgId = this.dict.personOrgId
      this.patientRegister.query.customerOrgId = this.dict.personOrgId
      this.patientRegister.query.CustomerOrgParentId = this.dict.personOrgId
      this.form.customerOrgId = [this.dict.personOrgId] //单位编号 默认个人       
      this.form.customerOrgParentId = this.dict.personOrgId
      this.form.customerOrgRegisterId = "00000000-0000-0000-0000-000000000001" //默认单位体检次数

      // "appointPatientRegisterId": "string",
      // "personId": "string",
      // "personName": "string",
      // "idNo": "string",
      // "sexId": "string",
      // "sexName": "string",
      // "maritalStatusId": "string",
      // "maritalStatusName": "string",
      // "customerOrgId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      // "customerOrgName": "string",
      // "childCustomerOrgName": "string",
      // "customerOrgGroupId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      // "customerOrgGroupName": "string",
      // "medicalPackageId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      // "medicalPackageName": "string",
      // "completeFlag": "string",
      // "appointDate": "2024-06-09T11:46:34.962Z",
      // "remark": "string",
      // "medicalCenterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      // "customerOrgRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      // "pregnantFlag": "string",
      // "pregnantFlagName": "string",
      // "height": 0,
      // "weight": 0
      this.initFormData(this.dataTransOpts.tableS.patient_register.id)
        .then(() => {
          delete appoint_patient_register.medicalCenterId
          Object.assign(this.form, appoint_patient_register,
            {
              patientName: appoint_patient_register.personName,
              completeFlag: '1',
            }
          )

          console.log('this.form', JSON.stringify(this.form))
          // 明细必填项
          // "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "asbitemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "standardPrice": 0,
          // "chargePrice": 0,
          // "payTypeFlag": "string",
          // "isCharge": "string",
          // "amount": 0

          // 预约明细数据
          // "appointRegisterAsbitemId": "00000000-0000-0000-0000-000000000000",
          // "asbitemId": "3a126b34-f6f0-56a1-e899-a092874acde7",
          // "asbitemName": "腹部平片(立位）",
          // "itemTypeId": "3a126ac6-2fbf-ca50-82a4-73dcc5a5028b",
          // "itemTypeName": "放射科",
          // "appointPatientRegisterId": "3a12ebf4-565a-dbc4-4f2d-d72cd3050cab",
          // "standardPrice": 45.00,
          // "chargePrice": 30.50,
          // "payTypeFlag": "\u0000",
          // "isCharge": "N",
          // "amount": 1,
          // "isInMedicalPackage": "N",
          // "itemTypeDisplayOrder": 28,
          // "displayOrder": 1
          this.dataTransOpts.tableM.register_check_asbitem = deepCopy(this.dataTransOpts.tableM.appoint_register_asbitem)

          this.changeIdNo() //  触发身份证查询档案号
        })

    },

    // 关闭预约窗口--人寿 （团检、个人都可以）
    close_dialogWin_WebBookingMzak() {
      // console.log('this.dataTransOpts.tableS.appoint_patient_register',this.dataTransOpts.tableS.appoint_patient_register)
      // console.log('this.dataTransOpts.tableM.appoint_register_asbitem',this.dataTransOpts.tableM.appoint_register_asbitem)
      // 没有选中网上预约记录，直接返回，不做任何处理
      let appoint_patient_register = this.dataTransOpts.tableS.appoint_patient_register
      if (!appoint_patient_register.thirdBookingId) return

      this.dataTransOpts.tableS.patient_register.id = ''
      // this.preCustomerOrgId = this.dict.personOrgId
      this.patientRegister.query.customerOrgId = appoint_patient_register.customerOrgId
      this.patientRegister.query.CustomerOrgParentId = appoint_patient_register.customerOrgId
      this.form.customerOrgId = [appoint_patient_register.customerOrgId] //单位编号 默认个人  

      let customerOrgParentId = ''
      this.getParentCustomerOrgId(appoint_patient_register.customerOrgId)
        .then(res => {
          customerOrgParentId = res
          this.form.customerOrgParentId = customerOrgParentId
          return this.initFormData(this.dataTransOpts.tableS.patient_register.id)
        })
        .then(() => {
          //  this.form.customerOrgName = customerOrgParentId
          // "appointPatientRegisterId": "string",
          // "personId": "string",
          // "personName": "string",
          // "idNo": "string",
          // "sexId": "string",
          // "sexName": "string",
          // "maritalStatusId": "string",
          // "maritalStatusName": "string",
          // "customerOrgId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "customerOrgName": "string",
          // "childCustomerOrgName": "string",
          // "customerOrgGroupId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "customerOrgGroupName": "string",
          // "medicalPackageId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "medicalPackageName": "string",
          // "completeFlag": "string",
          // "appointDate": "2024-06-09T11:46:34.962Z",
          // "remark": "string",
          // "medicalCenterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "customerOrgRegisterId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "pregnantFlag": "string",
          // "pregnantFlagName": "string",
          // "height": 0,
          // "weight": 0
          delete appoint_patient_register.medicalCenterId
          Object.assign(this.form, appoint_patient_register,
            {
              patientName: appoint_patient_register.personName,
              completeFlag: '1',
            }
          )

          // 人寿接口，甲方需求：岗位数据导入人员类别
          // personnelTypeId   --> positionName
          // dict.personnelType" :key="item.id" :label="item.displayName" 
          let lfind = arrayExistObj(this.dict.personnelType, 'displayName', appoint_patient_register.positionName)
          if (lfind > -1) this.form.personnelTypeId = this.dict.personnelType[lfind].id


          console.log('this.form', JSON.stringify(this.form))
          // 明细必填项
          // "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "asbitemId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          // "standardPrice": 0,
          // "chargePrice": 0,
          // "payTypeFlag": "string",
          // "isCharge": "string",
          // "amount": 0

          // 预约明细数据
          // "appointRegisterAsbitemId": "00000000-0000-0000-0000-000000000000",
          // "asbitemId": "3a126b34-f6f0-56a1-e899-a092874acde7",
          // "asbitemName": "腹部平片(立位）",
          // "itemTypeId": "3a126ac6-2fbf-ca50-82a4-73dcc5a5028b",
          // "itemTypeName": "放射科",
          // "appointPatientRegisterId": "3a12ebf4-565a-dbc4-4f2d-d72cd3050cab",
          // "standardPrice": 45.00,
          // "chargePrice": 30.50,
          // "payTypeFlag": "\u0000",
          // "isCharge": "N",
          // "amount": 1,
          // "isInMedicalPackage": "N",
          // "itemTypeDisplayOrder": 28,
          // "displayOrder": 1
          this.dataTransOpts.tableM.register_check_asbitem = deepCopy(this.dataTransOpts.tableM.appoint_register_asbitem)

          // 触发分组 项目
          if (this.form.customerOrgGroupId) this.changeCustomerOrgGroupId()

          this.changeIdNo() //  触发身份证查询档案号
        })

    },


    btnLabel() {
      if (!this.form.id) {
        this.$message.warning({ showClose: true, message: '人员信息尚未保存！' })
        return
      }
      this.dataTransOpts.refresh.lis_request.M++ //触发检验条码刷新      
      this.dataTransOpts.refresh.register_check.M++ //触发检查条码刷新
      this.dialogWin.Label = true
    },

    // 复制分组时，设置当前顶级单位及体检次数
    setCurParentOrgId() {
      // 获取顶级单位
      console.log('setCurParentOrgId_this.form.customerOrgId', this.form.customerOrgId)
      this.getParentCustomerOrgId(this.form.customerOrgId)
        .then(res => {
          if (res) {
            if (res != this.dict.personOrgId) {
              this.customerOrgId = res
              // 获取体检次数
              getapi(`/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${res}`)
                .then(res => {
                  if (res.code > -1) {
                    this.customerOrgRegisterList = res.data
                    if (res.data.length > 0) {
                      this.customerOrgRegister = res.data[res.data.length - 1]
                      this.getCustomerOrgGroupCopy(this.customerOrgRegister.id)
                    }
                  }
                })
            }
          }
        })
    },


    //复制分组
    btnCopyGroup() {
      console.log('this.customerOrgGroup', this.customerOrgGroup)

      this.customerOrgRegisterList = [];
      this.customerOrgRegister = {};
      this.customerOrgGroups = [];
      // 首次打开 复制分组 页面时，需获取顶级单位信息
      if (this.customerOrgAll.length == 0) {
        getapi("/api/app/customer-org/parent-all")
          .then(res => {
            if (res.code > -1) {
              this.customerOrgAll = res.data
              this.customerOrgDisp = res.data
              this.groupVisble = true
              // 复制分组时，设置当前顶级单位及体检次数
              this.setCurParentOrgId()
            }
          })
      } else {
        // 复制分组时，设置当前顶级单位及体检次数
        this.setCurParentOrgId()
        this.groupVisble = true
      }
    },

    //选中分组
    async groupRowClick(row) {
      this.curGroupId = row.id
      this.groupAsbitems = []
      try {
        let res = await getapi(`/api/app/customerorggroupdetail/getcustomerorggroupdetailinasbitem?CustomerOrgGroupId=${row.id}`)
        if (res.code != -1) this.groupAsbitems = res.data
      } catch (error) {
        console.log(error)
      }
    },

    //双击选分组，并确认复制
    async groupRowDblclick(row) {
      await this.groupRowClick(row)
      this.copyGroup()
    },

    //复制分组(确认选中分组)
    copyGroup() {
      if (!this.curGroupId) {
        this.$message.warning({ showClose: true, message: "请先选择要复制的套餐！" })
        return
      }
      console.log('this.packageAsbitems', this.groupAsbitems)
      this.addAbs(deepCopy(this.groupAsbitems))
      this.groupVisble = false
    },



    //复制套餐
    btnCopyMedicalPackage() {
      this.medicalPackageVisble = true
    },

    //选中套餐
    packageRowClick(row) {
      return new Promise((resolve, reject) => {
        this.curPackageId = row.id
        this.packageAsbitems = []
        postapi('/api/app/medicalpackagedetail/getmedicalpackageinasbitem', { medicalPackageId: row.id })
          .then(res => {
            if (res.code > -1) {
              this.packageAsbitems = res.data
              resolve()
            } else {
              reject(res.message)
            }
          })
          .catch(err => {
            reject(err.message)
          })
      })
    },

    //双击选套餐，并确认复制
    rowDblclick(row) {
      this.packageRowClick(row)
        .then(res => {
          this.copyMedicalPackage()
        })
    },

    //复制套餐(确认选中套餐)
    copyMedicalPackage() {
      if (!this.curPackageId) {
        this.$message.warning({ showClose: true, message: "请先选择要复制的套餐！" })
        return
      }
      console.log('this.packageAsbitems', this.packageAsbitems)
      this.addAbs(deepCopy(this.packageAsbitems))
      this.medicalPackageVisble = false
    },

    // 过滤体检单位
    filterMethodOrg(keyWords) {
      if (keyWords) {
        this.customerOrgDisp = [];
        this.customerOrgAll.forEach((item) => {
          if (
            item.displayName.toLowerCase().indexOf(keyWords.toLowerCase()) > -1 ||
            item.simpleCode.toLowerCase().indexOf(keyWords.toLowerCase()) > -1
            // || item.shortName.toLowerCase().indexOf(keyWords.toLowerCase()) > - 1
          ) {
            this.customerOrgDisp.push(item);
          }
        });
      } else {
        this.customerOrgDisp = deepCopy(this.customerOrgAll);
      }
    },

    //选择单位
    changeCustomerOrg(v) {
      if (!v) {
        this.customerOrgRegisterList = [];
        this.customerOrgRegister = {};
        this.customerOrgGroups = [];
      } else {
        getapi(
          `/api/app/customerorgregister/getlistincustomerorgid?CustomerOrgId=${v}`
        ).then((res) => {
          if (res.code != -1) {
            this.customerOrgRegisterList = res.data;
            if (res.data.length > 0) {
              this.customerOrgRegister = res.data[res.data.length - 1];
              this.getCustomerOrgGroupCopy(this.customerOrgRegister.id);
            }
          }
        });
      }
    },

    //选择体检次数
    changeTimes(v) {
      this.getCustomerOrgGroup(v.id);
    },


    //获取体检次数下的分组
    getCustomerOrgGroupCopy(customerOrgRegisterId) {
      // this.isDrag = false;
      // objCopy(this.formInit, this.form);
      // this.form.customerOrgRegisterId = customerOrgRegisterId;
      this.customerOrgGroups = [];
      getapi(
        `/api/app/customerorggroup/getlistinfilter?CustomerOrgRegisterId=${customerOrgRegisterId}`
      ).then((res) => {
        if (res.code != -1) {
          this.customerOrgGroups = res.data;
          this.customerOrgGroups.forEach((e) => {
            e.customerOrgRegisterId = customerOrgRegisterId;
          });
        }
      });
    },

    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮 
      //console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return 'current-row';
      } else {
        return '';
      }
    },

    // 添加组合项目
    ///api/app/register-asbitem/many/3fa85f64-5717-4562-b3fc-2c963f66afa6'
    addAbs(asbItemChoosed) {

      if (asbItemChoosed.length < 1) {
        this.$message.warning({ showClose: true, message: "该套餐或分组下无可复制的组合项目" })
        return
      }

      //性别、年龄判断 
      // "displayName": "身高体重",
      //   "shortName": "哈f哈",
      //   "forSexId": "F",
      //   "itemTypeId": "3a0b16de-75b9-c910-c61b-844709a88940",
      //   "price": 0,
      console.log('asbItemChoosed.length', asbItemChoosed.length)
      let unChecks = []  //不适配项目名称
      for (let i = 0; i < asbItemChoosed.length; i++) {
        if (this.form.sexId == 'U') break //未选性别时，无需判断组合项目性别限制
        if (asbItemChoosed[i].forSexId == 'A') continue
        if (asbItemChoosed[i].forSexId != this.form.sexId) {
          unChecks.push(asbItemChoosed[i].displayName)
          asbItemChoosed[i].unCheck = true
        }
      }

      if (unChecks.length > 0) {
        this.$message.warning({ showClose: true, message: `所选项目：${unChecks.toString()}，不适合当前人员性别` })
        if (asbItemChoosed.length == unChecks.length) return
      }
      let payTypeFlag = '0'   // 0: 个人，1：单位，2：免费
      if (this.form.customerOrgId != this.dict.personOrgId) payTypeFlag = '1'
      asbItemChoosed.forEach(e => {
        if (!e.unCheck) {
          // 未在已选列表中，才选择添加
          let lfind = arrayExistObj(this.dataTransOpts.tableM.register_check_asbitem, 'asbitemId', e.id)
          if (lfind < 0) {
            let pojo = {
              asbitemId: e.id,
              asbitemName: e.displayName,
              patientRegisterId: this.form.id,
              standardPrice: e.price,
              chargePrice: e.price,
              payTypeFlag,
              isCharge: "N",
              checkCompleteFlag: '0',
              discount: 100,
              amount: 1,
              total: e.price,
            }
            this.dataTransOpts.tableM.register_check_asbitem.push(pojo)
          }
        }
      });

      // 刷新左侧待选组合项目
      this.changeItemType(deepCopy(this.dataTransOpts.copyGroup.itemTypeIds))

    },



    //项目类别过滤 组合项目，未过滤已选择的组合项目
    changeItemType(data) {
      //console.log('getAsbItemByItemType', typeof this.itemTypeIds, this.itemTypeIds)
      this.dataTransOpts.copyGroup.itemTypeIds = data
      let asbItemAll = deepCopy(this.dataTransOpts.copyGroup.asbItemAll)
      let lv = "";
      if (typeof this.dataTransOpts.copyGroup.itemTypeIds == "object") {
        if (this.dataTransOpts.copyGroup.itemTypeIds.length > 0) lv = this.dataTransOpts.copyGroup.itemTypeIds[this.dataTransOpts.copyGroup.itemTypeIds.length - 1];
      }

      if (lv) {
        this.dataTransOpts.copyGroup.asbItem = arrayFilter(asbItemAll, "itemTypeId", lv);
      } else {
        this.dataTransOpts.copyGroup.asbItem = deepCopy(asbItemAll);
      }

      arrayReduce(this.dataTransOpts.copyGroup.asbItem, this.dataTransOpts.tableM.register_check_asbitem, "id=asbitemId");
      //console.log('this.dataTransOpts.copyGroup.asbItem',this.dataTransOpts.copyGroup.asbItem,this.dataTransOpts.tableM.register_check_asbitem)
    },

    //回车替代tab键
    enterToTab() {
      this.$nextTick(() => {
        let inputs = document.querySelectorAll("form input"); //用数组可以读取多个标签的元素  //.inline-input
        //// console.log('inputs',inputs);
        // 为每个输入框添加键盘事件监听器
        inputs.forEach((input, i) => {

          input.addEventListener('keydown', (event) => {

            // 如果按下的是回车键
            // // console.log('data-ismultiline',input.getAttribute('data-ismultiline'));

            if (event.keyCode === 13) {
              // 阻止回车键的默认行为（换行）
              event.preventDefault();

              // 如果是身份证，则计算出生与年龄
              let placeholder = input.getAttribute('placeholder')
              if (placeholder == '身份证号') this.changeIdNo()

              // 跳至下一个输入框
              for (let j = i + 1; j < inputs.length; j++) {
                if (inputs[j].getAttribute('disabled') != "disabled") {
                  inputs[j].focus();
                  break;
                }
              }
            }
          });
        });
      });
    },

  },

  //监听事件
  watch: {
    //人员ID未切换换时 也可以强制刷新数据
    "dataTransOpts.refresh.patient_register.S": {
      // immediate: true,
      handler(newVal, oldVal) {
        // console.log(`watch 人员登记 newVal:${newVal} oldVal:${oldVal} registerCheckId: ${this.dataTransOpts.tableS.patient_register.id}`);
        if (newVal != oldVal) this.initFormData(this.dataTransOpts.tableS.patient_register.id)
      }
    },

    //拍照触发
    // "form.photo"(newVal, oldVal) {
    //   //// console.log('patientRegister.patientRegisterRd.id newVal：',newVal,' oldVal：',oldVal)
    //   if (newVal != oldVal) {
    //     this.getPeoplePhoto(newVal)
    //   }
    // },

    //修改单位触发
    // "form.customerOrgId": {
    //   // immediate:true,
    //   // // deep:true,
    //   handler(newVal, oldVal) {
    //     //// console.log('patientRegister.patientRegisterRd.id newVal：',newVal,' oldVal：',oldVal)
    //     if (newVal != oldVal) {
    //       this.changeCustomerOrgId(newVal)
    //     }
    //   }
    // },

    // 从体检人员登记列表 点登记，触发
    // 清空查询条件
    "dataTransOpts.plus.clearPatientRegisterQuery": {
      // immediate: true,
      handler(newVal, oldVal) {
        // console.log('从体检人员登记列表 点登记，触发', newVal, oldVal)
        if (newVal != oldVal) {
          this.preCustomerOrgId = this.patientRegister.query.customerOrgId
          // console.log('this.preCustomerOrgId', this.preCustomerOrgId)
        }
      }
    },

  },
};
</script>
<style scoped>
::v-deep .el-icon-search:before {
  color: #00F;
}

::v-deep .el-select-group__title {
  font-size: 15px;
  background-color: #EEEEEE;
  color: black;
  font-weight: 700;
}


.btn {
  margin-top: 5px;
}

.commonbutton {
  width: 100px;
}

.query {
  margin-left: 10px;
}

.querySpan {
  margin-right: 2px;
}
</style>
