<template>
  <div class="layout_display_flex_y">
    <div>
      <el-button icon="Location" type="primary" @click="beforeFetchAssigninfo"
        >定点信息
      </el-button>
      <el-button icon="Check" type="primary" @click="submitPatientInfo">
        保存
      </el-button>
      <ReadCard
        :pat-no="patient.inpatientNo"
        biztype="01103"
        @success="afterReadCard"
      />
      <el-button icon="CreditCard" type="primary" @click="injurySicard">
        工伤读社保卡
      </el-button>
      <el-button icon="Top" type="success" @click="checkRegisterDatetime"
        >医保入院登记
      </el-button>
      <el-button icon="Bottom" type="danger" @click="beforeCancelRegister"
        >撤销入院登记
      </el-button>
      <el-button icon="Coin" type="success" @click="xiangMuLuRuRouter"
        >项目录入
      </el-button>
      <generate-medicine-return-order />
      <el-button type="danger" @click="chronicDiseaseRegister"
        >慢病登记
      </el-button>
    </div>
    <div style="margin-bottom: 8px">
      <el-divider content-position="left" class="el-divider_shorter"
        >患者基本信息
      </el-divider>
      <el-descriptions :column="3" border>
        <el-descriptions-item>
          <template #label> 住院号</template>
          {{ patient.inpatientNo }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 住院次数</template>
          {{ patient.admissTimes }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 出生日期</template>
          {{ patient.birthDate }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>入院日期</template>
          {{ patient.admissDate }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 病区</template>
          {{ patient.admissWardName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 入院诊断</template>
          <div
            style="width: 180px"
            class="ellipsis-text"
            :title="patient.admissDiagStr"
          >
            {{ patient.admissDiagStr }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 小科室</template>
          {{ patient.smallDeptName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 入院医生</template>
          {{ patient.admissPhysicianName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 登记日期</template>
          <el-date-picker
            v-model="patient.ybRegisterDate"
            placeholder="选择日期时间"
            style="width: 180px"
            type="datetime"
            @change="formatYbRegisterDate"
          ></el-date-picker>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 证件类型</template>
          <el-select
            v-model="patient.psnCertType"
            :clearable="true"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option
              v-for="item in psnCertTypes"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span style="color: #8492a6; font-size: 12px">{{
                item.code
              }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>证件号码</template>
          <el-input
            v-model="patient.socialNo"
            style="width: 180px"
            clearable
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 姓名</template>
          <el-input v-model="patient.name" style="width: 180px"></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 性别</template>
          <el-select v-model="patient.sex" placeholder=" " style="width: 180px">
            <el-option
              v-for="item in sexes"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 联系电话</template>
          <el-input v-model="patient.homeTel" style="width: 180px"></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 管床医生</template>
          <el-input
            v-model="patient.referPhysicianName"
            readonly
            @click="searchPhysician(1)"
            style="width: 180px"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 责任护士</template>
          <el-input
            v-model="patient.dutyNurseName"
            readonly
            @click="searchPhysician(2)"
            style="width: 180px"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 国籍</template>
          <el-select
            v-model="patient.country"
            style="width: 180px"
            :filterable="true"
          >
            <el-option
              v-for="item in countries"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span style="color: #8492a6; font-size: 12px">{{
                item.code
              }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 民族</template>
          <el-select
            v-model="patient.nation"
            style="width: 180px"
            :filterable="true"
          >
            <el-option
              v-for="item in nations"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span style="color: #8492a6; font-size: 12px">{{
                item.code
              }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 联系人姓名</template>
          <el-input
            v-model="patient.contactName"
            style="width: 180px"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 联系人关系</template>
          <el-select
            v-model="patient.contactRelation"
            style="width: 180px"
            :filterable="true"
          >
            <el-option
              v-for="item in relations"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
              <span style="color: #8492a6; font-size: 12px">{{
                item.code
              }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 联系人地址</template>
          <el-input
            v-model="patient.contactAddrName"
            style="width: 180px"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 联系人电话</template>
          <el-input
            v-model="patient.contactPhone"
            style="width: 180px"
          ></el-input>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label> 参保地区</template>
          <el-cascader
            v-model="patient.admdvsCascader"
            clearable
            filterable
            placeholder="请选择"
            :options="allAdmdvses"
            :disabled="injuryMode"
            @change="handleAdmdvsChange"
          ></el-cascader>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label> 医疗类别</template>
          <el-select
            v-model="patient.medType"
            :clearable="true"
            placeholder="请选择"
            @change="handleSelectMedType"
            style="width: 180px"
          >
            <el-option
              v-for="item in medTypes"
              :key="item.code"
              :disabled="item.disabled"
              :label="item.name"
              :value="item.code"
            >
              <span style="color: #8492a6; font-size: 12px">{{
                item.code
              }}</span>
              <el-divider direction="vertical"></el-divider>
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-descriptions-item>
        <span v-if="patient.medType === '52'">
          <el-descriptions-item>
            <template #label>生育类别</template>
            <el-select
              v-model="patient.matnType"
              placeholder="请选择"
              style="width: 180px"
            >
              <el-option
                v-for="item in matnTypes"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>是否晚育</template>
            <el-select
              v-model="patient.latechbFlag"
              placeholder="请选择"
              style="width: 180px"
            >
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>是否早产</template>
            <el-select
              v-model="patient.pretFlag"
              placeholder="请选择"
              style="width: 180px"
            >
              <el-option label="否" value="0"></el-option>
              <el-option label="是" value="1"></el-option>
            </el-select>
          </el-descriptions-item>
        </span>
        <el-descriptions-item
          v-if="patient.medType === '2102' || patient.medType === '52'"
        >
          <template #label>患者病种</template>
          <el-input
            v-model="patient.diseName"
            readonly
            style="width: 180px"
            @click="openDiseInput"
          ></el-input>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>就诊人群类型</template>
          <el-select
            v-model="expContent.MDTRT_GRP_TYPE"
            placeholder="普通患者无需填写"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="item in mdtrtGrpTypes"
              :key="item.key"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>外伤标志</template>
          <el-select
            v-model="expContent.TRUM_FLAG"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="否" value="0" key="trumFlag-0"></el-option>
            <el-option label="是" value="1" key="trumFlag-1"></el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>涉及第三方标志</template>
          <el-select
            v-model="expContent.REL_TTP_FLAG"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="否" value="0" key="relTtpFlag-0"></el-option>
            <el-option label="是" value="1" key="relTtpFlag-1"></el-option>
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>住院类型</template>
          <el-select
            v-model="expContent.IPT_TYPE"
            placeholder="请选择"
            style="width: 180px"
          >
            <el-option label="普通住院" value="1" key="iptType-1"></el-option>
            <el-option
              label="急诊或者请求住院"
              value="2"
              key="iptType-2"
            ></el-option>
            <el-option label="转院住院" value="3" key="iptType-3"></el-option>
          </el-select>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>慢病类型</template>
          <div>{{ patient.crmName }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="layout_flex_1-y layout_display_flex_y">
      <el-divider content-position="left" class="el-divider_shorter">
        医保入院诊断（*自费患者无需填写*）
        <el-button
          circle
          icon="Plus"
          title="添加入院诊断"
          type="primary"
          @click="openDiagDialog"
        ></el-button>
        <el-button
          :disabled="zyInYbDiags.length === 0"
          circle
          icon="Check"
          title="保存入院诊断"
          type="success"
          @click="saveYbDiags"
        ></el-button>
      </el-divider>
      <div class="layout_flex_1-y">
        <el-table :data="zyInYbDiags" height="100%" stripe>
          <el-table-column label="诊断序号" prop="diagNo"></el-table-column>
          <el-table-column label="诊断属性" prop="property"></el-table-column>
          <el-table-column label="诊断编码" prop="icdCode"></el-table-column>
          <el-table-column label="诊断名称" prop="icdText"></el-table-column>
          <el-table-column label="诊断类别">
            <template #default="scope">
              {{ getDiagTypeName(scope.row.diagType) }}
            </template>
          </el-table-column>
          <el-table-column label="诊断时间" prop="opDate"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                circle
                icon="Delete"
                type="danger"
                @click="deleteYbDiag(scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <Assignmentinfo
    v-if="showAssigninfo"
    :admdvs="patient.admdvs"
    :social-no="patient.socialNo"
    @close="showAssigninfo = false"
  />

  <el-dialog
    v-model="showSearchSpecialDiag"
    :close-on-click-modal="false"
    title="医保患者病种录入"
    width="60%"
  >
    <div style="margin: -16px 0 4px 2px; height: 22px; line-height: 22px">
      患者当前病种：
      <span
        style="
          padding: 2px 6px;
          background: #005279;
          border-radius: 4px;
          color: white;
        "
      >
        {{
          patient.diseCode ? patient.diseCode + " | " + patient.diseName : "无"
        }}
      </span>
    </div>
    <el-tag>可选病种</el-tag>&nbsp;&nbsp;
    <el-input
      v-model="specialDiagName"
      clearable
      placeholder="请输入病种名称"
      style="width: 260px"
    ></el-input>
    <el-table
      :data="cptSpecialDiags.slice((currentPage - 1) * 10, currentPage * 10)"
      height="400"
      highlight-current-row
      stripe
    >
      <el-table-column label="病种编码" prop="newCode"></el-table-column>
      <el-table-column label="病种名称" prop="newName"></el-table-column>
      <el-table-column label="限额方式" prop="limitWay"></el-table-column>
      <el-table-column
        label="限额额度计算方式"
        prop="limitAmountCalculateWay"
      ></el-table-column>
      <el-table-column label="疾病限额" prop="limitAmount"></el-table-column>
      <el-table-column>
        <template #default="scope">
          <el-button type="primary" @click="addDiseInfo(scope.row)"
            >选择此病种
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-size="10"
      :total="cptSpecialDiags.length"
      :layout="'total, prev, pager, next, jumper'"
      style="margin-top: 6px"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </el-dialog>

  <el-dialog
    v-model="showAdmissApplyForm"
    title="医保入院登记申请"
    width="500px"
  >
    <div style="margin-bottom: 20px">
      登记时间：
      <el-date-picker
        v-model="admissApply.admissDatetime"
        placeholder="请选择医保登记开始时间"
        type="datetime"
      ></el-date-picker>
    </div>
    <el-input
      v-model="admissApply.inputComment"
      placeholder="请输入申请理由"
      type="textarea"
    ></el-input>
    <div style="width: 450px; text-align: right; margin-top: 30px">
      <el-button icon="Close" type="info" @click="cancelAdmissApply"
        >取消
      </el-button>
      <el-button icon="Check" type="success" @click="confirmAdmissApply"
        >提交
      </el-button>
    </div>
  </el-dialog>
  <el-dialog v-model="showPsnInsuinfo" title="人员信息" width="65%">
    <el-tag>{{ injuryMode ? "工伤信息" : "参保信息" }}</el-tag>
    <div v-if="injuryMode">
      <el-table
        :data="injuryinfo"
        height="180"
        stripe
        @row-click="handleClickInjuryinfo"
      >
        <el-table-column label="个人唯一识别码" prop="psn_no" width="100"></el-table-column>
        <el-table-column label="单位唯一识别码" prop="emp_no" width="100"></el-table-column>
        <el-table-column label="单位名称" prop="emp_name" width="100"></el-table-column>
        <el-table-column label="证件号码" prop="certno" width="150"></el-table-column>
        <el-table-column label="姓名" prop="psn_name" ></el-table-column>
        <el-table-column label="性别" prop="gend" :formatter="(row) => formatGender(row.gend)"></el-table-column>
        <el-table-column label="年龄" prop="age"></el-table-column>
        <el-table-column label="工伤人员类别" prop="psn_type" :formatter="(row) => formatInjuryPersonType(row.psn_type)"></el-table-column>
        <el-table-column label="统筹区号" prop="insu_admdvs"></el-table-column>
        <el-table-column label="在院状态" prop="inhosp_stas" :formatter="(row) => formatInHospStatus(row.inhosp_stas)"></el-table-column>
        <el-table-column label="待遇不享受原因" prop="trt_chk_rslt" width="100"></el-table-column>
        <el-table-column label="工伤诊断结论" prop="exam_ccls" width="150"></el-table-column>
        <el-table-column label="证件类型" prop="certificate_type" :formatter="(row) => formatCertType(row.certificate_type)"></el-table-column>
        <el-table-column label="出生日期" prop="birthday"></el-table-column>
      </el-table>
    </div>
    <div v-else>
      <el-table
        :data="psnBaseinfo.insuinfo"
        height="180"
        stripe
        @row-click="handleClickInsuinfo"
      >
        <el-table-column label="余额" prop="balc"></el-table-column>
        <el-table-column label="险种类型" prop="insutypeName"></el-table-column>
        <el-table-column label="人员类别" prop="psnTypeName"></el-table-column>
        <el-table-column
          label="参保状态"
          prop="psnInsuStasName"
        ></el-table-column>
        <el-table-column
          label="个人参保日期"
          prop="psnInsuDate"
        ></el-table-column>
        <el-table-column
          label="暂停参保日期"
          prop="pausInsuDate"
        ></el-table-column>
        <el-table-column
          label="公务员标志"
          prop="cvlservFlagName"
        ></el-table-column>
        <el-table-column
          label="参保地医保区划"
          prop="insuplcAdmdvs"
        ></el-table-column>
        <el-table-column
          label="参保地名称"
          prop="insuplcAdmdvsName"
        ></el-table-column>
        <el-table-column label="单位名称" prop="empName"></el-table-column>
      </el-table>
      <div style="height: 16px"></div>
      <el-tag>身份信息</el-tag>
      <el-table :data="psnBaseinfo.idetinfo" height="180" stripe>
        <el-table-column
          label="人员身份类别"
          prop="psnIdetTypeName"
        ></el-table-column>
        <el-table-column
          label="人员类别等级"
          prop="psnTypeLv"
        ></el-table-column>
        <el-table-column label="备注" prop="memo"></el-table-column>
        <el-table-column label="开始时间" prop="begntime"></el-table-column>
        <el-table-column label="结束时间" prop="endtime"></el-table-column>
      </el-table>
    </div>
  </el-dialog>
  <Search
    v-if="searchParams.showSearch"
    :med-type="patient.medType"
    :target="searchParams.target"
    :title="searchParams.title"
    :show-emp-dept="searchParams.target === 'physician'"
    :show-yb-code="searchParams.target === 'physician'"
    @close="searchParams.showSearch = false"
    @click-item="handleClickSearchItem"
  />
</template>

<script setup>
import {
  computed,
  onActivated,
  onDeactivated,
  onMounted,
  reactive,
  ref,
  watchEffect,
} from "vue";
import {
  getZyInYbDiags,
  saveZyInYbDiags,
  submitSiPatientInfo,
} from "@/api/inpatient/patient";
import { getAllSpecialDiags } from "@/api/inpatient/dictionary";
import {
  fetchCountryDictionary,
  fetchNationDictionary,
  fetchRelationDictionary,
} from "@/api/dictionary/fetch-dictionaries";
import { diagTypes, sexes } from "@/data";
import { allAdmdvses } from "@/data/admdvs";
import { nullPatient } from "@/utils/validate";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  admissRegister,
  revokeAdmission,
} from "@/api/medical-insurance/si-inpatient";
import { formatDatetime, getDatetime } from "@/utils/date";
import { clone } from "@/utils/clone";
import {
  getMatnTypes,
  getMedTypesByFlag,
  getPsnCertTypes,
} from "@/api/medical-insurance/si-dict";
import {
  checkRegisterDate,
  obtainBasicPersonInfo,
} from "@/api/medical-insurance/si-query";
import {
  inpatientRegister,
  revokeInpatientRegister,
  employeeInfoInquiry,
} from "@/api/medical-insurance/si-injury";
import {
  selectAdmissApply,
  submitAdmissApply,
} from "@/api/medical-insurance/si-admiss-apply";
import { baseinfo } from "@/data/inpatient";
import XmlrV2 from "@/components/xmlr/index.vue";
import Assignmentinfo from "@/components/medical-insurance/assigninfo/Index.vue";
import Search from "@/components/search/Index.vue";
import ReadCard from "@/components/medical-insurance/readcard/Index.vue";
import GenerateMedicineReturnOrder from "@/components/medical-insurance/medicine-return-order/GenerateMedicineReturnOrder.vue";
import { CyMessageBox } from "@/utils/cy-message-box";
import sleep from "@/utils/sleep";
import XEUtils from "xe-utils";
import router from "@/router";
import { useMedinsStore } from "@/pinia/medins-store";
import { useDialog } from "@/components/cy/CyDialog/index";

const patient = computed(() => {
  const patientInfo = baseinfo();
  const pContent = patientInfo.expContent
    ? JSON.parse(patientInfo.expContent)
    : {};
  expContent.MDTRT_GRP_TYPE = pContent.MDTRT_GRP_TYPE;
  expContent.TRUM_FLAG = pContent.TRUM_FLAG;
  expContent.REL_TTP_FLAG = pContent.REL_TTP_FLAG;
  expContent.IPT_TYPE = pContent.IPT_TYPE;
  return patientInfo;
});
const fetchZyYbDiags = () => {
  if (nullPatient()) {
    return;
  }
  getZyInYbDiags(patient.value.inpatientNo, patient.value.admissTimes).then(
    res => {
      zyInYbDiags.value = res;
    }
  );
};

const medinsStore = useMedinsStore();
const injuryMode = computed(() => {
  return medinsStore.isInjuryMode;
});

const handleSelectMedType = val => {
  medinsStore.setInjuryMode((val === "gs21") || (val === "gs22") || (val === "gs23"));
};
const actived = ref(false);

onActivated(() => {
  actived.value = true;
});

onDeactivated(() => {
  actived.value = false;
});

const currentPatNo = ref(null);
watchEffect(() => {
  if (actived.value) {
    if (
      patient.value.inpatientNo &&
      patient.value.inpatientNo !== currentPatNo.value
    ) {
      currentPatNo.value = patient.value.inpatientNo;
      fetchZyYbDiags();
    }
  }
});

const searchParams = reactive({
  showSearch: false,
  title: "",
  target: "",
});

const psnCertTypes = ref([]);
const medTypes = ref([]);
const countries = ref([]);
const nations = ref([]);
const relations = ref([]);
const diagItem = ref({});
const showSearchSpecialDiag = ref(false);
const zyInYbDiags = ref([]);
const specialDiags = ref([]);
const specialDiagName = ref("");
const cptSpecialDiags = computed(() => {
  return specialDiags.value.filter(item => {
    return (
      (item.oldName + "" + item.newName).indexOf(specialDiagName.value) !== -1
    );
  });
});
const matnTypes = ref([]);

const expContent = reactive({
  MDTRT_GRP_TYPE: "",
  TRUM_FLAG: "",
  REL_TTP_FLAG: "",
  IPT_TYPE: "",
});
const mdtrtGrpTypes = [
  { code: "1", name: "新冠肺炎确诊患者", key: "mdtrtGrpTypes-1" },
  { code: "2", name: "其他国家突发公共事件", key: "mdtrtGrpTypes-2" },
  { code: "3", name: "新冠肺炎疑似患者", key: "mdtrtGrpTypes-3" },
  { code: "4", name: "无症状感染者", key: "mdtrtGrpTypes-4" },
];

const handleAdmdvsChange = val => {
  patient.value.admdvs = val[1];
};

const openDiagDialog = () => {
  if (nullPatient()) {
    return;
  }
  if (!patient.value.medType) {
    ElMessage({
      message: "请先选择医疗类别！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  searchParams.title = "医保入院诊断";
  searchParams.target = injuryMode.value ? "injurydiag" : "diag";
  searchParams.showSearch = true;
};

const openDiseInput = () => {
  getAllSpecialDiags(patient.value.medType).then(res => {
    specialDiags.value = res;
    showSearchSpecialDiag.value = true;
  });
};

const addDiseInfo = row => {
  patient.value.diseCode = row.newCode;
  patient.value.diseName = row.newName;
  showSearchSpecialDiag.value = false;
};

const getDiagTypeName = val => {
  for (let i = 0; i < diagTypes.length; i++) {
    if (diagTypes[i].code === val) {
      return diagTypes[i].name;
    }
  }
};

const deleteYbDiag = index => {
  zyInYbDiags.value.splice(index, 1);
  for (let i = 0; i < zyInYbDiags.value.length; i++) {
    const element = zyInYbDiags.value[i];
    element.diagNo = i + 1;
    if (i === 0) {
      element.property = "主要诊断";
    }
  }
};

const saveYbDiags = () => {
  const param = {
    inpatientNo: patient.value.inpatientNo,
    admissTimes: patient.value.admissTimes,
    diags: zyInYbDiags.value,
  };
  saveZyInYbDiags(param).then(() => {
    ElMessage({
      message: "医保入院诊断保存成功。",
      type: "success",
      duration: 2500,
      showClose: true,
    });
    showSearchSpecialDiag.value = false;
  });
};

const submitPatientInfo = () => {
  if (nullPatient()) {
    return;
  }
  ElMessageBox.confirm("确定保存患者信息？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    patient.value.expContent = JSON.stringify(expContent);
    submitSiPatientInfo({
      patient: patient.value,
      diags: zyInYbDiags.value,
    }).then(() => {
      ElMessage({
        message: "保存患者信息成功。",
        type: "success",
        duration: 2500,
        showClose: true,
      });
    });
  });
};

const searchPhysician = flag => {
  switch (flag) {
    case 1:
      searchParams.title = "管床医生";
      break;
    case 2:
      searchParams.title = "责任护士";
      break;
  }
  searchParams.target = "physician";
  searchParams.showSearch = true;
};

const handleClickSearchItem = item => {
  if (searchParams.target === "physician") {
    if (!item.ybCode) {
      ElMessage({
        message: "请选择有医保赋码的人员。",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }
    switch (searchParams.title) {
      case "管床医生":
        if (!item.ybCode.startsWith("D")) {
          ElMessage({
            message: "医师医保编码首字母为D，请重新选择。",
            type: "warning",
            duration: 2500,
            showClose: true,
          });
          return;
        }
        patient.value.referPhysician = item.code;
        patient.value.referPhysicianName = item.name;
        break;
      case "责任护士":
        if (!item.ybCode.startsWith("N")) {
          ElMessage({
            message: "护士医保编码首字母为N，请重新选择。",
            type: "warning",
            duration: 2500,
            showClose: true,
          });
          return;
        }
        patient.value.dutyNurse = item.code;
        patient.value.dutyNurseName = item.name;
        break;
    }
  } else if (
    searchParams.target === "diag" ||
    searchParams.target === "injurydiag"
  ) {
    diagItem.value.icdCode = item.icdCode;
    diagItem.value.icdText = item.icdText;
    diagItem.value.diagType = item.diagType;
    diagItem.value.property =
      zyInYbDiags.value.length === 0 ? "主要诊断" : "次要诊断";
    diagItem.value.diagNo = zyInYbDiags.value.length + 1;
    diagItem.value.opDate = getDatetime();
    zyInYbDiags.value.push(clone(diagItem.value));
  }
  searchParams.showSearch = false;
};

const afterReadCard = result => {
  patient.value.mdtrtCertType = result.mdtrtCertType;
  patient.value.readCardResult = result.readCardResult;
  patient.value.busCardInfo = result.busCardInfo;
  patient.value.readCardBizType = result.readCardBizType;
};

const formatYbRegisterDate = () => {
  patient.value.ybRegisterDate = formatDatetime(patient.value.ybRegisterDate);
};

const admissApply = ref({});
const showAdmissApplyForm = ref(false);

// 新增：用于存储工伤读卡接口返回结果
const injurySicardResult = ref({});

const injurySicard = async () => {
  if (nullPatient()) {
    return;
  }
  if (!patient.value.medType) {
    ElMessage({
      message: "请先选择医疗类别！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  if (!(patient.value.medType&&((patient.value.medType === 'gs21') || (patient.value.medType === 'gs22') || (patient.value.medType === 'gs23')))) {
    ElMessage({
      message: "请先选择工伤相关的医疗类别！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  const loading = ElMessage({
    message: '正在读取社保卡，请稍候...',
    type: 'info',
    duration: 0,
    showClose: true,
    grouping: true,
  });
  try {
    const response = await fetch('http://130.150.161.72:9206/thyy/api/public/injury/workinjury', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        action: 'transaction',
        transactionName: 'ReadCard',
      }),
    });
    const result = await response.json();
    console.log("patient.value00000000000000000000",patient.value)
    console.log("result1111111111111111111111111111",result)
    if (result && result.code === 1 && result.data) {
      if(result.data && result.data.data && result.data.data.certno && (result.data.data.certno !== patient.value.socialNo)) {
          ElMessage({
            message: '人证不符,请检查身份证号码！',
            type: 'error',
            duration: 2500,
            showClose: true,
          });
          return        
      }
      if(result.data && result.data.data && result.data.data.psn_name && (result.data.data.psn_name !== patient.value.name)) {
          ElMessage({
            message: '人证不符,请检查姓名！',
            type: 'error',
            duration: 2500,
            showClose: true,
          });
          return        
      }
      // 新增：调用 addWorkInjuryPatientRelation
      try {
        // 解析 exam_ccls 字段
        let QualificationId = '';
        let injury_part_desc = '';
        let visit_type = '';
        if (result.data.data.exam_ccls) {
          // 格式：^工伤医疗费资格审核信息ID|受伤部位信息描述|就诊类型^
          const match = result.data.data.exam_ccls.match(/^\^?(.*?)\|(.*?)\|(.*?)\^?$/);
          if (match) {
            QualificationId = match[1];
            injury_part_desc = match[2];
            visit_type = match[3];
          }
        }
        await fetch('http://130.150.161.72:9206/thyy/api/public/injury/addWorkInjuryPatientRelation', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
                  inpatient_no:patient.value.inpatientNo,
                  admiss_times:patient.value.admissTimes,
                  psn_no:result.data.data.psn_no,
                  emp_no:result.data.data.emp_no,
                  emp_name:result.data.data.emp_name,
                  certno:result.data.data.certno,
                  psn_name:result.data.data.psn_name,
                  gend:result.data.data.gend,
                  age:result.data.data.age,
                  psn_type:result.data.data.psn_type,
                  insu_admdvs:result.data.data.insu_admdvs,
                  inhosp_stas:result.data.data.inhosp_stas,
                  trt_chk_rslt:result.data.data.trt_chk_rslt,
                  exam_ccls:result.data.data.exam_ccls,
                  certificate_type:result.data.data.certificate_type,
                  birthday:result.data.data.birthday,
                  QualificationId,
                  injury_part_desc,
                  visit_type
          }),
        });
      } catch (e) {
          ElMessage({
            message: '工伤读社保卡接口异常',
            type: 'error',
            duration: 2500,
            showClose: true,
          });
          return
      }
      injurySicardResult.value = result.data;
      patient.value.mdtrtCertType = 'injurySicard';
      patient.value.readCardResult = injurySicardResult.value;
      patient.value.readCardBizType = '01103';
      console.log("patient.value111111111111111111111111",patient.value)
      ElMessage({
        message: '工伤读社保卡成功',
        type: 'success',
        duration: 2500,
        showClose: true,
      });
    } else {
      ElMessage({
        message: result.message || '工伤读社保卡失败',
        type: 'error',
        duration: 2500,
        showClose: true,
      });
    }
  } catch (error) {
    ElMessage({
      message: '工伤读社保卡接口异常',
      type: 'error',
      duration: 2500,
      showClose: true,
    });
  } finally {
    loading.close && loading.close();
  }
};
const checkRegisterDatetime = () => {
  if (nullPatient()) {
    return;
  }
  if(!(patient.value && patient.value.mdtrtCertType && patient.value.readCardResult)) {
      ElMessage({
        message: "请进行读卡操作！",
        type: "warning",
        duration: 2600,
        showClose: true,
      });    
    return;
  }
  if(patient.value.mdtrtCertType === "sicard"){
    if ((patient.value.medType&&((patient.value.medType === 'gs21') || (patient.value.medType === 'gs22') || (patient.value.medType === 'gs23')))) {
      ElMessage({
        message: "工伤相关的医疗类别,不能用此读卡功能！",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }    
    if(!(patient.value.name && patient.value.readCardResult && patient.value.readCardResult.includes(patient.value.name))) {
      // 社保卡读卡成功，但姓名不匹配！
      ElMessage({
        message: "社保卡读卡成功，但姓名不匹配！",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }
    if(!(patient.value.socialNo && patient.value.readCardResult && patient.value.readCardResult.includes(patient.value.socialNo))) {
      // 社保卡读卡成功，但身份证不匹配！
      ElMessage({
        message: "社保卡读卡成功，但身份证不匹配！",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }    
  }else if(patient.value.mdtrtCertType === "qrcode"){
    if ((patient.value.medType&&((patient.value.medType === 'gs21') || (patient.value.medType === 'gs22') || (patient.value.medType === 'gs23')))) {
      ElMessage({
        message: "工伤相关的医疗类别,不能用此读卡功能！",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }    
    // 电子凭证读卡逻辑 - JSON格式数据
    try {
      const cardData = JSON.parse(patient.value.readCardResult);
      if (!(patient.value.name && cardData.userName === patient.value.name)) {
        ElMessage({
          message: "电子凭证读卡成功，但姓名不匹配！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
      }
      if (!(patient.value.socialNo && cardData.idNo === patient.value.socialNo)) {
        ElMessage({
          message: "电子凭证读卡成功，但身份证不匹配！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
      }
    } catch (error) {
      ElMessage({
        message: "电子凭证读卡数据格式错误！",
        type: "error",
        duration: 2500,
        showClose: true,
      });
      return;
    }
  }else if(patient.value.mdtrtCertType === "face"){
    if ((patient.value.medType&&((patient.value.medType === 'gs21') || (patient.value.medType === 'gs22') || (patient.value.medType === 'gs23')))) {
      ElMessage({
        message: "工伤相关的医疗类别,不能用此读卡功能！",
        type: "warning",
        duration: 2500,
        showClose: true,
      });
      return;
    }    
    // 刷脸读卡逻辑 - JSON格式数据
    try {
      const cardData = JSON.parse(patient.value.readCardResult);
      if (!(patient.value.name && cardData.userName === patient.value.name)) {
        ElMessage({
          message: "刷脸读卡成功，但姓名不匹配！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
      }
      if (!(patient.value.socialNo && cardData.idNo === patient.value.socialNo)) {
        ElMessage({
          message: "刷脸读卡成功，但身份证不匹配！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
      }
    } catch (error) {
      ElMessage({
        message: "刷脸读卡数据格式错误！",
        type: "error",
        duration: 2500,
        showClose: true,
      });
      return;
    }
  }
  if ((patient.value.medType&&((patient.value.medType === 'gs21') || (patient.value.medType === 'gs22') || (patient.value.medType === 'gs23')))) {
    if(!(zyInYbDiags && zyInYbDiags.length && zyInYbDiags.length > 0)) {
        ElMessage({
          message: "医保入院诊断,不能为空！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
    }
  }   
  patient.value.expContent = JSON.stringify(expContent);
  submitSiPatientInfo({
    patient: patient.value,
    diags: zyInYbDiags.value,
  }).then(() => {
    checkRegisterDate(
      patient.value.inpatientNo,
      patient.value.admissTimes
    ).then(() => {
      selectAdmissApply(patient.value).then(res => {
        if (null === res.status) {
          admissApply.value.patNo = patient.value.inpatientNo;
          admissApply.value.times = patient.value.admissTimes;
          admissApply.value.ledgerSn = patient.value.ledgerSn;
          admissApply.value.admissDatetime = patient.value.ybRegisterDate;
          admissApply.value.inputComment = "人证相符。";
          showAdmissApplyForm.value = true;
        } else {
          switch (res.status) {
            case 0:
              ElMessageBox.alert(
                "医保科尚未处理此患者的医保入院申请，请耐心等候或者致电医保科（内线电话：2102）。",
                "提示",
                {
                  type: "warning",
                }
              );
              break;
            case 1:
              getPsnInsuinfo();
              break;
            case 2:
              ElMessageBox.confirm(
                "医保科驳回了此患者的医保入院申请，驳回意见为【" +
                  res.handleComment +
                  "】",
                "提示",
                {
                  type: "error",
                  distinguishCancelAndClose: true,
                  confirmButtonText: "我知道了",
                  cancelButtonText: "重新提交",
                  showCancelButton: true,
                }
              ).catch(action => {
                if (action === "cancel") {
                  admissApply.value.patNo = patient.value.inpatientNo;
                  admissApply.value.times = patient.value.admissTimes;
                  admissApply.value.ledgerSn = patient.value.ledgerSn;
                  admissApply.value.admissDatetime =
                    patient.value.ybRegisterDate;
                  showAdmissApplyForm.value = true;
                }
              });
              break;
          }
        }
      });
    });
  });
};

const cancelAdmissApply = () => {
  admissApply.value = {};
  showAdmissApplyForm.value = false;
};

const confirmAdmissApply = () => {
  if (!admissApply.value.admissDatetime) {
    ElMessage({
      message: "医保入院登记时间不能为空！",
      type: "error",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  if (!admissApply.value.inputComment) {
    ElMessage({
      message: "申请理由不能为空！",
      type: "error",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  admissApply.value.admissDatetime = formatDatetime(
    admissApply.value.admissDatetime
  );
  ElMessageBox.confirm("是否确认提交入院登记申请？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      submitAdmissApply(admissApply.value).then(res => {
        ElMessage({
          message: res,
          type: "success",
          duration: 2500,
          showClose: true,
        });
        showAdmissApplyForm.value = false;
      });
    })
    .catch(() => {});
};

const psnBaseinfo = ref({});
const showPsnInsuinfo = ref(false);
const injuryinfo = ref([]);
const getPsnInsuinfo = () => {
  if (nullPatient()) {
    return;
  }
  if (!patient.value.medType) {
    ElMessage({
      message: "请选择患者的医疗类别！",
      type: "warning",
      showClose: true,
    });
    return;
  }
  if (injuryMode.value) {
    //employeeInfoInquiry(patient.value).then(res => {
      //injuryinfo.value = res;
      injuryinfo.value = [patient.value.readCardResult.data];
      showPsnInsuinfo.value = true;
    //});
  } else {
    const param = {
      medType: patient.value.medType,
      patNo: patient.value.inpatientNo,
      times: patient.value.admissTimes,
      ledgerSn: patient.value.ledgerSn,
      socialNo: patient.value.socialNo,
      name: patient.value.name,
      admdvs: patient.value.admdvs,
      psnCertType: patient.value.psnCertType,
      needSaving: 1,
    };
    obtainBasicPersonInfo(param).then(res => {
      patient.value.psnNo = res.psnNo;
      psnBaseinfo.value = res;
      showPsnInsuinfo.value = true;
      if (XEUtils.toNumber(res.gend) !== patient.value.sex) {
        sleep(800).then(() => {
          CyMessageBox.alert({
            message: `患者医保性别<span style="color:red">${res.gendName}</span>，与HIS信息不一致，请核实。`,
            type: "warning",
            dangerouslyUseHTMLString: true,
          });
        });
      }
    });
  }
};

const handleClickInjuryinfo = row => {
  ElMessageBox.confirm("确定进行工伤入院登记？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
        // 解析 exam_ccls 字段
        let QualificationId = '';
        let injury_part_desc = '';
        let visit_type = '';
        if (patient.value.readCardResult.data.exam_ccls) {
          // 格式：^工伤医疗费资格审核信息ID|受伤部位信息描述|就诊类型^
          const match = patient.value.readCardResult.data.exam_ccls.match(/^\^?(.*?)\|(.*?)\|(.*?)\^?$/);
          if (match) {
            QualificationId = match[1];
            injury_part_desc = match[2];
            visit_type = match[3];
          }
        }
      const params = {
        ipt_otp_no: patient.value.inpatientNo + '_' + patient.value.admissTimes,
        med_type: patient.value.medType,
        adm_time: getCurrentDateTimeStr(),
        adm_diag_dscr: zyInYbDiags && zyInYbDiags.length && (zyInYbDiags.length > 0) && zyInYbDiags[0] && zyInYbDiags[0].icdCode ? zyInYbDiags[0].icdCode : '',
        wardarea_name: patient.value.admissWardName,
        adm_dept_codg: patient.value.admissWard,
        adm_bed: patient.value.bedNo,
        atddr_no: patient.value.admissPhysician,
        tel: patient.value.contactPhone,
        psn_no: patient.value.readCardResult.data.psn_no,
        ipt_no: patient.value.inpatientNo,
        qualification_id: QualificationId
      }
      //row.patNo = patient.value.inpatientNo;
      //row.times = patient.value.admissTimes;
      //row.ledgerSn = patient.value.ledgerSn;
      //row.aka130 = "42";
      //row.bka003 = "420";
      //inpatientRegister(row).then(res => {
       // ElMessage({
      //    message: "审核已通过，医保入院登记成功。",
      //    type: "success",
      //    duration: 2500,
      ////    showClose: true,
      //  });
        showPsnInsuinfo.value = false;
      //});
    })
    .catch(() => {});
};

const handleClickInsuinfo = row => {
  ElMessageBox.confirm("确定进行医保入院登记？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(() => {
      patient.value.balc = row.balc;
      patient.value.insutype = row.insutype;
      patient.value.psnType = row.psnType;
      patient.value.insuplcAdmdvs = row.insuplcAdmdvs;
      patient.value.insuplcAdmdvsName = row.insuplcAdmdvsName;
      patient.value.empName = row.empName;
      admissRegister(patient.value).then(() => {
        ElMessage({
          message: "医保入院登记成功。",
          type: "success",
          duration: 2500,
          showClose: true,
        });
        showPsnInsuinfo.value = false;
      });
    })
    .catch(() => {});
};

const beforeCancelRegister = () => {
  if (nullPatient()) return;
  ElMessageBox.prompt("请输入撤销入院登记的原因：", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      if (!value) {
        ElMessage({
          message: "撤销入院登记的原因不能为空！",
          type: "warning",
          duration: 2500,
          showClose: true,
        });
        return;
      }
      ElMessageBox.confirm(
        "撤销医保入院登记的原因为【" + value + "】确定撤销？",
        "提示",
        {
          type: "warning",
        }
      ).then(() => {
        patient.value.revokeRemark = value;
        if (injuryMode.value) {
          revokeInpatientRegister(patient.value).then(() => {
            ElMessageBox.alert("撤销入院登记成功。", "提示", {
              type: "success",
            });
          });
        } else {
          revokeAdmission(patient.value).then(() => {
            ElMessageBox.alert("撤销入院登记成功。", "提示", {
              type: "success",
            });
          });
        }
      });
    })
    .catch(() => {});
};

const showAssigninfo = ref(false);
const beforeFetchAssigninfo = () => {
  if (nullPatient()) {
    return;
  }
  if (!patient.value.socialNo) {
    ElMessage({
      message: "患者身份证不能为空！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  if (!patient.value.admdvs) {
    ElMessage({
      message: "患者参保地不能为空！",
      type: "warning",
      duration: 2500,
      showClose: true,
    });
    return;
  }
  showAssigninfo.value = true;
};

function chronicDiseaseRegister() {
  if (nullPatient()) {
    return;
  }
  router.push(
    "/outpatient/chronicDisease/chronicDiseaseRegister/" +
      patient.value.inpatientNo
  );
}

const xiangMuLuRuRouter = () => {
  if (nullPatient()) {
    return;
  }
  useDialog(XmlrV2, {
    dialogProps: {
      fullscreen: true,
      showClose: false,
    },
    showFooter: false,
    hideHeader: true,
    params: { patNo: patient.value.inpatientNo },
  });
};

const currentPage = ref(1);
const handleCurrentChange = val => {
  currentPage.value = val;
};

// 性别转化
function formatGender(val) {
  switch (val) {
    case '1': return '男';
    case '2': return '女';
    case '9': return '未说明性别';
    default: return val || '';
  }
}
// 工伤人员类别转化
function formatInjuryPersonType(val) {
  const map = {
    '01': '新工伤', '02': '老工伤', '03': '建筑业', '04': '退休职业病',
    '05': '机关事业老工伤纳入', '06': '机关事业老工伤确认', '07': '伤残军人',
    '08': '非全日制和多单位就业', '09': '8023人员', '10': '包干老工伤',
    '11': '超龄就业人员', '12': '实习生', '13': '离职职业病', '14': '见习生',
    '15': '新业态人员'
  };
  return map[val] || val || '';
}
// 在院状态转化
function formatInHospStatus(val) {
  switch (val) {
    case '0': return '未在院';
    case '1': return '工伤在院';
    case '2': return '医疗在院';
    default: return val || '';
  }
}
// 证件类型转化
function formatCertType(val) {
  const map = {
    '01': '居民身份证', '04': '港澳居民来往内地通行证', '05': '台湾居民来往大陆通行证',
    '07': '外国人永久居留身份证', '08': '外国人护照', '16': '港澳台居民居住证',
    '90': '社会保障卡', '99': '其他'
  };
  return map[val] || val || '';
}

// 获取当前时间，格式为YYYYMMDDHH24MISS
function getCurrentDateTimeStr() {
  const now = new Date();
  const pad = (n) => n < 10 ? '0' + n : n;
  return (
    now.getFullYear().toString() +
    pad(now.getMonth() + 1) +
    pad(now.getDate()) +
    pad(now.getHours()) +
    pad(now.getMinutes()) +
    pad(now.getSeconds())
  );
}

onMounted(() => {
  getPsnCertTypes().then(res => {
    psnCertTypes.value = res;
  });
  getMedTypesByFlag("hospitalization").then(res => {
    medTypes.value = res;
  });
  fetchCountryDictionary().then(res => {
    countries.value = res;
  });
  fetchNationDictionary().then(res => {
    nations.value = res;
  });
  fetchRelationDictionary().then(res => {
    relations.value = res;
  });
  getMatnTypes().then(res => {
    matnTypes.value = res;
  });
});
</script>

<style scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}

.el-collapse-item__content {
  padding-bottom: 0;
}

.el-collapse-item__header {
  height: 30px;
  line-height: 30px;
}

.el-collapse-item__header,
.el-collapse-item__wrap {
  background-color: inherit;
}

.el-autocomplete-suggestion li {
  line-height: normal !important;
}
</style>
