<template>
  <div class="app-container" ref="layout">
    <div ref="topform" class="form">
      <SearchFilter :labelWidths="280" style="width: calc(100% - 80px);"  size="mini" @search="handleQuery"
        @reset="resetQuery" @minShowCtrol="getMaxTableHeight" v-show="showSearch">
      <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px"> -->
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="queryParams.patientName" placeholder="请输入患者姓名" clearable @keyup.enter.native="handleQuery"
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="患者电话" prop="patientPhone">
          <el-input v-model="queryParams.patientPhone" placeholder="请输入患者电话" clearable @keyup.enter.native="handleQuery"
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentDateStart">
          <el-date-picker v-model="appointmentDate" type="daterange" range-separator="至" start-placeholder="开始日期"
            style="width: 300px" value-format="yyyy-MM-dd" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="就诊时间" prop="visitDate">
        <el-date-picker v-model="queryParams.visitDate" value-format="yyyy-MM-dd" style="width:300px" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="入院时间" prop="admissionTime">
        <el-date-picker v-model="queryParams.admissionTime" value-format="yyyy-MM-dd" style="width:300px" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item> -->
        <!-- ，门诊：OUTPATIENT_SERVICE，住院：BE_IN_HOSPITAL -->
        <!-- <el-form-item label="就诊方式" prop="visitMethod">
        <el-select v-model="queryParams.visitMethod" placeholder="请选择就诊方式" clearable style="width:200px">
          <el-option v-for="dict in dict.type.visit_method" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
        <!-- <el-form-item label="诊断" prop="mainDiagnosis">
        <el-input v-model="queryParams.mainDiagnosis" placeholder="请选择诊断" clearable style="width:200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
        <el-form-item label="预约治疗组" prop="appointmentTreatmentGroup" >
          <el-input v-model="queryParams.appointmentTreatmentGroup" placeholder="请输入预约治疗组" clearable
            style="width: 200px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="登记号" prop="registrationNo">
          <el-input v-model="queryParams.registrationNo" placeholder="请输入登记号" clearable style="width: 200px"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="手术名称" prop="surgicalName">
        <el-input v-model="queryParams.surgicalName" placeholder="请输入手术名称" clearable @keyup.enter.native="handleQuery"
          style="width:200px" />
      </el-form-item> -->
        <!-- ，微信小程序：WE_CHAT_APPLET，微信公众号：WE_CHAT_OFFICIAL_ACCOUNT，管理端：MANAGE_END -->
        <!-- <el-form-item label="患者来源" prop="patientSource">
        <el-select v-model="queryParams.patientSource" placeholder="请选择患者来源" clearable style="width:200px">
          <el-option v-for="dict in dict.type.patient_source" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
        <!-- <el-form-item label="出院方式" prop="dischargeMethod">
        <el-input v-model="queryParams.dischargeMethod" placeholder="请输入出院方式" clearable style="width:200px"
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
        <el-form-item label="医院" prop="hospitalAgencyId">
          <el-select v-model="queryParams.hospitalAgencyId" filterable placeholder="请选择医院" style="width: 200px"
            clearable @clear="clearhospitalAgency" @change="changehospitalAgency">
            <el-option v-for="item in hospitalAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院区" prop="campusAgencyId">
          <el-select v-model="queryParams.campusAgencyId" filterable placeholder="请选择院区" style="width: 200px" clearable
            @clear="clearcampusAgency" @change="changecampusAgency">
            <el-option v-for="item in campusAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentId">
          <el-select v-model="queryParams.departmentId" filterable placeholder="请选择科室" style="width: 200px" clearable
            @clear="cleardepartment" @change="changedepartment">
            <el-option v-for="item in departmentlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="病区" prop="wardId">
          <el-select v-model="queryParams.wardId" filterable placeholder="请选择病区" style="width: 200px" clearable>
            <el-option v-for="item in wardlist" :key="item.id" :label="item.wardName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开证医生" prop="certificateIssuingDoctorId">
          <el-select v-model="queryParams.certificateIssuingDoctorId" filterable placeholder="请选择开证医生"
            style="width: 200px" clearable>
            <el-option v-for="item in attendingPhysicianlist" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker clearable v-model="queryParams.birthDate" type="date" value-format="yyyy-MM-dd"
          style="width:200px" placeholder="请选择出生日期">
        </el-date-picker>
      </el-form-item> -->
        <!-- 预住院患者：PRE_HOSPITALIZED_PATIENT，在院患者：IN_HOSPITAL_PATIENT，门诊患者：OUTPATIENT，出院患者：DISCHARGED_PATIENT，签约患者：CONTRACTED_PATIENT -->
        <!-- <el-form-item label="患者类型" prop="patientType">
        <el-select v-model="queryParams.patientType" placeholder="请选择患者类型" clearable style="width:200px">
          <el-option v-for="dict in dict.type.patient_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item> -->
      <!-- </el-form> -->
    </SearchFilter>

    </div>
    <div ref="mb8" class="mb8">
      <el-row :gutter="10" class="">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
            v-hasPermi="['manage:preHospitalized:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
            v-hasPermi="['manage:preHospitalized:edit']">编辑</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['manage:preHospitalized:remove']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleUpload">导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>
    <div ref="table">
      <el-table :max-height="maxTableHeight" v-loading="loading" :data="patientInfoList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column label="患者姓名" align="center" prop="patientName" />
        <el-table-column label="患者电话" align="center" prop="patientPhone" width="120" />
        <el-table-column label="性别" align="center" prop="sex">
          <template slot-scope="scope">
            {{ scope.row.sex == "MALE" ? "男" : "" }}
            {{ scope.row.sex == "FEMALE" ? "女" : "" }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="出生日期" align="center" prop="birthDate" width='130' /> -->
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="家属电话" align="center" prop="familyMemberPhone" width="130" />
        <!-- <el-table-column label="签约状态" align="center" prop="signStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sign_status" :value="scope.row.signStatus" />
        </template>
      </el-table-column>
      <el-table-column label="签约时间" align="center" prop="signTime" width='130'>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
        <el-table-column label="医院" align="center" prop="hospitalAgencyName" width="130" />
        <el-table-column label="院区" align="center" prop="campusAgencyName" width="130" />
        <el-table-column label="科室名称" align="center" prop="departmentName" width="130" />
        <el-table-column label="病区名称" align="center" prop="wardName" width="130" />
        <el-table-column label="预约时间" align="center" prop="appointmentDate" width="130" />
        <!-- <el-table-column label="住院号" align="center" prop="admissionNumber" width='130' /> -->
        <!-- <el-table-column label="门诊号" align="center" prop="outpatientNumber" width='130' /> -->
        <el-table-column label="开证医生" align="center" prop="certificateIssuingDoctorName" />
        <el-table-column label="诊断" align="center" prop="mainDiagnosis" />
        <!-- <el-table-column label="就诊时间" align="center" prop="visitDate" width='130'>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.visitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="就诊方式" align="center" prop="visitMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.visit_method" :value="scope.row.visitMethod" />
        </template>
      </el-table-column>
      <el-table-column label="入院时间" align="center" prop="admissionTime" width='130' />
      <el-table-column label="主治医生" align="center" prop="attendingPhysician" />
     <el-table-column label="出院方式" align="center" prop="dischargeMethod" />
      <el-table-column label="患者来源" align="center" prop="patientSource">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.patient_source" :value="scope.row.patientSource" />
        </template>
      </el-table-column>-->
        <el-table-column label="住址" align="center" prop="address" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleAuthRole(scope.row)">详情</el-button>
            <el-button size="mini" type="text" @click="handleHospital(scope.row)">住院</el-button>
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
              v-hasPermi="['manage:preHospitalized:edit']">编辑</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['manage:preHospitalized:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" /> -->
    <myPagination v-show="total > 0" :total="total" :pageSize="queryParams.pageSize"
      :indexFromWrap="queryParams.pageNum" @updateCPage="updateCPage"></myPagination>
    <!-- 添加或修改患者信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" :inline="true">
        <div class="divtitle">基本信息</div>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" style="width: 200px" />
        </el-form-item>
        <el-form-item label="患者电话" prop="patientPhone">
          <el-input v-model="form.patientPhone" placeholder="请输入患者电话" style="width: 200px" maxlength="11" />
        </el-form-item>
        <el-form-item label="家属电话" prop="familyMemberPhone">
          <el-input v-model="form.familyMemberPhone" placeholder="请输入家属电话" style="width: 200px" maxlength="11" />
        </el-form-item>
        <!-- <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker clearable v-model="form.birthDate" style="width: 200px" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="身份证号" prop="cardNo">
          <el-input v-model="form.cardNo" placeholder="请输入身份证号" style="width: 200px" maxlength="18" />
        </el-form-item>
        <!-- <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio label="MALE">男</el-radio>
            <el-radio label="FEMALE">女</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" style="width:200px" />
        </el-form-item> -->
        <el-form-item label="住址" prop="address">
          <el-input type="textarea" style="width: 200px" :rows="2" placeholder="请输入住址" v-model="form.address" />
        </el-form-item>
        <div class="divtitle" style="margin-top: 20px">就诊信息</div>
        <el-form-item label="主要诊断" prop="mainDiagnosis">
          <el-input v-model="form.mainDiagnosis" placeholder="请输入主要诊断" style="width: 200px" />
        </el-form-item>
        <el-form-item label="医院" prop="hospitalAgencyId">
          <el-select v-model="form.hospitalAgencyId" filterable placeholder="请选择医院" style="width: 200px" clearable
            @clear="clearhospitalAgency(1)" @change="changehospitalAgency($event, 1)">
            <el-option v-for="item in hospitalAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院区" prop="campusAgencyId" v-if="form.hospitalAgencyId">
          <el-select v-model="form.campusAgencyId" filterable placeholder="请选择院区" style="width: 200px" clearable
            @clear="clearcampusAgency(1)" @change="changecampusAgency($event, 1)">
            <el-option v-for="item in form_campusAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室名称" prop="departmentId" v-if="form.hospitalAgencyId">
          <el-select v-model="form.departmentId" filterable placeholder="请选择科室" style="width: 200px" clearable
            @clear="cleardepartment(1)" @change="changedepartment($event, 1)">
            <el-option v-for="item in form_departmentlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约病区" prop="wardId" v-if="form.hospitalAgencyId">
          <el-select v-model="form.wardId" filterable placeholder="请选择病区" style="width: 200px" clearable>
            <el-option v-for="item in form_wardlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开证医生" prop="certificateIssuingDoctorId" v-if="form.hospitalAgencyId">
          <el-select v-model="form.certificateIssuingDoctorId" filterable placeholder="请选择开证医生" style="width: 200px"
            clearable>
            <el-option v-for="item in form_attendingPhysicianlist" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约治疗组" prop="appointmentTreatmentGroup">
          <el-input v-model="form.appointmentTreatmentGroup" placeholder="请输入预约治疗组" style="width: 200px" />
        </el-form-item>
        <el-form-item label="责任护士" prop="responsibleNurse">
          <el-input v-model="form.responsibleNurse" placeholder="请输入责任护士" style="width: 200px" />
        </el-form-item>
        <el-form-item label="登记号" prop="registrationNo">
          <el-input v-model="form.registrationNo" placeholder="请输入登记号" style="width: 200px" />
        </el-form-item>
        <el-form-item label="登记日期" prop="registrationDate">
          <el-date-picker clearable v-model="form.registrationDate" type="date" value-format="yyyy-MM-dd"
            style="width: 200px" placeholder="请选择登记日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentDate">
          <el-date-picker clearable v-model="form.appointmentDate" type="date" value-format="yyyy-MM-dd"
            style="width: 200px" placeholder="请选择预约时间">
          </el-date-picker>
        </el-form-item>
        <!--  <el-form-item label="患者来源" prop="patientSource">
          <el-select v-model="form.patientSource" placeholder="请选择患者来源" clearable style="width:200px">
            <el-option v-for="dict in dict.type.patient_source" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="患者类型" prop="patientType">
          <el-select v-model="form.patientType" placeholder="请选择患者类型" style="width:200px">
            <el-option v-for="dict in dict.type.patient_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约状态" prop="signStatus">
          <el-select v-model="form.signStatus" placeholder="请选择签约状态" style="width:200px">
            <el-option v-for="dict in dict.type.sign_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="签约时间" prop="signTime">
          <el-date-picker clearable v-model="form.signTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择签约时间"
            style="width:200px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="就诊方式" prop="visitMethod">
          <el-select v-model="form.visitMethod" placeholder="请选择就诊方式" style="width:200px">
            <el-option v-for="dict in dict.type.visit_method" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主治医生" prop="attendingPhysician">
          <el-input v-model="form.attendingPhysician" placeholder="请输入主治医生" style="width:200px" />
        </el-form-item>
        <el-form-item label="住院号" prop="admissionNumber">
          <el-input v-model="form.admissionNumber" placeholder="请输入住院号" style="width:200px" />
        </el-form-item>
        <el-form-item label="就诊流水号" prop="visitSerialNumber">
          <el-input v-model="form.visitSerialNumber" placeholder="请输入就诊流水号" style="width:200px" />
        </el-form-item>
        <el-form-item label="手术名称" prop="surgicalName">
          <el-input v-model="form.surgicalName" placeholder="请输入手术名称" style="width:200px" />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker clearable v-model="form.admissionTime" type="date" value-format="yyyy-MM-dd" style="width:200px"
            placeholder="请选择入院时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出院时间" prop="dischargeTime">
          <el-date-picker clearable v-model="form.dischargeTime" type="date" value-format="yyyy-MM-dd" style="width:200px"
            placeholder="请选择出院时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="病历内容">
          <editor v-model="form.medicalRecordContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="门诊号" prop="outpatientNumber">
          <el-input v-model="form.outpatientNumber" placeholder="请输入门诊号" style="width:200px" />
        </el-form-item>
        <el-form-item label="就诊时间" prop="visitDate">
          <el-date-picker clearable v-model="form.visitDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择就诊时间"
            style="width:200px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出院方式" prop="dischargeMethod">
          <el-input v-model="form.dischargeMethod" placeholder="请输入出院方式" style="width:200px" />
        </el-form-item>
        <el-form-item label="微信openid" prop="openId">
          <el-input v-model="form.openId" placeholder="请输入微信openid" style="width:200px" />
        </el-form-item>
        -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改住院 -->
    <el-dialog title="住院信息" :visible.sync="openHospital" width="1000px" append-to-body>
      <el-form ref="formHospital" :model="formHospital" :rules="rulesHospital" label-width="100px" :inline="true">
        <el-form-item label="就诊方式" prop="visitMethod">
          <el-select v-model="formHospital.visitMethod" placeholder="请选择就诊方式" style="width:200px" disabled>
            <el-option v-for="dict in dict.type.visit_method" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主要诊断" prop="mainDiagnosis">
          <el-input v-model="formHospital.mainDiagnosis" placeholder="请输入主要诊断" style="width: 200px" />
        </el-form-item>
        <el-form-item label="医院" prop="hospitalAgencyId">
          <el-select v-model="formHospital.hospitalAgencyId" filterable placeholder="请选择医院" style="width: 200px"
            clearable @clear="clearhospitalAgency(1)" @change="changehospitalAgency($event, 1)">
            <el-option v-for="item in hospitalAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="院区" prop="campusAgencyId">
          <el-select v-model="formHospital.campusAgencyId" filterable placeholder="请选择院区" style="width: 200px" clearable
            @clear="clearcampusAgency(1)" @change="changecampusAgency($event, 1)">
            <el-option v-for="item in form_campusAgencylist" :key="item.id" :label="item.agencyName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室名称" prop="departmentId">
          <el-select v-model="formHospital.departmentId" filterable placeholder="请选择科室" style="width: 200px" clearable
            @clear="cleardepartment(1)" @change="changedepartment($event, 1)">
            <el-option v-for="item in form_departmentlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约病区" prop="wardId">
          <el-select v-model="formHospital.wardId" filterable placeholder="请选择病区" style="width: 200px" clearable>
            <el-option v-for="item in form_wardlist" :key="item.id" :label="item.departmentName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="主治医生" prop="attendingPhysicianId">
          <el-select v-model="formHospital.attendingPhysicianId" filterable placeholder="请选择主治医生" style="width: 200px"
            clearable>
            <el-option v-for="item in form_attendingPhysicianlist" :key="item.userId" :label="item.nickName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="住院号" prop="inHospitalNumber">
          <el-input v-model="formHospital.inHospitalNumber" placeholder="请输入住院号" style="width: 200px"
            onKeyUp="value=value.replace(/[\W]/g,'')" />
        </el-form-item>
        <el-form-item label="责任护士" prop="responsibleNurse">
          <el-input v-model="formHospital.responsibleNurse" placeholder="请输入责任护士" style="width: 200px" />
        </el-form-item>
        <el-form-item label="就诊流水号" prop="visitSerialNumber">
          <el-input v-model="formHospital.visitSerialNumber" placeholder="请输入就诊流水号" style="width: 200px" />
        </el-form-item>
        <el-form-item label="入院时间" prop="admissionTime">
          <el-date-picker clearable v-model="formHospital.admissionTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
            format="yyyy-MM-dd HH:mm" style="width: 200px" placeholder="请选择入院时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="手术名称" prop="surgicalName">
          <el-input v-model="formHospital.surgicalName" placeholder="请输入手术名称" style="width: 200px" />
        </el-form-item>
        <el-form-item label="手术记录" prop="surgicalRecord">
          <editor v-model="formHospital.surgicalRecord" :min-height="192" style="width:838px" />
        </el-form-item>
        <el-form-item label="病历内容" prop="inHospitalInfo">
          <editor v-model="formHospital.inHospitalInfo" :min-height="192" style="width:838px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormHospital">确 定</el-button>
        <el-button @click="cancelHospital">取 消</el-button>
      </div>
    </el-dialog>
    <!-- //导入 -->
    <el-dialog title="导入预住院患者信息" :visible.sync="uploadopen" width="400px" append-to-body>
      <el-upload drag class="upload-demo" ref="upload" :action="action.url" :on-preview="handlePreview"
        :headers="action.headers" :on-remove="handleRemove" :file-list="fileList" :auto-upload="false"
        :on-success="handleAvatarSuccess">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip" style="line-height: 25px">
          <div>
            1.
            <span style="color: #1890ff; cursor: pointer" @click="importTemplate">下载导入模板</span>
          </div>
          <div>2.最大支持2MB的xls/xlsx文件</div>
          <div>3.一次导入患者数量不能超过5000</div>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="uploadcancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchFilter from '../../components/SearchForm.vue'
import { usergetList } from "@/api/unitconfig/patientConfiguration";
import { listPatientInfo, getPatientInfo, delPatientInfo, addPatientInfo, updatePatientInfo, saveRecord } from "@/api/manage/preHospitalized";
import { getAge } from "@/utils/age";
import { selectAgencyList, getDepartmentList, getAgencyList } from "@/api/manage/selectAgencyList";
import { getToken } from '@/utils/auth'

export default {
  name: "preHospitalized",
  dicts: ['patient_type', 'visit_method', 'sign_status', 'patient_source'],
  components: { SearchFilter },
  data() {
    return {
      maxTableHeight: undefined,
      // 医生
      attendingPhysicianlist: [],
      //form-医生
      form_attendingPhysicianlist: [],
      //医院list
      hospitalAgencylist: [],
      // 院区list
      campusAgencylist: [],
      //科室list
      departmentlist: [],
      //病区list
      wardlist: [],
      //form-医院list
      form_hospitalAgencylist: [],
      // form-院区list
      form_campusAgencylist: [],
      //form-科室list
      form_departmentlist: [],
      //form-病区list
      form_wardlist: [],
      //导入
      fileList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 患者信息表格数据
      patientInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openHospital: false,
      uploadopen: false,
      // 查询参数
      appointmentDate: [],
      queryParams: {
        certificateIssuingDoctorId: undefined,
        pageNum: 1,
        pageSize: 10,
        appointmentDateStart: '',
        appointmentDateEnd: '',
        patientName: null,
        patientPhone: null,
        birthDate: null,
        patientType: null,
        visitMethod: null,
        mainDiagnosis: null,
        certificateIssuingDoctor: null,
        hospitalAgencyId: null,
        hospitalAgencyName: null,
        campusAgencyId: null,
        campusAgencyName: null,
        departmentId: null,
        departmentName: null,
        wardId: null,
        wardName: null,
        surgicalName: null,
        admissionTime: null,
        outpatientNumber: null,
        visitDate: null,
        dischargeMethod: null,
        patientSource: null,
      },
      // 表单参数
      form: {},
      formHospital: {},
      // 表单校验
      rulesHospital: {

        hospitalAgencyId: [
          { required: true, message: '请选择医院', trigger: 'change' }
        ],
        inHospitalNumber: [
          { required: true, message: '请输入住院号', trigger: 'change' }
        ],
        visitSerialNumber: [
          { required: true, message: '请输入就诊流水号', trigger: 'change' }
        ],
        attendingPhysicianId: [
          { required: true, message: '请选择主治医生', trigger: 'change' }
        ],
        inHospitalInfo: [
          { required: true, message: '请输入病历内容', trigger: 'change' }
        ],
        admissionTime: [
          { required: true, message: '请选择入院时间', trigger: 'change' }
        ],
      },
      rules: {
        cardNo: [
          { required: true, message: '身份证号格式有误！', trigger: 'change' },
          {
            pattern: /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/,
            message: "身份证号格式有误！",
            trigger: "blur"
          }
        ],
        hospitalAgencyId: [
          { required: true, message: '请选择医院', trigger: 'change' }
        ],
        patientName: [
          { required: true, message: '请输入患者姓名', trigger: 'change' }
        ],
        patientPhone: [
          { required: true, message: '请输入患者手机号', trigger: 'change' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        familyMemberPhone: [
          { required: false, message: '请输入正确的手机号', trigger: 'change' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号",
            trigger: "blur"
          }
        ],
        appointmentDate: [
          { required: true, message: '请选择患者预约时间', trigger: 'change' }
        ],
      },
      action: {
        headers: {
          Authorization: 'Bearer ' + getToken(),
        },
        url: process.env.VUE_APP_BASE_API + '/manage/preHospital/importInfo'
      },
    };
  },
  created() {
    this.getList();
    this.selectAgencyinfo();
  },
  mounted() {
    this.getMaxTableHeight()
    this.screenChange()
  },
  methods: {
    updateCPage(index, size) {
      this.queryParams.pageNum = index
      this.queryParams.pageSize = size
      this.getList();
    },
    /** 详情操作 */
    handleAuthRole(row) {
      this.$router.push({
        path: "/patient/patientdetails",
        query: {
          path: '/patient/preHospitalized',
          patientId: row.patientId,
          cardNo: row.cardNo,
          patientName: row.patientName,
          patientPhone: row.patientPhone,
          sex: row.sex,
          birthDate: row.birthDate,
          familyMemberPhone: row.familyMemberPhone,
          address: row.address,
          patientSource: row.patientSource,
          createTime: row.createTime,
          age: row.birthDate ? getAge(row.birthDate) : ''
        },
      });
    },
    handleHospital(row) {
      this.resetHospital()
      this.openHospital = true
      if (row.hospitalAgencyId) {
        this.changehospitalAgency(row.hospitalAgencyId, 1, 2)
      }
      if (row.campusAgencyId) {
        this.changecampusAgency(row.campusAgencyId, 1, 2)
      }
      if (row.departmentId) {
        this.changedepartment(row.departmentId, 1, 2)
      }
      this.formHospital.patientId = row.patientId
      this.formHospital.mainDiagnosis = row.mainDiagnosis ? row.mainDiagnosis : ''
      this.formHospital.responsibleNurse = row.responsibleNurse ? row.responsibleNurse : ''
      this.formHospital.hospitalAgencyId = row.hospitalAgencyId ? row.hospitalAgencyId : ''
      this.formHospital.campusAgencyId = row.campusAgencyId ? row.campusAgencyId : ''
      this.formHospital.departmentId = row.departmentId ? row.departmentId : ''
      this.formHospital.wardId = row.wardId ? row.wardId : ''
      this.formHospital.patientPreHospitalizationId = row.id
      // this.formHospital.wardName = row.wardName ? row.wardName : ''
    },
    /** 查询患者信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.patientType = 'PRE_HOSPITALIZED_PATIENT'
      listPatientInfo(this.queryParams).then(response => {
        response.rows.forEach(e => {
          e.birthDate ? e.age = getAge(e.birthDate) : ''
        })
        this.patientInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 住院取消按钮
    cancelHospital() {
      this.openHospital = false;
      this.resetHospital();
    },
    // 表单重置
    reset() {
      this.form = {
        patientName: null,
        patientPhone: null,
        familyMemberPhone: null,
        birthDate: null,
        age: null,
        cardNo: null,
        sex: null,
        address: null,
        patientType: 'PRE_HOSPITALIZED_PATIENT',
        certificateIssuingDoctorId: null,
        mainDiagnosis: null,
        hospitalAgencyId: null,
        campusAgencyId: null,
        departmentId: null,
        wardId: null,
        responsibleNurse: null,
        appointmentTreatmentGroup: null,
        registrationNo: null,
        registrationDate: null,
        appointmentDate: null,
        patientSource: null,
      };
      this.resetForm("form");
    },
    resetHospital() {
      this.formHospital = {
        attendingPhysicianId: undefined,
        patientName: null,
        patientPhone: null,
        familyMemberPhone: null,
        birthDate: null,
        cardNo: null,
        sex: null,
        address: null,
        signStatus: null,
        signTime: null,
        certificateIssuingDoctor: null,
        visitMethod: 'BE_IN_HOSPITAL',
        mainDiagnosis: null,
        hospitalAgencyId: null,
        campusAgencyId: null,
        departmentId: null,
        wardId: null,
        patientPreHospitalizationId: null,
        admissionNumber: null,
        responsibleNurse: null,
        visitSerialNumber: null,
        surgicalRecord: null,
        surgicalName: null,
        admissionTime: null,
        dischargeTime: null,
        inHospitalInfo: null,
        appointmentTreatmentGroup: null,
        registrationNo: null,
        registrationDate: null,
        appointmentDate: null,
        inHospitalNumber: null,
        outpatientNumber: null,
        visitDate: null,
        dischargeMethod: null,
        openId: null,
        unionId: null,
        patientSource: null,
        delFlag: null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      if (this.appointmentDate?.length > 0) {
        this.queryParams.appointmentDateStart = this.appointmentDate[0]
        this.queryParams.appointmentDateEnd = this.appointmentDate[1]
      } else {
        this.queryParams.appointmentDateStart = null
        this.queryParams.appointmentDateEnd = null
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.appointmentDate = []
      this.queryParams.appointmentDateStart = ''
      this.queryParams.appointmentDateEnd = ''
      // this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加患者信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPatientInfo(id).then(response => {
        this.form = response.data;
        if (this.form.hospitalAgencyId) {
          this.changehospitalAgency(this.form.hospitalAgencyId, 1, 2)
        }
        if (this.form.campusAgencyId) {
          this.changecampusAgency(this.form.campusAgencyId, 1, 2)
        }
        if (this.form.departmentId) {
          this.changedepartment(this.form.departmentId, 1, 2)
        }
        this.open = true;
        this.title = "修改患者信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.hospitalAgencyId && this.hospitalAgencylist?.length > 0) {
        this.form.hospitalAgencyName = this.hospitalAgencylist.find(e => e.id == this.form.hospitalAgencyId)?.agencyName
      }
      if (this.form.campusAgencyId && this.form_campusAgencylist?.length > 0) {
        this.form.campusAgencyName = this.form_campusAgencylist.find(e => e.id == this.form.campusAgencyId)?.agencyName
      }
      if (this.form.departmentId && this.form_departmentlist?.length > 0) {
        this.form.departmentName = this.form_departmentlist.find(e => e.id == this.form.departmentId)?.departmentName
      }
      if (this.form.wardId && this.form_wardlist?.length > 0) {
        this.form.wardName = this.form_wardlist.find(e => e.id == this.form.wardId)?.departmentName
      }
      if (this.form.certificateIssuingDoctorId && this.form_attendingPhysicianlist?.length > 0) {
        this.form.certificateIssuingDoctorName = this.form_attendingPhysicianlist.find(e => e.userId == this.form.certificateIssuingDoctorId)?.nickName
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePatientInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPatientInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 住院提交按钮 */
    submitFormHospital() {
      if (this.formHospital.hospitalAgencyId && this.hospitalAgencylist?.length > 0) {
        this.formHospital.hospitalAgencyName = this.hospitalAgencylist.find(e => e.id == this.formHospital.hospitalAgencyId)?.agencyName
      }
      if (this.formHospital.campusAgencyId && this.form_campusAgencylist?.length > 0) {
        this.formHospital.campusAgencyName = this.form_campusAgencylist.find(e => e.id == this.formHospital.campusAgencyId)?.agencyName
      }
      if (this.formHospital.departmentId && this.form_departmentlist?.length > 0) {
        this.formHospital.departmentName = this.form_departmentlist.find(e => e.id == this.formHospital.departmentId)?.departmentName
      }
      if (this.formHospital.wardId && this.form_wardlist?.length > 0) {
        this.formHospital.wardName = this.form_wardlist.find(e => e.id == this.formHospital.wardId)?.departmentName
      }
      // if (this.formHospital.attendingPhysicianId && this.form_attendingPhysicianlist?.length > 0) {
      //   this.formHospital.attendingPhysicianName = this.form_attendingPhysicianlist.find(e => e.userId == this.formHospital.attendingPhysicianId)?.nickName
      // }
      // return
      this.$refs["formHospital"].validate(valid => {
        if (valid) {
          // if (this.formHospital.id != null) {
          saveRecord(this.formHospital).then(response => {
            this.$modal.msgSuccess("保存成功");
            this.openHospital = false;
            this.getList();
          });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delPatientInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/patientInfo/export', {
        ...this.queryParams
      }, `patientInfo_${new Date().getTime()}.xlsx`)
    },
    //导入相关的方法
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleAvatarSuccess() {
      this.uploadcancel();
      this.fileList = []
      this.getList();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    //导入
    handleUpload() {
      this.uploadopen = true
    },
    //取消导入
    uploadcancel() {
      this.uploadopen = false
    },
    //获取医院list
    selectAgencyinfo() {
      let query = {
        agencyStatus: 'ON',
        nodeType: 'HOSPITAL',
      }
      selectAgencyList(query).then(res => {
        this.hospitalAgencylist = res.data
      })
    },
    //主治医生
    usergetListinfo(id, type) {
      usergetList({
        hospitalAgencyId: id,
        postName: 'DOCTOR'
      }).then(res => {
        if (type) {
          this.form_attendingPhysicianlist = res.data
        } else {
          this.attendingPhysicianlist = res.data
        }
      })
    },
    //获取下级单位
    getAgencyListinfo(nodeType, id, type) {
      let query = {
        nodeType: nodeType,
      }
      if (nodeType == 'HOSPITAL') {
        query.hospitalId = id
      } else if (nodeType == 'CAMPUS') {
        query.campusId = id
      } else if (nodeType == 'DEPARTMENT') {
        query.departmentId = id
      }
      getAgencyList(query).then(res => {
        if (type) {
          if (nodeType == 'HOSPITAL') {
            this.form_campusAgencylist = res.data.campusList
            this.form_departmentlist = res.data.departmentList
          } else if (nodeType == 'CAMPUS') {
            this.form_departmentlist = res.data.departmentList
          }
          this.form_wardlist = res.data.wardList
        } else {
          if (nodeType == 'HOSPITAL') {
            this.campusAgencylist = res.data.campusList
          }
          if (nodeType == 'CAMPUS' || nodeType == 'HOSPITAL') {
            this.departmentlist = res.data.departmentList
          }
          this.wardlist = res.data.wardList
        }
      })
    },
    //选中医院获取院区
    changehospitalAgency(id, type, typetwo) {
      this.getAgencyListinfo('HOSPITAL', id, type)
      // let query = {
      //   agencyStatus: 'ON',
      //   nodeType: 'CAMPUS',
      //   parentId: id,
      // }
      // selectAgencyList(query).then(res => {
      if (type) {
        if (!typetwo) {
          this.formHospital.campusAgencyId = null
          this.formHospital.departmentId = null
          this.formHospital.wardId = null
          this.formHospital.certificateIssuingDoctorId = null
          this.form.campusAgencyId = null
          this.form.departmentId = null
          this.form.wardId = null
          this.form.certificateIssuingDoctorId = null
        }
      } else {
        this.queryParams.campusAgencyId = null
        this.queryParams.departmentId = null
        this.queryParams.wardId = null
        this.queryParams.certificateIssuingDoctorId = null
      }
      // })
      this.usergetListinfo(id, type)
    },
    //选中院区获取科室
    changecampusAgency(id, type, typetwo) {
      this.getAgencyListinfo('CAMPUS', id, type)
      // let query = {
      //   nodeType: 'DEPARTMENT',
      //   hospitalAgencyId: id,
      // }
      // getDepartmentList(query).then(res => {
      if (type) {
        if (!typetwo) {
          this.formHospital.departmentId = null
          this.formHospital.wardId = null
          this.form.departmentId = null
          this.form.wardId = null
        }
      } else {
        this.queryParams.departmentId = null
        this.queryParams.wardId = null
      }
      // })
    },
    //选中科室获取病区
    changedepartment(id, type, typetwo) {
      this.getAgencyListinfo('DEPARTMENT', id, type)
      // let query = {
      //   nodeType: 'WARD',
      //   parentDepartmentId: id,
      // }
      // getDepartmentList(query).then(res => {
      if (type) {
        if (!typetwo) {
          this.formHospital.wardId = null
          this.form.wardId = null
        } else {
          this.queryParams.wardId = null
        }
      }
      // })
    },
    //清空医院
    clearhospitalAgency(type) {
      if (type) {
        this.form.campusAgencyId = null
        this.form.departmentId = null
        this.form.wardId = null
        this.form.attendingPhysicianId = null
        this.formHospital.campusAgencyId = null
        this.formHospital.departmentId = null
        this.formHospital.wardId = null
        this.formHospital.attendingPhysicianId = null
      } else {
        this.queryParams.campusAgencyId = null
        this.queryParams.departmentId = null
        this.queryParams.wardId = null
        this.queryParams.attendingPhysicianId = null
        setTimeout(() => {
          this.attendingPhysicianlist = []
        }, 1000);
      }
    },
    //清空院区
    clearcampusAgency(type) {
      if (type) {
        this.form.departmentId = null
        this.form.wardId = null
        this.formHospital.departmentId = null
        this.formHospital.wardId = null
        this.getAgencyListinfo('HOSPITAL', this.form.hospitalAgencyId, type)
      } else {
        this.queryParams.departmentId = null
        this.queryParams.wardId = null
        this.getAgencyListinfo('HOSPITAL', this.queryParams.hospitalAgencyId)
      }
    },
    //清空科室
    cleardepartment(type) {
      if (type) {
        this.form.wardId = null
        if (this.form.departmentId) {
          this.getAgencyListinfo('DEPARTMENT', this.form.departmentId, type)
        } else if (this.form.campusAgencyId) {
          this.getAgencyListinfo('CAMPUS', this.form.campusAgencyId, type)
        } else if (this.form.hospitalAgencyId) {
          this.getAgencyListinfo('HOSPITAL', this.form.hospitalAgencyId, type)
        }
        if (this.formHospital.departmentId) {
          this.getAgencyListinfo('DEPARTMENT', this.formHospital.departmentId, type)
        }
        else if (this.formHospital.campusAgencyId) {
          this.getAgencyListinfo('CAMPUS', this.formHospital.campusAgencyId, type)
        } else if (this.formHospital.hospitalAgencyId) {
          this.getAgencyListinfo('HOSPITAL', this.formHospital.hospitalAgencyId, type)
        }
      } else {
        this.queryParams.wardId = null
        if (this.queryParams.departmentId) {
          this.getAgencyListinfo('DEPARTMENT', this.queryParams.departmentId)
        } else if (this.queryParams.campusAgencyId) {
          this.getAgencyListinfo('CAMPUS', this.queryParams.campusAgencyId)
        } else if (this.queryParams.hospitalAgencyId) {
          this.getAgencyListinfo('HOSPITAL', this.queryParams.hospitalAgencyId)
        }
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/system/importDownload/downloadTemplate?fileType=prehospitalized",
        {},
        `预住院患者导入模板.xlsx`
      );
    },
    // 获取表格最高高度
    getMaxTableHeight() {
      const windowInnerHeight = window.innerHeight // 屏幕可视高度
      const layoutDiv = this.$refs.layout
      const formDiv = this.$refs.topform
      const mb8Div = this.$refs.mb8
      this.maxTableHeight =
        windowInnerHeight - 134 -
        this.getBoxPadding(layoutDiv) -
        this.getBoxHeight(mb8Div) -
        this.getBoxHeight(formDiv)
    },
    // 屏幕resize监听
    screenChange() {
      // 屏幕resize监听事件：一旦屏幕宽高发生变化，就会执行resize
      window.addEventListener('resize', this.getMaxTableHeight, true)
      // 将屏幕监听事件移除
      // 这步是必须的。离开页面时不移除，再返回，或者进入到别的有相同元素的页面会报错
      // 或者将这里的方法直接写在beforeDestroy函数中也可以
      this.$once('hook:beforeDestroy', () => {
        window.removeEventListener('resize', this.getMaxTableHeight, true)
      })
    },
    changecertificateIssuingDoctor(e) {
      console.log(e)
      console.log(this.queryParams)
    },
  }
};
</script>
<style lang="scss" scoped>
.divtitle {
  font-size: 16px;
  font-weight: 600;
  height: 60px;
  margin-left: 20px;
}
</style>
