<template>
  <div>
    <div>
      <div class="middlebox">
        <div class="contenttitle">
          体检查询 /
          <span class="contenttitleBold">体检报告</span>
        </div>
      </div>
      <div>
        <!--查询条件-->
        <PatientRegisterQueryNobtn orgEnable="Y" @triggerQuery="triggerQuery" />
      </div>
      <div style="display: flex;margin-top:7px">
        <div :style="'display: block; width:' + (window.pageWidth - 110 - 10) + 'px;'">

          <!--显示列表-->
          <div style="display: flex">
            <div :style="'background-color: #fff;padding: 10px;border-radius: 8px;width:' +
              Math.floor(((window.pageWidth - 110 - 60) * 3) / 4) +
              'px;'
              ">
              <div @contextmenu.prevent="onContextmenu">
                <u-table :data="tableDatas" border ref="info" id="info"
                  :height="(window.pageHeight < 600) ? 230 : (window.pageHeight - 370)" highlight-current-row
                  @row-click="rowClick" size="small" row-key="patientRegisterId"
                  @selection-change="handleSelectionChange" @row-contextmenu="rowContextmenu"
                  @table-body-scroll="scrollFull" use-virtual :row-height="35" big-data-checkbox
                  :data-changes-scroll-top="false">
                  <u-table-column :type="dragCol[0].type" width="40" align="center" />
                  <!--列可拖拽 key值很关键  -->
                  <u-table-column v-for="(item, index) in dragCol" v-if="index != 0" :key="`${item.label + index}`"
                    :type="dragCol[index].type" :min-width="dragCol[index].minWidth" :align="dragCol[index].align"
                    :label="dragCol[index].type ? '' : item.label" :prop="dragCol[index].prop"
                    :sortable="dragCol[index].type || dragCol[index].prop == 'sn' ? false : true"
                    :show-overflow-tooltip="dragCol[index].showTooltip">

                    <template slot-scope="scope">
                      <div v-if="dragCol[index].prop == 'sn'">
                        {{ scope.$index + 1 }}
                      </div>
                      <div v-else-if="dragCol[index].prop == 'completeFlag'"
                        :style="`color: ${setPrStatusColor(scope.row.isAudit, scope.row.completeFlag)}`">
                        {{ dddw(dict.completeFlag, "id", scope.row[dragCol[index].prop], "displayName") }}
                      </div>
                      <div v-else-if="dragCol[index].prop == 'birthDate'">
                        {{ scope.row[dragCol[index].prop].substring(0, 10) }}
                      </div>
                      <div v-else-if="dragCol[index].prop == 'isReportPrint'">
                        <i class="el-icon-printer" v-if="scope.row.isReportPrint == 'Y'"
                          style="font-size: 24px;color: green;"></i>
                      </div>
                      <div v-else-if="dragCol[index].prop == 'isLock'">
                        <i class="el-icon-lock" v-if="scope.row.isLock == 'Y'" style="font-size: 20px; color: red" />
                      </div>
                      <div v-else-if="
                        dragCol[index].prop == 'isVip' ||
                        dragCol[index].prop == 'isUpload' ||
                        dragCol[index].prop == 'isUploadAppoint' ||
                        dragCol[index].prop == 'isReceiveReport'
                      ">
                        <el-checkbox :value="scope.row[dragCol[index].prop] == 'Y'" true-label="Y" false-label="N" />
                      </div>
                      <div v-else>
                        {{ scope.row[dragCol[index].prop] }}
                      </div>
                    </template>

                  </u-table-column>

                </u-table>
                <div style="display: flex;justify-content:space-between;">
                  <div></div>
                  <div>
                    <span style="font-size:12px;">共：{{ loadOpts.totalCount }} 条记录，当前显示：{{ tableDatas.length
                    }}
                      条。</span>
                  </div>
                </div>
              </div>


            </div>
            <div :style="'background-color: #fff;padding: 10px;border-radius: 8px;margin-left: 10px;width:' +
              Math.floor((window.pageWidth - 110 - 45 - 8) / 4) +
              'px;'
              ">
              <RegisterCheckStatus :patientRegisterId="selectedRow.id" :brushTimes="refParams.brushSummary" />
            </div>
          </div>

          <!--项目状态-->
          <SumAsbItemStatus :patientRegisterId="selectedRow.id" :tabChoosed="'1'"
            :brushSummary="refParams.brushSummary" />
        </div>
        <!--按钮-->
        <div style="margin-left: 10px; ">
          <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="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">
            <el-dropdown @command="btnImportResult">
              <el-button type="primary" class="commonbutton">
                导入结果<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="pacs">导入检查结果</el-dropdown-item>
                <el-dropdown-item command="lis">导入检验结果</el-dropdown-item>
                <el-dropdown-item command="diAn">导入迪安结果</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="listBtn">
            <el-dropdown @command="btnExportComm">
              <el-button type="primary" class="commonbutton">
                导出<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="exp" @click="btnExport">人员信息导出</el-dropdown-item>
                <el-dropdown-item command="zip" @click="exportZip">导出Zip</el-dropdown-item>
                <el-dropdown-item command="jpg" @click="exportJpg">导出Jpg</el-dropdown-item>
                <el-dropdown-item command="pdf" @click="btnReportExport(false)">导出 pdf 报告</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </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="selectedRow.id" :refParams="refParams" />
            </el-tab-pane>
            <el-tab-pane label="图文报告" name="4">
              <ImageTextReport :refParams="refParams" />
            </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="selectedRow.id" :refParams="refParams" />
            </el-tab-pane>
            <el-tab-pane label="历次综述" name="6">
              <SumHistory :patientId="selectedRow.id" :refParams="refParams" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapActions } from "vuex";
