<template>
  <div>
    <div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnQuery"
          >查询</el-button
        >
      </div>
      <div class="listBtn">
        <el-button
          type="primary"
          class="commonbutton"
          @click="btnImportResult('pacs')"
          >导入检查结果</el-button
        >
      </div>
      <div class="listBtn">
        <el-button
          type="primary"
          class="commonbutton"
          @click="btnImportResult('lis')"
          >导入检验结果</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnReport(true)"
          >预览报告</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnReport(false)"
          >打印报告</el-button
        >
      </div>
      <div class="listBtn">
        <el-button
          type="primary"
          class="commonbutton"
          @click="btnReportExport(false)"
          >导出 pdf 报告</el-button
        >
      </div>
      <div class="listBtn">
        <el-button
          type="primary"
          class="commonbutton"
          @click="btnGetReport('Y')"
          >领取报告</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnUpReport"
          >上传Web</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="btnCheckHistory"
          >历次结果</el-button
        >
      </div>
      <div class="listBtn">
        <!-- <download-excel :fields="jsonFields" :fetch="btnExport" type="xls" :name="xlsName">
                    <el-button type="" class="commonbutton" style="width:100%">人员信息导出</el-button>
                </download-excel> -->
        <el-button type="" class="commonbutton" @click="btnExport"
          >人员信息导出</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="exportZip"
          >导出Zip</el-button
        >
      </div>
      <div class="listBtn">
        <el-button type="primary" class="commonbutton" @click="exportJpg"
          >导出Jpg</el-button
        >
      </div>
    </div>
    <div>
      <!-- 通用进度条 -->
      <el-dialog
        title="数据处理中……"
        :visible.sync="elProgress.display"
        width="640px"
        :show-close="false"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <ElProgressOCX />
      </el-dialog>

      <el-dialog
        title="报告领取"
        :visible.sync="dialogGetReport"
        width="350px"
        :show-close="false"
        :close-on-click-modal="false"
        :append-to-body="true"
      >
        <div>
          <div class="query" style="display: flex; margin: 0 0 30px 10px">
            <span class="spanClass">领取人</span>
            <el-input
              placeholder="领取人"
              v-model="receiveReport.reportReceiveName"
              size="small"
              clearable
              style="width: 120px"
            />
          </div>
          <div style="display: flex; justify-content: space-between">
            <div></div>
            <div style="display: flex">
              <div>
                <el-button
                  type="primary"
                  class="commonbutton"
                  @click="btnGetReportOk"
                  >确定</el-button
                >
              </div>
              <div style="margin-left: 10px">
                <el-button
                  type="primary"
                  class="commonbutton"
                  @click="dialogGetReport = false"
                  >取消</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </el-dialog>

      <el-dialog
        title="历次结果"
        :visible.sync="dialogVisibleCheckHistory"
        :close-on-click-modal="false"
        width="900px"
      >
        <div>
          <el-tabs v-model="tabChoosed">
            <!---->
            <el-tab-pane label="明细结果" name="2">
              <CheckDetails
                :patientRegisterId="dataTransOpts.tableS.patient_register.id"
                :refParams="{ place: 'doctor' }"
              />
            </el-tab-pane>
            <el-tab-pane label="本次图文报告" name="4">
              <ImageTextReport :refParams="{ place: 'doctor' }" />
            </el-tab-pane>
            <!-- <el-tab-pane label="项目对比" name="4">
                        <SumItemsType :patientId="doctorCheck.prBase.patientId" />
                    </el-tab-pane> -->
            <el-tab-pane label="横向对比" name="5">
              <SumItems
                :patientId="dataTransOpts.tableS.patient_register.id"
                :refParams="{ place: 'doctor' }"
              />
            </el-tab-pane>
            <el-tab-pane label="历次综述" name="6">
              <SumHistory
                :patientId="dataTransOpts.tableS.patient_register.id"
                :refParams="{ place: 'doctor' }"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import { arrayExistObj, deepCopy, parseID, dddw } from "../../utlis/proFunc";
import ElProgressOCX from "../report/ElProgressOCX.vue";
//import PatientRegisterList from "../doctorCheck/PatientRegisterList.vue";
import CheckDetails from "../../components/sumDoctorCheck/CheckDetails.vue";
import SumItemsType from "../../components/sumDoctorCheck/SumItemsType.vue";
import SumItems from "../../components/sumDoctorCheck/SumItems.vue";
import SumHistory from "../../components/sumDoctorCheck/SumHistory.vue";
import OccDisease from "../../components/occDisease/OccDisease.vue";
import ImageTextReport from "../../components/occDisease/ImageTextReport.vue";
import { exportJsonToExcel } from "../../utlis/Export2Excel";

export default {
  components: {
    //PatientRegisterList,
    ElProgressOCX,
    CheckDetails,
    SumItemsType,
    SumItems,
    SumHistory,
    OccDisease,
    ImageTextReport,
  },
  data() {
    return {
      dialogGetReport: false,
      dialogVisibleCheckHistory: false,
      tabChoosed: "2",
      receiveReport: {
        patientRegisterIds: [],
        isReceiveReport: "Y",
        reportReceiveName: "", //// 报告领取人
      },
      jsonFields: {},
      xlsName: "",

      dragCol: [
        { label: "序号", prop: "sn", minWidth: 40, align: "center" },
        { label: "打印", prop: "isReportPrint", minWidth: 60, align: "center" },
        {
          label: "领取",
          prop: "isReceiveReport",
          minWidth: 60,
          align: "center",
        },
        {
          label: "体检进度",
          prop: "completeFlag",
          minWidth: 90,
          align: "center",
        },
        {
          label: "体检日期",
          prop: "medicalStartDate",
          minWidth: 100,
          align: "center",
        },
        {
          label: "单位名称",
          prop: "org",
          minWidth: 180,
          align: "left",
          showTooltip: true,
        },
        {
          label: "部门名称",
          prop: "dept",
          minWidth: 150,
          align: "left",
          showTooltip: true,
        },
        { label: "姓名", prop: "patientName", minWidth: 60, align: "center" },
        { label: "性别", prop: "sexName", minWidth: 60, align: "center" },
        { label: "年龄", prop: "age", minWidth: 60, align: "center" },
        { label: "民族", prop: "nationName", minWidth: 70, align: "center" },
        { label: "身份证号", prop: "idNo", minWidth: 160, align: "center" },
        {
          label: "条码号",
          prop: "patientRegisterNo",
          minWidth: 110,
          align: "center",
        },
        { label: "档案号", prop: "patientNo", minWidth: 80, align: "center" },
        { label: "次数", prop: "medicalTimes", minWidth: 60, align: "center" },
        { label: "备注", prop: "remark", minWidth: 150, align: "left" },
        {
          label: "分组/套餐",
          prop: "groupPack",
          minWidth: 150,
          align: "center",
        },
        {
          label: "手机",
          prop: "mobileTelephone",
          minWidth: 130,
          align: "center",
        },
        { label: "电话", prop: "telephone", minWidth: 130, align: "center" },
        { label: "出生日期", prop: "birthDate", minWidth: 90, align: "center" },
        {
          label: "婚姻",
          prop: "maritalStatusName",
          minWidth: 70,
          align: "center",
        },
        {
          label: "地址",
          prop: "address",
          minWidth: 400,
          align: "left",
          showTooltip: true,
        },
        {
          label: "体检卡号",
          prop: "medicalCardNo",
          minWidth: 90,
          align: "center",
        },
        { label: "工卡号", prop: "jobCardNo", minWidth: 90, align: "center" },
        {
          label: "体检类别",
          prop: "medicalTypeName",
          minWidth: 100,
          align: "center",
        },
        {
          label: "人员类别",
          prop: "personnelTypeName",
          minWidth: 100,
          align: "center",
        },
        { label: "职务", prop: "jobPost", minWidth: 70, align: "center" },
        { label: "职称", prop: "jobTitle", minWidth: 70, align: "center" },
        { label: "介绍人", prop: "salesman", minWidth: 80, align: "center" },
        { label: "VIP", prop: "isVip", minWidth: 80, align: "center" },
        {
          label: "总检医生",
          prop: "summaryDoctorName",
          minWidth: 90,
          align: "center",
        },
        {
          label: "总检日期",
          prop: "summaryDate",
          minWidth: 140,
          align: "center",
        },
        {
          label: "审核医生",
          prop: "auditDoctorName",
          minWidth: 90,
          align: "center",
        },
        {
          label: "审核日期",
          prop: "auditDate",
          minWidth: 140,
          align: "center",
        },
        {
          label: "登记人",
          prop: "registerName",
          minWidth: 80,
          align: "center",
        },
        {
          label: "登记时间",
          prop: "registerDate",
          minWidth: 140,
          align: "center",
        },
        {
          label: "打印人",
          prop: "reportPrintName",
          minWidth: 70,
          align: "center",
        },
        {
          label: "领取人",
          prop: "reportReceiveName",
          minWidth: 70,
          align: "center",
        },
        {
          label: "领取时间",
          prop: "reportReceiveDate",
          minWidth: 140,
          align: "center",
        },
        { label: "锁住", prop: "isLock", minWidth: 60, align: "center" },
        {
          label: "预约备单",
          prop: "isUploadAppoint",
          minWidth: 90,
          align: "center",
        },
        { label: "上传", prop: "isUpload", minWidth: 60, align: "center" },
        // { label: "标准金额", prop: "standardAmount", minWidth: 80, align: "center" },
        // { label: "应收金额", prop: "receivableAmount", minWidth: 80, align: "center" },
        // { label: "实收金额", prop: "chargeAmount", minWidth: 80, align: "center" },
        // { label: "支付方式", prop: "chargePayMode", minWidth: 80, align: "center" },
      ],
    };
  },

  created() {},

  //挂载完成
  mounted() {
    this.dataTransOpts.tableS.patient_register.id = "";
    // this.getPatientRegister(this.dataTransOpts.tableS.patient_register.patientRegisterNo)
  },

  computed: {
    ...mapState([
      "dict",
      "elProgress",
      "dataTransOpts",
      "patientRegister",
      "doctorCheck",
      "sumDoctorCheck",
      "report",
    ]),
  },

  methods: {
    dddw,
    btnQuery() {
      this.patientRegister.query.times++;
    },
    exportJpg() {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }

      if (
        !(
          this.dataTransOpts.tableM.patient_register &&
          this.dataTransOpts.tableM.patient_register.length > 0
        )
      ) {
        this.$message.warning({ showClose: true, message: "请勾选择记录！" });
        return;
      }
      this.$peisAPI
        .openDirectoryDialog()
        .then((res) => {
          let lres = JSON.parse(res);
          if (lres.code > -1 && lres.data) {
            this.report2Jpg(JSON.parse(lres.data).directory);
          }
          console.log("lres", lres);
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    async report2Jpg(path) {
      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      let token = window.sessionStorage.getItem("token");
      let toOutShell = {
        localPath: path,
        token,
        patientRegisterId: "",
      };

      for (
        let i = 0;
        i < this.dataTransOpts.tableM.patient_register.length;
        i++
      ) {
        let e = this.dataTransOpts.tableM.patient_register[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.dataTransOpts.tableM.patient_register.length
        );

        // 导出pdf
        try {
          toOutShell.patientRegisterId = e.patientRegisterId;
          let jsonToOutShell = JSON.stringify(toOutShell);
          console.log("toOutShell", jsonToOutShell);
          let res = await this.$peisAPI.exportDcmjpg(jsonToOutShell);
          if (JSON.parse(res).code < 0) {
            console.log("this.$peisAPI.exportDcmjpg err", res);
          }
        } catch (error) {
          console.log("error", error);
          this.$message.warning({ showClose: true, message: error });
        }
      }
      this.elProgress.display = false;
    },

    // 历次结果
    btnCheckHistory() {
      if (!this.dataTransOpts.tableS.patient_register.id) return;
      this.dialogVisibleCheckHistory = true;
      this.dataTransOpts.refresh.sumDoctor.M++; //刷新历次明细
      this.dataTransOpts.plus.OccDisease++; //刷新图文报告
    },

    exportZip() {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }

      if (
        !(
          this.dataTransOpts.tableM.patient_register &&
          this.dataTransOpts.tableM.patient_register.length > 0
        )
      ) {
        this.$message.warning({ showClose: true, message: "请勾选择记录！" });
        return;
      }
      this.$peisAPI
        .openDirectoryDialog()
        .then((res) => {
          let lres = JSON.parse(res);
          if (lres.code > -1 && lres.data) {
            this.report2Zip(JSON.parse(lres.data).directory);
          }
          console.log("lres", lres);
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    async report2Zip(path) {
      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      let token = window.sessionStorage.getItem("token");
      let toOutShell = {
        localPath: path,
        token,
        patientRegisterId: "",
      };

      for (
        let i = 0;
        i < this.dataTransOpts.tableM.patient_register.length;
        i++
      ) {
        let e = this.dataTransOpts.tableM.patient_register[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.dataTransOpts.tableM.patient_register.length
        );

        // 导出pdf
        try {
          toOutShell.patientRegisterId = e.patientRegisterId;
          let jsonToOutShell = JSON.stringify(toOutShell);
          console.log("toOutShell", jsonToOutShell);
          let res = await this.$peisAPI.exportDcmZip(jsonToOutShell);
          if (JSON.parse(res).code < 0) {
            console.log("this.$peisAPI.exportDcmZip err", res);
          }
        } catch (error) {
          console.log("error", error);
          this.$message.warning({ showClose: true, message: error });
        }
      }
      this.elProgress.display = false;
    },

    // 导入结果
    btnImportResult(checkType) {
      if (!this.dataTransOpts.tableS.patient_register.id) {
        this.$message.warning({ showClose: true, message: "请先选择记录！" });
        return;
      }

      let patientRegisterId = this.dataTransOpts.tableS.patient_register.id;
      let url = "/api/app/ImportLisResult/ImportResultByPatientRegisterId";
      switch (checkType) {
        case "pacs":
          url = "/api/app/ImportPacsResult/ImportResultByPatientRegisterId";
          postapi(url, { patientRegisterId })
            .then((res) => {
              if (res.code > -1) {
                return postapi(
                  "/api/app/ImportElectrocardiogramResult/ImportElectrocardiogramResultByPatientRegisterId",
                  { patientRegisterId }
                );
              }
            })
            .then((res) => {
              if (res && res.code > -1) {
                this.$message.success({
                  showClose: true,
                  message: "导入成功！",
                });
              }
            });
          break;
        default:
          postapi(url, { patientRegisterId }).then((res) => {
            if (res.code > -1) {
              this.$message.success({ showClose: true, message: "导入成功！" });
            }
          });
          break;
      }
    },

    //领取体检报告（提交）
    btnGetReportOk() {
      postapi(
        "/api/app/PatientRegister/BatchUpdatePatientRegisterReportReceive",
        this.receiveReport
      ).then((res) => {
        if (res.code > -1) {
          this.$message.success({ showClose: true, message: "操作成功！" });
          let reportReceiveDate = moment(new Date()).format(
            "yyyy-MM-DD HH:mm:ss"
          );
          let lfind = -1;
          this.receiveReport.patientRegisterIds.forEach((patientRegisterId) => {
            lfind = arrayExistObj(
              this.patientRegister.prList,
              "patientRegisterId",
              patientRegisterId
            );
            if (lfind > -1) {
              this.patientRegister.prList[lfind].isReceiveReport =
                this.receiveReport.isReceiveReport;
              this.patientRegister.prList[lfind].reportReceiveName =
                this.receiveReport.reportReceiveName;
              this.patientRegister.prList[lfind].reportReceiveDate =
                reportReceiveDate;
            }
          });
          this.dialogGetReport = false;
        }
      });
    },

    //领取体检报告(按钮)
    btnGetReport(isReceiveReport) {
      //console.log('this.dataTransOpts.tableS.patient_register.id',this.dataTransOpts.tableS.patient_register.id,this.dataTransOpts.tableM.patient_register)
      let rd = [];
      if (
        this.dataTransOpts.tableM.patient_register &&
        this.dataTransOpts.tableM.patient_register.length > 0
      ) {
        rd = rd.concat(this.dataTransOpts.tableM.patient_register);
      }
      if (rd.length == 0) {
        if (this.dataTransOpts.tableS.patient_register.id)
          rd.push({
            patientRegisterId: this.dataTransOpts.tableS.patient_register.id,
          });
      }
      if (rd.length == 0) {
        this.$message.warning({
          showClose: true,
          message: "请先勾选或选择记录（有勾选人员时，仅操作勾选的记录）！",
        });
        return;
      }
      let lfind = arrayExistObj(
        this.patientRegister.prList,
        "patientRegisterId",
        rd[0].patientRegisterId
      );
      if (lfind > -1) {
        this.receiveReport.reportReceiveName =
          this.patientRegister.prList[lfind].patientName;
      }

      this.receiveReport.patientRegisterIds = [];
      this.receiveReport.isReceiveReport = isReceiveReport;
      rd.forEach((e) => {
        this.receiveReport.patientRegisterIds.push(e.patientRegisterId);
      });
      //
      // {
      //     "patientRegisterIds": [
      //         "3fa85f64-5717-4562-b3fc-2c963f66afa6"
      //     ],
      //     "isReceiveReport": "string",
      //     "reportReceiveName": "string"
      // }

      this.dialogGetReport = true;
    },

    //上传报告
    async btnUpReport() {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }

      if (
        this.dataTransOpts.tableM.patient_register &&
        this.dataTransOpts.tableM.patient_register.length > 0
      ) {
        this.elProgress.display = true;
        this.elProgress.percentage = 0;

        let ReportCode = "0005";
        let token = window.sessionStorage.getItem("token");
        let user = window.sessionStorage.getItem("user");
        let toOutShell = {
          ReportCode,
          token,
          isBuildImage: "N",
          IsUploadPdf: "N",
          preViewCanPrint: "Y",
          BusinessCode: "",
          Parameters: [
            { Name: "printer", Value: user },
            { Name: "LTS", Value: "Y" }, //Y、N   N只看不能打印
            { Name: "firstPage", Value: "pic/peisReportFirstPage.jpg" }, //报告首页主图
            { Name: "pageHeader", Value: "pic/peisReportPageHeader.jpg" }, //报告页眉图片
            { Name: "pageFooter", Value: "pic/peisReportPageFooter.jpg" }, //报告页脚图片
            { Name: "orgSign", Value: "pic/orgSign.png" }, // 体检章
            { Name: "picExtOne", Value: "pic/hisLog.jpg" }, // 院徽
            { Name: "picExtTwo", Value: "pic/orgSignCom.png" }, // 单位公章
            { Name: "resultSign", Value: "pic/resultSign.png" }, // 结果章，如：职业病（本次体检未发现职业性异常）
            { Name: "picExtThree", Value: "pic/peisQrCode.jpg" }, // 公众号二维码
            { Name: "picExtFour", Value: "pic/peisQrCodeMini.jpg" }, // 小程序二维码
          ],
          IsHealthReport: "Y",
        };

        for (
          let i = 0;
          i < this.dataTransOpts.tableM.patient_register.length;
          i++
        ) {
          let e = this.dataTransOpts.tableM.patient_register[i];
          this.elProgress.percentage = Math.floor(
            ((i + 1) * 100) / this.dataTransOpts.tableM.patient_register.length
          );

          // 调上传接口
          try {
            if (e.completeFlag == "3") {
              toOutShell.BusinessCode = e.patientRegisterId;
              toOutShell.customerOrgName = e.customerOrgName || ""; // 增加单位名称参数
              toOutShell.departmentName = e.departmentName || "";
              let jsonToOutShell = JSON.stringify(toOutShell);
              console.log("toOutShell", jsonToOutShell);
              let res = await this.$peisAPI.upLoadReportPdf(jsonToOutShell);
              if (JSON.parse(res).code < 0) {
                this.$message.error({ showClose: true, message: res.message });
                console.log("$peisAPI.upLoadReportPdf err", res);
              } else {
                // 上传成功 ，更新上传传状态
                e.isUpload = "Y";
                // console.log('btnUpReport success', JSON.parse(res))
              }
            } else {
              let patientRegisterId = e.patientRegisterId;
              let res2 = await postapi(
                "/api/app/TransToWebPeis/TransPatientRegisterByPatientRegisterId",
                { patientRegisterId }
              );
              if (res2.code == -1) {
                console.log("TransToWebPeis err", res2);
              } else {
                // 上传成功 ，更新备单状态
                e.isUploadAppoint = "Y";
              }
            }
          } catch (error) {
            console.log("error", error);
            this.$message.warning({ showClose: true, message: error });
          }
        }
        this.elProgress.display = false;
      } else {
        this.$message.warning({ showClose: true, message: "请勾选择记录！" });
        return;
      }
    },

    //体检报告打印（预览）
    async btnReport(isPreview) {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }

      ///3a0c990e-5756-2dc0-19d5-69a617fe4048 isPatientOccupationalDisease patientRegisterId  completeFlag  isAudit
      let rds = this.getChoosedRds();
      if (rds.length == 0) return;

      let ReportCode = "0005";
      if (rds[0].isPatientOccupationalDisease == "Y") ReportCode = "0006";

      let token = window.sessionStorage.getItem("token");
      let user = window.sessionStorage.getItem("user");
      let toOutShell = {
        ReportCode,
        token,
        isBuildImage: "N",
        IsUploadPdf: "N",
        preViewCanPrint: "Y",
        BusinessCode: rds[0].patientRegisterId,
        Parameters: [
          { Name: "printer", Value: user },
          { Name: "LTS", Value: "Y" }, //Y、N   N只看不能打印
          { Name: "firstPage", Value: "pic/peisReportFirstPage.jpg" }, //报告首页主图
          { Name: "pageHeader", Value: "pic/peisReportPageHeader.jpg" }, //报告页眉图片
          { Name: "pageFooter", Value: "pic/peisReportPageFooter.jpg" }, //报告页脚图片
          {
            Name: "orgSign",
            Value:
              rds[0].isPatientOccupationalDisease == "Y"
                ? "pic/orgSignOcc.png"
                : "pic/orgSign.png",
          }, // 体检章
          { Name: "picExtOne", Value: "pic/hisLog.jpg" }, // 院徽
          { Name: "picExtTwo", Value: "pic/orgSignCom.png" }, // 单位公章
          { Name: "resultSign", Value: "pic/resultSign.png" }, // 结果章，如：职业病（本次体检未发现职业性异常）
          { Name: "picExtThree", Value: "pic/peisQrCode.jpg" }, // 公众号二维码
          { Name: "picExtFour", Value: "pic/peisQrCodeMini.jpg" }, // 小程序二维码
          { Name: "picExtFive", Value: "pic/sumDoctorSign.jpg" }, // 总检签名（部份企业固定才用）
          { Name: "picExtSix", Value: "pic/auditDoctorSign.jpg" }, // 总检审核签名（部份企业固定才用）
        ],
      };

      // 总检审核后才能打印
      if (rds[0].completeFlag != "3") toOutShell.preViewCanPrint = "N";
      if (toOutShell.preViewCanPrint == "Y" && rds[0].isAudit == "N") {
        let sysParmId = "medical_report_print_after_summary_check_is_audit";
        let sysParam = await postapi(
          "/api/app/SysParmValue/GetSysParmValueBySysParmId",
          { sysParmId }
        );
        if (sysParam.data.toUpperCase() == "Y")
          toOutShell.preViewCanPrint = "N";
      }

      // let res = await postapi(`/api/app/printreport/getpeisreport?PatientRegisterId=${this.patientRegister.patientRegisterId}`)
      // toOutShell.ReportTable = res.data
      let JSONtoOutShell = JSON.stringify(toOutShell);
      console.log("$peisAPI.printPre", JSONtoOutShell);
      if (isPreview) {
        this.$peisAPI
          .printPre(JSONtoOutShell)
          .then((res) => {
            if (JSON.parse(res).code < 0) {
              this.$message.warning({
                showClose: true,
                message: JSON.parse(res).message,
              });
            }
          })
          .catch((err) => {
            console.log("预览体检报告错误", err);
            this.$message.warning({ showClose: true, message: `${err}` });
          });
      } else {
        let lfind = -1;
        for (let i = 0; i < rds.length; i++) {
          let rd = rds[i];

          toOutShell.ReportCode =
            rd.isPatientOccupationalDisease == "Y" ? "0006" : "0005";
          toOutShell.BusinessCode = rd.patientRegisterId;
          if (rd.completeFlag != "3") toOutShell.preViewCanPrint = "N";
          if (toOutShell.preViewCanPrint == "Y" && rd.isAudit == "N") {
            let sysParmId = "medical_report_print_after_summary_check_is_audit";
            let sysParam = await postapi(
              "/api/app/SysParmValue/GetSysParmValueBySysParmId",
              { sysParmId }
            );
            if (sysParam.data.toUpperCase() == "Y")
              toOutShell.preViewCanPrint = "N";
          }

          if (toOutShell.preViewCanPrint == "N") {
            this.$message.warning({
              showClose: true,
              message: "未总检或未审核，不可打印报告",
            });
            continue;
          }
          JSONtoOutShell = JSON.stringify(toOutShell);
          try {
            let lres = await this.$peisAPI.print(JSONtoOutShell);
            if (JSON.parse(lres).code < 0) {
              this.$message.warning({
                showClose: true,
                message: JSON.parse(lres).message,
              });
            } else {
              postapi(
                "/api/app/patientregister/updatepatientregisterreportprinttimesmany",
                [rd.patientRegisterId]
              ).then((res) => {
                if (res.code > -1) {
                  lfind = arrayExistObj(
                    this.patientRegister.prList,
                    "patientRegisterId",
                    rd.patientRegisterId
                  );
                  if (lfind > -1)
                    this.patientRegister.prList[lfind].isReportPrint = "Y";
                }
              });
            }
          } catch (error) {
            this.$message.warning({ showClose: true, message: error });
          }
        }
      }
    },

    // 导出 pdf 报告
    btnReportExport() {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }

      if (
        !(
          this.dataTransOpts.tableM.patient_register &&
          this.dataTransOpts.tableM.patient_register.length > 0
        )
      ) {
        this.$message.warning({ showClose: true, message: "请勾选择记录！" });
        return;
      }

      this.$peisAPI
        .openDirectoryDialog()
        .then((res) => {
          let lres = JSON.parse(res);
          if (lres.code > -1 && lres.data) {
            this.report2pdf(JSON.parse(lres.data).directory);
          }
          console.log("lres", lres);
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },

    async report2pdf(path) {
      if (this.dataTransOpts.tableM.patient_register.length < 1) return;
      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      let ReportCode = "0005";
      if (
        this.dataTransOpts.tableM.patient_register[0]
          .isPatientOccupationalDisease == "Y"
      )
        ReportCode = "0006";
      let token = window.sessionStorage.getItem("token");
      let user = window.sessionStorage.getItem("user");
      let toOutShell = {
        ReportCode,
        token,
        isBuildImage: "N",
        IsUploadPdf: "N",
        preViewCanPrint: "Y",
        BusinessCode: "",
        Parameters: [
          { Name: "printer", Value: user },
          { Name: "LTS", Value: "Y" }, //Y、N   N只看不能打印
          { Name: "firstPage", Value: "pic/peisReportFirstPage.jpg" }, //报告首页主图
          { Name: "pageHeader", Value: "pic/peisReportPageHeader.jpg" }, //报告页眉图片
          { Name: "pageFooter", Value: "pic/peisReportPageFooter.jpg" }, //报告页脚图片
          {
            Name: "orgSign",
            Value:
              this.dataTransOpts.tableM.patient_register[0]
                .isPatientOccupationalDisease == "Y"
                ? "pic/orgSignOcc.png"
                : "pic/orgSign.png",
          }, // 体检章
          { Name: "picExtOne", Value: "pic/hisLog.jpg" }, // 院徽
          { Name: "picExtTwo", Value: "pic/orgSignCom.png" }, // 单位公章
          { Name: "resultSign", Value: "pic/resultSign.png" }, // 结果章，如：职业病（本次体检未发现职业性异常）
          { Name: "picExtThree", Value: "pic/peisQrCode.jpg" }, // 公众号二维码
          { Name: "picExtFour", Value: "pic/peisQrCodeMini.jpg" }, // 小程序二维码
        ],
        IsHealthReport: "Y",
      };

      for (
        let i = 0;
        i < this.dataTransOpts.tableM.patient_register.length;
        i++
      ) {
        let e = this.dataTransOpts.tableM.patient_register[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.dataTransOpts.tableM.patient_register.length
        );

        // 导出pdf
        try {
          // 石家庄长城 手动导出没有总检也可以导出
          //if (e.completeFlag == "3") {
            toOutShell.BusinessCode = e.patientRegisterId;
            toOutShell.ExportDirectory = `${path}\\${e.patientName}_${e.patientRegisterNo}.pdf`;
            toOutShell.customerOrgName = e.customerOrgName || ""; // 增加单位名称参数
            toOutShell.departmentName = e.departmentName || "";

            let jsonToOutShell = JSON.stringify(toOutShell);
            console.log("toOutShell", jsonToOutShell);
            let res = await this.$peisAPI.exportToPdfPre(jsonToOutShell);
            if (JSON.parse(res).code < 0) {
              console.log("this.$peisAPI.exportToPdfPre err", res);
            }
          //}
        } catch (error) {
          console.log("error", error);
          this.$message.warning({ showClose: true, message: error });
        }
      }
      this.elProgress.display = false;
    },

    //按条码号查个人数据
    getPatientRegister(patientRegisterNo) {
      if (!patientRegisterNo) return;
      postapi(
        "/api/app/patientregister/GetAlreadyRegisterPatientRegisterByNo",
        { patientRegisterNo }
      ).then((res) => {
        if (res.code > -1) {
          this.dataTransOpts.tableS.patient_register = deepCopy(res.data);
        }
      });
    },

    // 通用判断 是否有选中或勾选记录（同时有选中与勾选记录时，以勾选记录为主）
    getChoosedRds() {
      let rd = [];
      if (
        this.dataTransOpts.tableM.patient_register &&
        this.dataTransOpts.tableM.patient_register.length > 0
      ) {
        rd = rd.concat(this.dataTransOpts.tableM.patient_register);
      }
      if (rd.length == 0) {
        if (this.dataTransOpts.tableS.patient_register.id) {
          let lfind = arrayExistObj(
            this.patientRegister.prList,
            "patientRegisterId",
            this.dataTransOpts.tableS.patient_register.id
          );
          if (lfind > -1)
            rd.push(
              this.patientRegister.prList.slice(lfind, Number(lfind) + 1)
            );
        }
      }
      if (rd.length == 0) {
        this.$message.warning({
          showClose: true,
          message: "请先勾选或选择记录（有勾选人员时，仅操作勾选的记录）！",
        });
      }
      return rd;
    },

    //通用导出
    btnExport(elId) {
      require.ensure([], () => {
        const tHeader = [];
        const filterVal = [];
        this.dragCol.forEach((e) => {
          tHeader.push(e.label);
          filterVal.push(e.prop);
        });
        const list = this.patientRegister.prList.map((row, index) => {
          const newRow = { ...row }; // 创建副本，避免修改原数据
          // 使用对象映射优化数据转换
          newRow.sn = index + 1;
          if (newRow.completeFlag)
            newRow.completeFlag =
              newRow.isAudit == "Y"
                ? "已审核"
                : dddw(
                    this.dict.completeFlag,
                    "id",
                    newRow.completeFlag,
                    "displayName"
                  );
          newRow.isReportPrint = newRow.isReportPrint == "Y" ? "√" : "";
          if (newRow.idNo) newRow.idNo = "\u200C"+newRow.idNo;
          if (newRow.patientRegisterNo)
            newRow.patientRegisterNo = "\u200C" + newRow.patientRegisterNo;
          if (newRow.patientNo) newRow.patientNo = "\u200C" + newRow.patientNo;
          if (newRow.isLock) newRow.isLock = newRow.isLock == "Y" ? "√" : "";
          if (newRow.isVip) newRow.isVip = newRow.isVip == "Y" ? "√" : "";
          if (newRow.isUpload)
            newRow.isUpload = newRow.isUpload == "Y" ? "√" : "";
          if (newRow.isUploadAppoint)
            newRow.isUploadAppoint = newRow.isUploadAppoint == "Y" ? "√" : "";
          if (newRow.isReceiveReport)
            newRow.isReceiveReport = newRow.isReceiveReport == "Y" ? "√" : "";

          //if (e.sexId) e.sexId = dddw(this.dict.sex, "id", e.sexId, "displayName")
          // if (e.patientRegisterNo) e.patientRegisterNo = " " + e.patientRegisterNo
          // if (e.patientNo) e.patientNo = " " + e.patientNo
          // if (e.idNo) e.idNo = " " + e.idNo
          // if (e.medicalPackageId !== this.dict.personOrgId && e.customerOrgId === this.dict.personOrgId) {
          //     e.packGroup = e.medicalPackageName  // dddw(this.dict.medicalPackage, "id", e.medicalPackageId, "displayName")
          // } else if (e.medicalPackageId !== this.dict.personOrgId && e.customerOrgId !== this.dict.personOrgId) {
          //     e.packGroup = e.customerOrgGroupName // dddw(this.dict.customerOrgGroupAll, "id", e.customerOrgGroupId, "displayName")
          // }
          //if (e.nationId) e.nationId = dddw(this.dict.nation, "id", e.nationId, "displayName")
          // if (e.idNo) e.idNo = " " + e.idNo
          // if (e.mobileTelephone) e.mobileTelephone = " " + e.mobileTelephone
          // if (e.telephone) e.telephone = " " + e.telephone

          if (newRow.birthDate)
            newRow.birthDate = moment(newRow.birthDate).format("yyyy-MM-DD");

          return newRow;
        });
        const data = list.map((v) => filterVal.map((j) => v[j]));
        exportJsonToExcel(
          tHeader,
          data,
          "人员列表" + moment(new Date()).format("yyyyMMDDHHmmss")
        ); //"列表excel"  是下载后的表名 可修改
      });

      // this.dragCol.forEach((e) => {
      //     switch (e.prop) {
      //         case 'medicalStartDate':  // 避免科学计数或数据转换
      //         case 'birthDate':
      //         case 'summaryDate':
      //         case 'auditDate':
      //         case 'registerDate':
      //         case 'reportReceiveDate':
      //         case 'idNo':
      //         case 'patientRegisterNo':
      //         case 'patientNo':
      //         case 'mobileTelephone':
      //         case 'telephone':
      //             this.jsonFields[e.label] = {
      //                 field: e.prop,
      //                 callback: value => {
      //                     return value ? `\u200C${value}` : '';
      //                 }
      //             }
      //             break;

      //         default:
      //             this.jsonFields[e.label] = e.prop;
      //             break;
      //     }

      // });

      // let tableDatas = deepCopy(this.patientRegister.prList)
      // tableDatas.forEach((e, index) => {
      //     e.sn = index + 1
      //     if (e.completeFlag) e.completeFlag = e.isAudit == "Y" ? "已审核" : dddw(this.dict.completeFlag, "id", e.completeFlag, "displayName")
      //     e.isReportPrint = e.isReportPrint == 'Y' ? '√' : ''
      //     if (e.isLock) e.isLock = e.isLock == 'Y' ? '√' : ''
      //     if (e.isVip) e.isVip = e.isVip == 'Y' ? '√' : ''
      //     if (e.isUpload) e.isUpload = e.isUpload == 'Y' ? '√' : ''
      //     if (e.isUploadAppoint) e.isUploadAppoint = e.isUploadAppoint == 'Y' ? '√' : ''
      //     if (e.isReceiveReport) e.isReceiveReport = e.isReceiveReport == 'Y' ? '√' : ''

      //     //if (e.sexId) e.sexId = dddw(this.dict.sex, "id", e.sexId, "displayName")
      //     // if (e.patientRegisterNo) e.patientRegisterNo = " " + e.patientRegisterNo
      //     // if (e.patientNo) e.patientNo = " " + e.patientNo
      //     // if (e.idNo) e.idNo = " " + e.idNo
      //     // if (e.medicalPackageId !== this.dict.personOrgId && e.customerOrgId === this.dict.personOrgId) {
      //     //     e.packGroup = e.medicalPackageName  // dddw(this.dict.medicalPackage, "id", e.medicalPackageId, "displayName")
      //     // } else if (e.medicalPackageId !== this.dict.personOrgId && e.customerOrgId !== this.dict.personOrgId) {
      //     //     e.packGroup = e.customerOrgGroupName // dddw(this.dict.customerOrgGroupAll, "id", e.customerOrgGroupId, "displayName")
      //     // }
      //     //if (e.nationId) e.nationId = dddw(this.dict.nation, "id", e.nationId, "displayName")
      //     // if (e.idNo) e.idNo = " " + e.idNo
      //     // if (e.mobileTelephone) e.mobileTelephone = " " + e.mobileTelephone
      //     // if (e.telephone) e.telephone = " " + e.telephone

      //     if (e.birthDate) e.birthDate = moment(e.birthDate).format("yyyy-MM-DD")

      // })
      // this.xlsName = '人员列表' + moment(new Date()).format('yyyyMMDDHHmmss') + '.xls'
      // return tableDatas;
    },
  },

  //监听事件()
  watch: {
    // 强制刷新人员登记信息
    "dataTransOpts.refresh.patient_register.S": {
      // immediate:true,
      handler(newVal, oldVal) {
        console.log(
          `watch 组合项目列表 newVal: ${newVal} oldVal: ${oldVal} patient_register.id: ${this.dataTransOpts.tableS.patient_register.patientRegisterNo}`
        );
        this.getPatientRegister(
          this.dataTransOpts.tableS.patient_register.patientRegisterNo
        );
        // this.dataTransOpts.refresh.register_check.M++
      },
    },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_button.css";

.listBtn {
  margin-top: 10px;
  /*
    text-align: center;
    */
}

.btnClass {
  width: 100px;
}

.spanClass {
  font-size: 14px;
  padding: 5px 2px 0 0;
}
</style>