import Sortable from "sortablejs";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import {
  tcdate,
  dddw, deepCopy,
  objCopy,
  arrayReduce,
  arrayExistObj, setPrStatusColor
} from "@/utlis/proFunc";

import PatientRegisterQueryNobtn from "../../components/report/PatientRegisterQueryNobtn.vue";
import RegisterCheckStatus from "../../components/report/RegisterCheckStatus.vue";
import SumAsbItemStatus from "../../components/sumDoctorCheck/SumAsbItemStatus.vue";
import ElProgressOCX from "../../components/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";
import PatientRegisterAsbItem from "../../components/patientRegister/patientRegisterAsbItem.vue";
import { UTable, UTableColumn } from "umy-ui";
export default {
  components: {
    PatientRegisterQueryNobtn,
    RegisterCheckStatus,
    PatientRegisterAsbItem, UTable, UTableColumn,
    SumAsbItemStatus,
    ElProgressOCX, CheckDetails, SumItemsType, SumItems, OccDisease, ImageTextReport
  },
  data() {
    return {
      patient_register_query_idno: 'Y', //身份证排他
      patient_register_query_name: 'N', //姓名排他
      dialogVisible: false,
      dialogCamera: false,
      dialogGuide: false,
      guideMsg: 'guideMsg',
      tabChoosed: "1",
      formInitData: {},      //体检登记初始表单数据
      editTimes: 0,

      rClickRow: null,       //右击的行
      rClickColumn: null,    //右击的列（预留）

      dom: null,   //用于滚动加载数据
      lazyLoading: false,  //是否懒加载中
      loadOpts: {
        totalCount: 0,
        skipCount: 0,
        maxResultCount: 100,
      },
      loadOptsInit: {},
      summary_check_doctor_alias: ["总检", "审核"],

      query: {
        cusOrgOCXdisp: '',
        ocxDatas: [],
        times: 0,  // 触发 查询条件 返回至列表组件
        queryType: '', // 点击按钮 还是在条码栏里回车等

        dateType: 'creationTime', //登记日期
        dateRange: null, //日期范围
        startDate: null,
        endDate: null,
        containRefuse: true, //包含弃检项目        
        times: 0, //触发查询次数
        customerOrgId: "", //体检单位ID                
        CustomerOrgParentId: "", //单位父级ID
        customerOrgFlag: true, //单位作为查询条件
        customerOrgRegister: { id: '' }, //单位体检次数 
        customerOrgGroupIds: [], //体检分组
        checkAsbs: null,
        patientRegisterNo: '',
        pacsNo: '',
        lisNo: '',
        patientName: '', //姓名
        sex: '', //性别
        idCardNo: '', //身份证号
        isReportPrint: '', // 报告是否打印
        isSeries: 'N',
        isSmsComplete: "N",
        isPhoneComplete: "N",
        diagnosisLevelId: [],
        medicalTypeIds: [],
        completeFlags: [],
        medicalConclusionId: [],
        personnelTypeIds: [],
        isRecoverGuide: '',
        personnelTypeId:'',
        completeFlag:'',

      },

      tableDatas: [],
      selectedRow: {},  // 当个选中
      checkedRows: [], // 勾选的记录数
      //拖动列  
      selectionCol: 0,
      dragCol: [
        { label: "勾选", type: "selection", minWidth: 40, align: "center" },
        { 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: 160, align: "center" },
        { label: "审核医生", prop: "auditDoctorName", minWidth: 90, align: "center" },
        { label: "审核日期", prop: "auditDate", minWidth: 160, align: "center" },
        { label: "登记人", prop: "registerName", minWidth: 80, align: "center" },
        { label: "登记时间", prop: "registerDate", minWidth: 160, 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" },
      ],

      // 按钮部份
      medical_report_print_after_summary_check_is_audit: 'N', // Y-审核后才可以打印报告，N-没审核未总检亦可以打印
      dialogGetReport: false,
      dialogVisibleCheckHistory: false,
      tabChoosed: "2",
      receiveReport: {
        patientRegisterIds: [],
        isReceiveReport: "Y",
        reportReceiveName: "", //// 报告领取人
      },
      jsonFields: {},
      xlsName: "",
      // 历次明细
      refParams: {
        place: 'doctor',
        brushSummary: 0,
        brushTimes: 0,
        patientRegisterId: ''
      }
    };
  },

  created() {

    this.loadOptsInit = Object.assign({}, this.loadOpts)
    this.tableDatas = []

    try {
      let LocalConfig = JSON.parse(
        window.localStorage.getItem("LocalConfig") || null
      );
      if (LocalConfig?.normal?.maxResultCount) {
        this.loadOpts.maxResultCount =
          LocalConfig.normal.maxResultCount;
      }
    } catch (error) {
      console.log('window.localStorage.getItem("LocalConfig")', error);
    }

    this.dictInit();
    this.selectedRow.id = ""
  },

  //挂载完成
  mounted() {
    this.$nextTick(() => {
      // this.scrollFull()

      // 监听列拖拽
      this.initColDrag()
    })
  },
  computed: {
    ...mapState(["window", "dict", "elProgress"]),
  },
  methods: {
    dddw, setPrStatusColor,
    //数据初始化
    dictInit() {
      //性别
      getapi("/api/app/sex").then((res) => {
        if (res.code != -1) {
          this.dict.sex = res.data;
        }
      });

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

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

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

      // 获取 是否审核才能打印报告
      postapi("/api/app/SysParmValue/GetSysParmValueBySysParmId",
        { sysParmId: "medical_report_print_after_summary_check_is_audit" }
      ).then(res => {
        if (res.code > -1) {
          this.medical_report_print_after_summary_check_is_audit = res.data.toUpperCase() || 'N'
        }
      });

      // 系统参数，获取 总检别名
      postapi('/api/app/SysParmValue/GetSysParmValueBySysParmId', { sysParmId: "summary_check_doctor_alias" })
        .then(res => {
          if (res.code > -1) {
            this.summary_check_doctor_alias = JSON.parse(res.data)
          }
        })

      // 获取系统参数 -- 身份证排他
      postapi("/api/app/SysParmValue/GetSysParmValueBySysParmId",
        { sysParmId: "patient_register_query_idno" }
      ).then((res) => {
        if (res.code > -1) {
          this.patient_register_query_idno = res.data || "Y";
        }
      });

      // 获取系统参数 -- 姓名排他
      postapi("/api/app/SysParmValue/GetSysParmValueBySysParmId",
        { sysParmId: "patient_register_query_name" }
      ).then((res) => {
        if (res.code > -1) {
          this.patient_register_query_name = res.data || "N";
        }
      });

    },

    // 触发查询
    triggerQuery(queryCondition) {
      console.log("triggerQuery.queryCondition", queryCondition)
      this.query = Object.assign({}, queryCondition)
      this.btnQuery()
    },

    handleSelectionChange(val) {
      this.checkedRows = val
    },

    //获取单位分组 /api/app/customer-org-group/in-customer-org-id/3a0c0444-d7a0-871f-4074-19faf1655caf
    // getCustomerOrgGroup(customerOrgld) {
    //   getapi(`/api/app/customer-org-group/in-customer-org-id/${customerOrgld}`)
    //     .then((res) => {
    //       console.log("getCustomerOrgGroup", res.data);
    //       if (res.code == 1) {
    //         this.patientRegister.customerOrgGroup = res.data;
    //       }
    //     });
    // },

    //点击体检次数行
    rowClick(row) {
      this.selectedRow = deepCopy(row)
      this.selectedRow.id = row.patientRegisterId

      // 刷新总检状态
      this.refParams.patientRegisterId = row.patientRegisterId
      this.refParams.brushSummary++  //同时刷新检查项目

    },

    async load() {
      this.loadOpts.skipCount++
      await this.reportQuery()
    },

    // 取消领取
    canselGetReport() {
      let body = {
        patientRegisterIds: [],
        isReceiveReport: 'N'
      }

      let rd = []
      if (this.checkedRows && this.checkedRows.length > 0) {
        rd = rd.concat(this.checkedRows)
      }
      if (rd.length == 0) {
        if (this.selectedRow.patientRegisterId) rd.push({ patientRegisterId: this.selectedRow.patientRegisterId })
      }
      if (rd.length == 0) {
        this.$message.warning({ showClose: true, message: "请先勾选或选择记录（有勾选人员时，仅操作勾选的记录）！" })
        return
      }

      rd.forEach(e => {
        body.patientRegisterIds.push(e.patientRegisterId)
      });


      postapi('/api/app/PatientRegister/BatchUpdatePatientRegisterReportReceive', body)
        .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
            body.patientRegisterIds.forEach(patientRegisterId => {
              lfind = arrayExistObj(this.tableDatas, 'patientRegisterId', patientRegisterId)
              if (lfind > -1) {
                this.tableDatas[lfind].isReceiveReport = body.isReceiveReport
                this.tableDatas[lfind].reportReceiveDate = reportReceiveDate
              }
            });
          }
        })
    },


    // 右击    
    rowContextmenu(row, column) {
      this.selectedRow = deepCopy(row)
    },

    onContextmenu(event) {
      // items.push({
      //   label: "一级菜单",
      //   children: [
      //     { label: "修改姓名", onClick: () => { this.fnUpBaseInfo(row, 'patientName'); } }
      //   ]
      // })      
      let items = []

      //取消领取报告
      items.push({
        label: '取消领取报告',
        onClick: () => {
          this.canselGetReport();
        }
      })

      // 右击菜单显示
      this.$contextmenu({
        items,
        event,
        x: event.clientX,
        y: event.clientY,
        customClass: "custom-class",
        zIndex: 3,
        minWidth: 80,
      });


      return false;
    },


    //滚动加载数据 
    async scrollFull(scroll, event) {
      if (!scroll.judgeFlse) return;

      // 正在加载时阻止重复触发
      if (this.lazyLoading) return;
      if (
        (Number(this.loadOpts.skipCount) + 1) *
        Number(this.loadOpts.maxResultCount) >=
        Number(this.loadOpts.totalCount)
      ) {
        return;
      }

      this.lazyLoading = true;
      try {
        await this.load();
      } catch (e) {
        console.error('scrollFull load error', e);
      }
      // this.dom = this.$refs['info'].bodyWrapper
      // console.log('this.dom', this.dom)

      // this.dom.addEventListener('scroll', async () => {
      //   // console.log('scrollTop',this.dom.scrollTop,'clientHeight',this.dom.clientHeight,'scrollHeight',this.dom.scrollHeight);
      //   if (this.dom.scrollTop + this.dom.clientHeight + 20 > this.dom.scrollHeight && !this.lazyLoading) {
      //     // 获取到的不是全部数据 当滚动到底部 
      //     console.log('scrollTop', this.dom.scrollTop, 'clientHeight', this.dom.clientHeight, 'scrollHeight', this.dom.scrollHeight);
      //     if (Number(this.loadOpts.skipCount) * Number(this.loadOpts.maxResultCount) >= Number(this.loadOpts.totalCount)) {
      //       this.lazyLoading = false
      //     } else {
      //       this.lazyLoading = true
      //       await this.load()
      //       this.lazyLoading = false
      //       // this.dom.scrollTop = this.dom.scrollTop - 100
      //     }
      //   }
      // })
    },

    //监听拖拽
    initColDrag() {
      // 1. 获取表格的表头元素
      const table = document.querySelector('.el-table__header-wrapper tr');

      // 2. 创建 Sortable 实例
      Sortable.create(table, {
        animation: 150, // 拖拽动画时长

        // 开始拖拽的时候
        onStart: (event) => {
          if (event.oldIndex == 0) {
            this.$alert('第1列不可以拖动', '提示')
          }
          //evt.oldIndex;  // element index within parent
        },
        // 3. 监听拖拽结束事件
        onEnd: (event) => {
          const { oldIndex, newIndex } = event;

          // 4. 更新列定义数组的顺序
          let movedColumn = this.dragCol.splice(oldIndex, 1)[0];
          this.dragCol.splice(newIndex, 0, movedColumn);
          //this.selectionCol = arrayExistObj(this.dragCol,'type','selection')

          // 5. 强制表格重新渲染以更新视图
          //this.tableBrush += 1;                
        }
      });
    },

    lmoment(date, forMat) {
      return moment(new Date(date)).format(forMat);
    },

    //查询
    btnQuery() {
      this.loadOpts.skipCount = 0
      this.reportQuery()
    },

    // 显示数据转换
    prListTrans(items) {
      let arr = []
      if (Array.isArray(items) && items.length > 0) {
        arr = items
        arr.forEach(e => {
          e.groupPack = e.medicalPackageName || e.customerOrgGroupName
          e.org = e.customerOrgName || e.departmentName
          e.dept = e.customerOrgName == e.departmentName ? '' : e.departmentName
        });
      }
      return arr
    },

    // 报告查询
    reportQuery() {
      console.log('reportQuery this.loadOpts', this.loadOpts)
      if (this.loadOpts.skipCount != 0 && this.loadOpts.skipCount * this.loadOpts.maxResultCount >= this.loadOpts.totalCount) return

      let body = {
        skipCount: this.loadOpts.skipCount,
        maxResultCount: this.loadOpts.maxResultCount
      };

      let queryType = this.query.queryType
      if (!queryType) {
        // 排他条件有值时
        if (this.query.patientRegisterNo) {
          queryType = "patientRegisterNo"
        } else if (this.query.patientNo) {
          queryType = "patientNo"
        } else if (this.query.idCardNo) {
          queryType = "idCardNo"
        } else if (this.query.patientName) {
          queryType = "patientName"
        }
      }

      // 优选精准查找
      switch (queryType) {
        case "patientRegisterNo":
          // 条码号排他
          body = {
            patientRegisterNo: this.query.patientRegisterNo,
            skipCount: this.loadOpts.skipCount,
            maxResultCount: this.loadOpts.maxResultCount
          }
          break;
        case "patientNo":
          // 条码号排他
          body = {
            patientNo: this.query.patientNo,
            skipCount: this.loadOpts.skipCount,
            maxResultCount: this.loadOpts.maxResultCount
          }
          break;
        case "idCardNo":
          // 判断身份证是否排他
          body.idNo = this.query.idCardNo
          if (this.patient_register_query_idno == 'Y') {
            body = {
              idNo: this.query.idCardNo,
              skipCount: this.loadOpts.skipCount,
              maxResultCount: this.loadOpts.maxResultCount
            }
          } else {
            queryType = ''
          }
          break;
        case "patientName":
          // 判断姓名是否排他
          body.patientName = this.query.patientName
          if (this.patient_register_query_name == 'Y') {
            body = {
              patientName: this.query.patientName,
              skipCount: this.loadOpts.skipCount,
              maxResultCount: this.loadOpts.maxResultCount
            }
          } else {
            queryType = ''
          }
          break;
        default:
          queryType = ''
          break;
      }

      // 非排他时查询
      if (!queryType) {
        let customerOrgs = [];
        if (this.query.ocxDatas.length > 0) {

          this.query.ocxDatas.forEach(e => {
            let dateType = '1'
            switch (e.dateType) {
              case 'medicalStartDate':
                dateType = '2'
                break;
              case 'checkDate':
                dateType = '4'
                break;
              case 'summaryDate':
                dateType = '3'
                break;
              case 'sumCheckDate':
                dateType = '5'
                break;
              default:
                break;
            }
            let rd = {
              startDate: moment(e.startDate).format('yyyy-MM-DD'),
              endDate: moment(e.endDate).format('yyyy-MM-DD'),
              dateType
            }

            if (e.customerOrgId) {
              rd.customerOrgId = e.customerOrgId
              if (e.customerOrgId == this.dict.personOrgId) {
                rd.customerOrgRegisterId = null
                rd.customerOrgGroupId = []
              } else {
                rd.customerOrgRegisterId = e.customerOrgRegister.id
                rd.customerOrgGroupId = e.customerOrgGroupIds
              }
            }
            customerOrgs.push(rd)
          })
        }
        body.customerOrgs = customerOrgs
        if (this.query.phone) body.phone = this.query.phone
        if (this.query.completeFlag) body.completeFlag = this.query.completeFlag
        if (this.query.isAudit) body.isAudit = this.query.isAudit
        if (this.query.isReportPrint) body.isReportPrint = this.query.isReportPrint
        if (this.query.isUpload) body.isUpload = this.query.isUpload
        if (this.query.medicalTypeIds && this.query.medicalTypeIds.length > 0) body.medicalTypeIds = this.query.medicalTypeIds
        if (this.query.personnelTypeId) body.personnelTypeId = this.query.personnelTypeId
        if (this.query.medicalConclusionId && this.query.medicalConclusionId.length > 0) body.medicalConclusionIds = this.query.medicalConclusionId
      }

      //console.log('/api/app/peisreport/getpatientregisterreport',body)
      // 带收费信息 /api/app/PeisReport/GetPatientRegisterReportWithCharge
      // 不带收费信息 /api/app/patientregister/getlistinfilter
      postapi('/api/app/peisreport/getpatientregisterreport', body).then(res => {
        if (res.code > -1) {
          this.lazyLoading = false
          // 连续扫码
          // console.log('this.query',this.query)
          if (this.query.isSeries == 'Y' && this.query.patientRegisterNo) {

            if (res.data.items.length > 0 && arrayExistObj(this.tableDatas, 'patientRegisterId', res.data.items[0].patientRegisterId) == -1) {
              this.tableDatas = this.tableDatas.concat(this.prListTrans(res.data.items))
            }

            if (this.tableDatas.length > 0 && res.data.items.length > 0) {
              let lfind = arrayExistObj(this.tableDatas, 'patientRegisterId', res.data.items[0].patientRegisterId)
              if (lfind > -1) {
                // this.$refs['info'].setCurrentRow();
                this.$nextTick(() => {
                  setTimeout(() => {
                    this.$refs['info'].setCurrentRow(this.tableDatas[lfind]);
                  }, 20)
                })
                this.rowClick(this.tableDatas[lfind])
              }
            }

            // 连续扫码，自动选中新扫的码 (换成虚拟表后，无法自动勾选了)
            // this.$nextTick(function () {
            //   this.tableDatas.forEach(row => {               
            //     this.$refs['info'].toggleRowSelection(row)
            //   })
            // });

          } else {
            // 刷新最大记录数
            this.loadOpts.totalCount = res.data.totalCount

            if (body.skipCount == 0) {  //查询
              this.tableDatas = [];
            }
            this.tableDatas = this.tableDatas.concat(this.prListTrans(res.data.items))

            if (body.skipCount == 0 && this.tableDatas.length > 0) {
              this.rowClick(this.tableDatas[0])
              this.$refs['info'].setCurrentRow();
              this.$refs['info'].setCurrentRow(this.tableDatas[0]);
            } else {
              this.$refs['info'].setCurrentRow();

              this.selectedRow = { id: '' }

              // 刷新总检状态(检查项目)
              this.refParams.brushSummary++

            }
          }
        }
      })
    },

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

      if (
        !(
          this.checkedRows &&
          this.checkedRows.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.checkedRows.length;
        i++
      ) {
        let e = this.checkedRows[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.checkedRows.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.selectedRow.id) return;
      this.dialogVisibleCheckHistory = true;
      this.refParams = Object.assign({}, this.refParams, { brushTimes: Number(this.refParams.brushTimes) + 1, patientRegisterId: this.selectedRow.id })

    },

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

      if (
        !(
          this.checkedRows &&
          this.checkedRows.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.checkedRows.length;
        i++
      ) {
        let e = this.checkedRows[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.checkedRows.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.selectedRow.id) {
        this.$message.warning({ showClose: true, message: "请先选择记录！" });
        return;
      }
      let url = '/api/app/ImportLisResult/ImportResultByPatientRegisterId'
      let patientRegisterId = this.selectedRow.id
      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;
        case 'diAn':
          url = "/api/app/ImportLisResult/ImportDianResultByPatientRegisterId";
          postapi(url, { patientRegisterId }).then(res => {
            if (res.code > -1) {
              this.$message.success({ showClose: true, message: '导入成功！' })
            }
          })
          break;
        default: //lis
          postapi(url, { patientRegisterId }).then(res => {
            if (res.code > -1) {
              this.$message.success({ showClose: true, message: '导入成功！' })
            }
          })
          break;
      }
    },

    // 导入结果
    btnExportComm(checkType) {
      switch (checkType) {
        case 'zip':
          this.exportZip()
          break;
        case 'jpg':
          this.exportJpg()
          break;
        case 'pdf':
          this.btnReportExport(false)
          break;
        default: //lis
          this.btnExport()
          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.tableDatas,
              "patientRegisterId",
              patientRegisterId
            );
            if (lfind > -1) {
              this.tableDatas[lfind].isReceiveReport =
                this.receiveReport.isReceiveReport;
              this.tableDatas[lfind].reportReceiveName =
                this.receiveReport.reportReceiveName;
              this.tableDatas[lfind].reportReceiveDate =
                reportReceiveDate;
            }
          });
          this.dialogGetReport = false;
        }
      });
    },

    //领取体检报告(按钮)
    btnGetReport(isReceiveReport) {
      //console.log('this.selectedRow.id',this.selectedRow.id,this.checkedRows)
      let rd = [];
      if (
        this.checkedRows &&
        this.checkedRows.length > 0
      ) {
        rd = rd.concat(this.checkedRows);
      }
      if (rd.length == 0) {
        if (this.selectedRow.id)
          rd.push({
            patientRegisterId: this.selectedRow.id,
          });
      }
      if (rd.length == 0) {
        this.$message.warning({
          showClose: true,
          message: "请先勾选或选择记录（有勾选人员时，仅操作勾选的记录）！",
        });
        return;
      }
      let lfind = arrayExistObj(
        this.tableDatas,
        "patientRegisterId",
        rd[0].patientRegisterId
      );
      if (lfind > -1) {
        this.receiveReport.reportReceiveName =
          this.tableDatas[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.checkedRows &&
        this.checkedRows.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.checkedRows.length;
          i++
        ) {
          let e = this.checkedRows[i];
          this.elProgress.percentage = Math.floor(
            ((i + 1) * 100) / this.checkedRows.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,
        TemplateCode: undefined, // 新加打印模版
        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" }, // 总检审核签名（部份企业固定才用）
        ],
      };


      let JSONtoOutShell = ''
      if (isPreview) {
        toOutShell.ReportCode =
          rds[0].isPatientOccupationalDisease == "Y" ? "0006" : "0005";

        toOutShell.BusinessCode = rds[0].patientRegisterId;

        // 选择报告打印模版
        if (toOutShell.ReportCode == "0005" && rds[0].reportFormatTemplateId) toOutShell.TemplateCode = rds[0].reportFormatTemplateId


        // 审核了才可以打印
        if (this.medical_report_print_after_summary_check_is_audit == 'Y') {
          //if (rd.completeFlag != "3") toOutShell.preViewCanPrint = "N";
          if (rds[0].isAudit == "N") toOutShell.preViewCanPrint = "N";
        }

        JSONtoOutShell = JSON.stringify(toOutShell);
        console.log("$peisAPI.printPre", toOutShell, JSONtoOutShell);
        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 (toOutShell.ReportCode == "0005" && rd.reportFormatTemplateId) toOutShell.TemplateCode = rd.reportFormatTemplateId


          // 审核了才可以打印
          if (this.medical_report_print_after_summary_check_is_audit == 'Y') {
            //if (rd.completeFlag != "3") toOutShell.preViewCanPrint = "N";
            if (rd.isAudit == "N") toOutShell.preViewCanPrint = "N";
          }

          if (toOutShell.preViewCanPrint == "N") {
            this.$message.warning({
              showClose: true,
              message: "未总检或未审核，不可打印报告",
            });
            continue;
          }

          try {
            JSONtoOutShell = JSON.stringify(toOutShell);
            // 防止打印太多数据 只输出 第一条
            if (i == 0) console.log('this.$peisAPI.print', toOutShell, JSONtoOutShell)

            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.tableDatas,
                    "patientRegisterId",
                    rd.patientRegisterId
                  );
                  if (lfind > -1)
                    this.tableDatas[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.checkedRows &&
          this.checkedRows.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.checkedRows.length < 1) return;
      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      let ReportCode = "0005";
      if (
        this.checkedRows[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.checkedRows[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.checkedRows.length;
        i++
      ) {
        let e = this.checkedRows[i];
        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.checkedRows.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.selectedRow = deepCopy(res.data);
        }
      });
    },

    // 通用判断 是否有选中或勾选记录（同时有选中与勾选记录时，以勾选记录为主）
    getChoosedRds() {
      let rd = [];
      if (
        this.checkedRows &&
        this.checkedRows.length > 0
      ) {
        rd = rd.concat(this.checkedRows);
      }
      if (rd.length == 0) {
        if (this.selectedRow.id) {
          let lfind = arrayExistObj(
            this.tableDatas,
            "patientRegisterId",
            this.selectedRow.id
          );
          if (lfind > -1)
            rd.push(
              this.tableDatas.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.tableDatas.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 (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"  是下载后的表名 可修改
      });

    },
  },

  //监听事件
  watch: {
    //触发查询事件
    // "query.times": {
    //   // immediate:true,
    //   handler(newVal, oldVal) {
    //     console.log('watch:query.times', newVal, oldVal)
    //     if (newVal != oldVal) {
    //       this.btnQuery();
    //     }
    //   }
    // },
  },
};
</script>
<style scoped>
@import '../../assets/css/global_card.css';
@import '../../assets/css/global_input.css';
@import '../../assets/css/global_table.css';
@import '../../assets/css/global.css';

.query {
  margin-left: 10px;
  font-size: 14px;
  color: #232748;
  font-weight: 400;
  font-family: "NotoSansSC-Regular";
}

.spanClass {
  padding: 0 2px 0 0;
}

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

.btnClass {
  width: 100px;
}
</style>
