<template>
  <div>
    <!--组件主体-->
    <div>
      <div
        :style="'width:' + (window.pageWidth - 10) + 'px;'"
        @contextmenu.prevent="onContextmenu"
      >
        <div>
          <el-table
            :data="tableData"
            border
            :height="
              window.pageHeight < 600
                ? 200
                : Math.floor(((window.pageHeight - 370) * 2) / 3)
            "
            highlight-current-row
            @row-click="rowClick"
            size="small"
            row-key="id"
            :row-class-name="handleRowClassName"
            id="phoneFollowUp"
          >
            <el-table-column prop="patientName" label="姓名" width="90" align="center" />
            <el-table-column prop="idNo" label="身份证" width="150" align="center" />
            <el-table-column prop="patientRegisterNo" label="人员条码号" width="90" align="center" />
            <el-table-column prop="medicalTimes" label="体检次数" width="90" align="center" />
            <el-table-column prop="sexName" label="性别" width="50" align="center" />
            <el-table-column prop="birthDate" label="出生日期" width="90" align="center" />
            <el-table-column prop="age" label="年龄" width="50" align="center" />
            <el-table-column prop="abnormalAsbitemDetail" label="组合项目异常" width="200">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.abnormalAsbitemDetail" :key="index">
                  {{item.asbitemName+' '+item.isCriticalValue+' '+item.isReview}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="abnormalItemDetail" label="项目异常" width="200">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.abnormalItemDetail" :key="index">
                  {{item.itemName+' '+item.isCriticalValue+' '+item.isReview}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="isSmsComplete" label="短信随访创建完成" width="200">
              <!-- <template slot-scope="scope">
                <el-checkbox v-model="scope.row.isSmsComplete" disabled true-label="Y" false-label="N"></el-checkbox>
              </template> -->
            </el-table-column>
            <el-table-column prop="isPhoneComplete" label="电话随访创建完成" width="200">
              <!-- <template slot-scope="scope">
                 <el-checkbox v-model="scope.row.isPhoneComplete" disabled true-label="Y" false-label="N"></el-checkbox>
              </template> -->
            </el-table-column>
            <el-table-column prop="jobCardNo" label="工卡号" width="90" align="center" />
            <el-table-column prop="medicalCardNo" label="体检卡号" width="90" align="center" />
            <el-table-column prop="maritalStatusName" label="婚姻状况" width="90" align="center" />
            <el-table-column prop="medicalTypeName" label="体检类别" align="center" />
            <el-table-column prop="personnelTypeName" label="人员类型" width="90" align="center" />
            <el-table-column prop="jobPost" label="职务" width="90" align="center" />
            <el-table-column prop="jobTitle" label="职称" width="90" align="center" />
            <el-table-column prop="isUpload" label="上传WEB" width="90" align="center">
              <!-- <template slot-scope="scope">
                 <el-checkbox v-model="scope.row.isUpload" disabled true-label="Y" false-label="N"></el-checkbox>
              </template> -->
            </el-table-column>
            <el-table-column prop="completeFlag" label="状态" width="90" align="center">
              <template slot-scope="scope">
                <div>{{ dddw(dict.completeFlag, "id", scope.row.completeFlag, "displayName") }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="isMedicalStart" label="开始标志" width="90" align="center">
              <!-- <template slot-scope="scope">
                <el-checkbox v-model="scope.row.isMedicalStart" disabled true-label="Y" false-label="N"></el-checkbox>
              </template> -->
            </el-table-column>
            <el-table-column prop="medicalStartDate" label="开始日期" width="90" align="center" />
            <el-table-column prop="patientNo" label="档案号" width="90" align="center" />
            <el-table-column prop="telephone" label="电话" width="90" align="center" />
            <el-table-column prop="mobileTelephone" label="手机号" />
            <el-table-column prop="customerOrgName" label="单位" />
            <el-table-column prop="customerOrgParentName" label="父级单位" />
          </el-table>
          <div style="display: flex; justify-content: space-between">
            <div></div>
          </div>
        </div>
        <!-- 组合项目  基本信息  -->
        <el-tabs v-model="tabChoosed">
          <el-tab-pane label="危急值" name="1">
            <AsbitemCriticalValue />
          </el-tab-pane>
          <el-tab-pane label="电话随访" name="2">
            <PhoneFollowUp />
          </el-tab-pane>
          <el-tab-pane label="短信随访" name="3">
            <SmsSend />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--组件弹窗-->
    <div></div>
  </div>
</template>
<script>
import moment from "moment";
import { mapState, mapActions } from "vuex";
import { getapi, postapi, putapi, deletapi } from "@/api/api";
import Sortable from "sortablejs";
import FileSaver from "file-saver";
import html2canvas from "html2canvas";
import { exportToExcel } from "../../utlis/Export2Excel";

import {
  getPagePriv,
  checkPagePriv,
  dddw,
  objCopy,
  arrayReduce,
  arrayExistObj,
  deepCopy,
  setPrStatusColor,
} from "../../utlis/proFunc";

import FollowCritical from "./FollowCritical.vue";
import PhoneFollowUp from "./PhoneFollowUp.vue";
import SmsSend from "./SmsSend.vue";
import AsbitemCriticalValue from "./AsbitemCriticalValue.vue";

export default {
  components: {
    FollowCritical,
    PhoneFollowUp,
    SmsSend,
    AsbitemCriticalValue
  },
  data() {
    return {
      pagePriv: {
        routeUrlorPageName: "patientRegister", //当前页面归属路由或归属页面权限名称
        privs: [], // 页面权限
      },
      peisid: null,
      startPoint: -1, // 多选起点 -1 表示选择
      endPoint: -1, // 多选终点 -1 表示未选择

      tableData: [], //表格数据
      tableDataCurrentRow: {}, // 当前被选中的行

      multipleSelection: [], //选中的数据列表

      dialogCamera: false,
      tabChoosed: "1",
      formInitData: {}, //体检登记初始表单数据
      editTimes: 0,

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

      dragColDesign: [], // 待调整的排序的序
      //拖动列
      dragCol: [
        { label: "序号", prop: "sn", minWidth: 40, align: "center" },
        { label: "锁住", prop: "isLock", minWidth: 55, align: "center" },
        {
          label: "单位",
          prop: "customerOrgParentName",
          minWidth: 180,
          align: "center",
        },
        {
          label: "部门",
          prop: "customerOrgName",
          minWidth: 120,
          align: "center",
        },
        { label: "姓名", prop: "patientName", minWidth: 80, align: "center" },
        { label: "性别", prop: "sexId", minWidth: 55, align: "center" },
        { label: "年龄", prop: "age", minWidth: 55, align: "center" },
        {
          label: "条码号",
          prop: "patientRegisterNo",
          minWidth: 150,
          align: "center",
        },
        { label: "档案号", prop: "patientNo", minWidth: 100, align: "center" },
        {
          label: "体检次数",
          prop: "medicalTimes",
          minWidth: 80,
          align: "center",
        },
        {
          label: "分组/套餐",
          prop: "groupPack",
          minWidth: 150,
          align: "center",
        },
        { label: "民族", prop: "nationId", minWidth: 55, align: "center" },
        { label: "身份证", prop: "idNo", minWidth: 160, align: "center" },
        { label: "出生日期", prop: "birthDate", minWidth: 80, align: "center" },
        { label: "邮箱", prop: "email", minWidth: 150, align: "center" },
        {
          label: "手机",
          prop: "mobileTelephone",
          minWidth: 130,
          align: "center",
        },
        { label: "电话", prop: "telephone", minWidth: 130, align: "center" },
        { label: "地址", prop: "address", minWidth: 400, align: "" },
        {
          label: "体检卡号",
          prop: "medicalCardNo",
          minWidth: 80,
          align: "center",
        },
        { label: "工卡号", prop: "jobCardNo", minWidth: 80, align: "center" },
        {
          label: "婚姻状况",
          prop: "maritalStatusId",
          minWidth: 80,
          align: "center",
        },
        {
          label: "体检类别",
          prop: "medicalTypeId",
          minWidth: 80,
          align: "center",
        },
        {
          label: "人员类别",
          prop: "personnelTypeId",
          minWidth: 80,
          align: "center",
        },
        { label: "职务", prop: "jobPost", minWidth: 200, align: "center" },
        { label: "职称", prop: "jobTitle", minWidth: 80, align: "center" },
        { label: "介绍人", prop: "salesman", minWidth: 80, align: "center" },
        { label: "是否VIP", prop: "isVip", minWidth: 80, align: "center" },
        {
          label: "体检进度",
          prop: "completeFlag",
          minWidth: 80,
          align: "center",
        },
        {
          label: "打印",
          prop: "guidePrintTimes",
          minWidth: 55,
          align: "center",
        },
        { label: "登记人", prop: "creatorName", minWidth: 80, align: "center" },
        {
          label: "登记日期",
          prop: "creationTime",
          minWidth: 140,
          align: "center",
        },
        {
          label: "体检日期",
          prop: "medicalStartDate",
          minWidth: 140,
          align: "center",
        },
        { label: "是否上传", prop: "isUpload", minWidth: 80, align: "center" },
        { label: "高原/健康", prop: "qztlType", minWidth: 90, align: "center" },
        { label: "行车", prop: "qztlIsMain", minWidth: 50, align: "center" },
        { label: "从业", prop: "qztlIsCy", minWidth: 50, align: "center" },
        { label: "普速", prop: "qztlIsCw", minWidth: 50, align: "center" },
        { label: "高铁", prop: "qztlIsGt", minWidth: 50, align: "center" },
        { label: "职害", prop: "qztlIsWh", minWidth: 50, align: "center" },
        { label: "复检", prop: "qztlIsFj", minWidth: 50, align: "center" },
      ],
      dialogColSort: false,

      dom: null, //用于滚动加载数据
      lazyLoading: false, //是否懒加载中
      loadOpts: {
        totalCount: 0,
        skipCount: 0,
        maxResultCount: 100,
      },
      loadOptsInit: {},

      upBaseInfo: {
        visble: false,
        label: "姓名",
        value: "",
        colName: "patientName",
        patientRegisterId: "",
      },

      queueParams: {}, // 分诊排队参数
      LocalConfig: {
        normal: {
          maxResultCount: 100, //分页时单页记录数
        },
      },
      LocalConfigInit: {},
    };
  },

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

    this.LocalConfigInit = deepCopy(this.LocalConfig);
    let LocalConfig = window.localStorage.getItem("LocalConfig") || null;
    // console.log('LocalConfig',LocalConfig)
    try {
      this.LocalConfig = Object.assign(
        {},
        deepCopy(this.LocalConfigInit),
        JSON.parse(LocalConfig) || {}
      );
    } catch (error) {
      console.log('window.localStorage.getItem("LocalConfig")', error);
    }
    // console.log('this.LocalConfig',this.LocalConfig)
    this.loadOpts.maxResultCount = Number(
      this.LocalConfig.normal.maxResultCount || 100
    );

    this.loadOptsInit = Object.assign({}, this.loadOpts);
  },

  //挂载完成
  mounted() {
    this.quickAsb = this.dict.asbItemAll;

    this.peisid = window.sessionStorage.getItem("peisid");

    // this.$nextTick(() => {
    //   this.scrollFull();
    // });
  },
  computed: {
    ...mapState([
      "window",
      "dataTransOpts",
      "dialogWin",
      "dict",
      "elProgress",
      "patientRegister",
      "customerOrg",
      "report",
    ]),
  },
  methods: {
    ...mapActions(["getCustomerOrgGroup", "getPatientRegisterAbs"]),
    moment,
    dddw,
    deepCopy,
    checkPagePriv,
    setPrStatusColor,

    // 扩展定义表格行样式
    handleRowClassName({ row, rowIndex }) {
      // highLightBg 为 'selected'的高亮
      //// console.log(rowIndex, row)
      //return row.highLightBg == 'selected' ? 'high-light-bg' : '';
      if (row.choosed) {
        return "current-row";
      } else {
        return "";
      }
    },

    // 行选择
    rowSelected(rows) {
      rows.forEach((e) => {
        this.$refs["info"].toggleRowSelection(e, true);
      });
    },

    refFuncSetData(item, v) {
      setData(this, item, v);
    },

    // 打印指引单(isPreview)
    async guidePrint(ReportCode, isPreview) {
      if (!this.$peisAPI) {
        this.$message.info({
          showClose: true,
          message: "此功能，需要在壳客户端才可运行！",
        });
        return;
      }
      let token = window.sessionStorage.getItem("token");
      let user = window.sessionStorage.getItem("user");
      let toOutShell = {
        ReportCode,
        token,
        isBuildImage: "N",
        IsUploadPdf: "N",
        preViewCanPrint: "N",
        Parameters: [
          { Name: "printer", Value: user },
          { Name: "hisLog", Value: "pic/hisLog.jpg" },
          { Name: "pageFooter", Value: "pic/peisQrCode.jpg" },
        ],
      };
      let lfind = -1;

      //选中（取消勾选）start -------------------------
      // this.multipleSelection = []
      // this.tableData.forEach(e => {
      //   if (e.choosed) {
      //     this.multipleSelection.push(deepCopy(e))
      //   }
      // })
      //选中（取消勾选） end  -------------------------

      if (this.multipleSelection.length < 1) {
        this.$message.info({
          showClose: true,
          message: "请勾选要打印指引单的人员记录！",
        });
        return;
      }

      if (isPreview) {
        /*
        //this.multipleSelection.forEach((item,index) =>{
        postapi(
          `/api/app/printreport/getpatientregisterguidereport?PatientRegisterId=${this.multipleSelection[0].id}`
        )
          .then((res) => {
            if (res.code != -1) {
              toOutShell.ReportTable = res.data;
              // console.log(
                "JSON.stringify(toOutShell)",
                JSON.stringify(toOutShell)
              );
              return this.$peisAPI.printPre(JSON.stringify(toOutShell));
            }
          })
          .then(res => {
            // console.log('this.$peisAPI.printPre', res)
            if (JSON.parse(res).code < 0) {
              this.$message.warning(JSON.parse(res).message);
            }
          })
          .catch((err) => {
            // console.log('打印指引单', err)
            this.$message.warning({ showClose: true, message: err });
          });
        */
        toOutShell.BusinessCode = this.multipleSelection[0].id;
        if (this.multipleSelection[0].completeFlag == "0") {
          this.$message.warning({
            showClose: true,
            message: "预登记人员，不可执行此操作！",
          });
          return;
        }

        this.$peisAPI
          .printPre(JSON.stringify(toOutShell))
          .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 {
        this.elProgress.display = true;
        this.elProgress.percentage = 0;

        for (let i = 0; i < this.multipleSelection.length; i++) {
          try {
            let patientregisterId = this.multipleSelection[i].id;
            if (this.multipleSelection[i].completeFlag == "0") {
              this.$message.warning({
                showClose: true,
                message: `${this.multipleSelection[i].patientName} 为预登记人员，不可打印指引单`,
              });
              continue;
            }
            toOutShell.BusinessCode = patientregisterId;
            let resPeisAPI = await this.$peisAPI.print(
              JSON.stringify(toOutShell)
            );
            if (JSON.parse(resPeisAPI).code < 0) continue;
            let resPrintTimes = await postapi(
              "/api/app/patientregister/updatepatientregisterguideprinttimesmany",
              [patientregisterId]
            );
            if (resPrintTimes.code == -1) continue;
            lfind = arrayExistObj(this.tableData, "id", patientregisterId);
            if (lfind > -1) {
              if (this.tableData[lfind].guidePrintTimes) {
                this.tableData[lfind].guidePrintTimes =
                  Number(this.tableData[lfind].guidePrintTimes) + 1;
              } else {
                this.tableData[lfind].guidePrintTimes = 1;
              }
            }
          } catch (error) {
            // console.log('打印指引单', error)
            this.$message.warning({ showClose: true, message: `${error}` });
          }

          this.elProgress.percentage = Math.floor(
            ((i + 1) * 100) / this.multipleSelection.length
          );
        }
        this.elProgress.display = false;
      }
    },

    // 指引单新打印方式，promise
    guidePrintPromise(ReportCode, isPreview, row) {
      return new Promise((resolve, reject) => {
        if (!this.$peisAPI) reject("此功能，需要在壳客户端才可运行！");

        let token = window.sessionStorage.getItem("token");
        let user = window.sessionStorage.getItem("user");
        let toOutShell = {
          ReportCode,
          token,
          isBuildImage: "N",
          IsUploadPdf: "N",
          preViewCanPrint: "N",
          Parameters: [
            { Name: "printer", Value: user },
            { Name: "hisLog", Value: "pic/hisLog.jpg" },
            { Name: "pageFooter", Value: "pic/peisQrCode.jpg" },
          ],
        };

        if (!row.completeFlag || row.completeFlag == "0")
          reject("预登记人员，不可执行此操作！");
        toOutShell.BusinessCode = row.id;
        console.log(JSON.stringify(toOutShell));
        if (isPreview) {
          this.$peisAPI
            .printPre(JSON.stringify(toOutShell))
            .then((res) => {
              let lres = JSON.parse(res);
              if (lres.code > -1) {
                resolve(lres);
              } else {
                reject(lres.message);
              }
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          this.$peisAPI
            .print(JSON.stringify(toOutShell))
            .then((res) => {
              let lres = JSON.parse(res);
              if (lres.code > -1) {
                return postapi(
                  "/api/app/patientregister/updatepatientregisterguideprinttimesmany",
                  [row.id]
                );
              } else {
                reject(lres.message);
              }
            })
            .then((res) => {
              if (res && res.code > -1) {
                let lfind = arrayExistObj(this.tableData, "id", row.id);
                if (lfind > -1) {
                  if (this.tableData[lfind].guidePrintTimes) {
                    this.tableData[lfind].guidePrintTimes =
                      Number(this.tableData[lfind].guidePrintTimes) + 1;
                  } else {
                    this.tableData[lfind].guidePrintTimes = 1;
                  }
                }
              }
              resolve(res);
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },

    printGuideLisPacs(row) {
      return new Promise((resolve, reject) => {
        this.guidePrintPromise("0008", false, row)
          .then((res) => {
            return this.lisPrint(row, "0002", false);
          })
          .then((res) => {
            return this.pacsPrint(row, "0004", false);
          })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    async printPromise() {
      if (this.multipleSelection.length < 1) {
        this.$message.info({
          showClose: true,
          message: "请勾选要打印人员检验检查条码的记录！",
        });
        return;
      }

      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      for (let i = 0; i < this.multipleSelection.length; i++) {
        let row = this.multipleSelection[i];
        try {
          await this.printGuideLisPacs(row);
        } catch (error) {
          console.log("printPromise", error);
        }

        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.multipleSelection.length
        );
      }
      this.elProgress.display = false;
    },

    handleSelectionChange(rows) {
      //this.multipleSelection = rows;
      //// console.log('this.multipleSelection',this.multipleSelection)
      // rows.forEach((item) => {
      //   item.highLightBg = "selected";
      // });
      // // 取消全选
      // if (!rows.length) {
      //   this.tableData.forEach((item) => {
      //     item.highLightBg = "";
      //   });
      // }
      this.multipleSelection = rows;
    },

    //设置新增/编辑的form数据
    setForm(formData) {
      this.patientRegister.patientRegisterRd = deepCopy(formData);
      if (!this.patientRegister.patientRegisterRd.id) {
        this.patientRegister.patientRegisterRd.customerOrgId =
          this.patientRegister.query.customerOrgId;
      }
    },

    //点击体检次数行
    rowClick(row) {
      // 按住了shift键
      // if (this.window.shift) {
      //   //清除所有选择
      //   this.tableData.forEach((e, index) => {
      //     e.choosed = false;
      //     e.index = index;
      //   });

      //   if (this.startPoint == -1) {
      //     this.tableData[row.index].choosed = true;
      //     this.startPoint = row.index;
      //   } else {
      //     if (this.startPoint > row.index) {
      //       for (let i = row.index; i <= this.startPoint; i++) {
      //         this.tableData[i].choosed = true;
      //       }
      //     } else if (this.startPoint <= row.index) {
      //       for (let i = this.startPoint; i <= row.index; i++) {
      //         this.tableData[i].choosed = true;
      //       }
      //     }
      //   }
      // } else if (this.window.ctrl) {  // 按住了ctrl 键
      //   this.tableData[row.index].choosed = true;
      //   if (this.startPoint == -1) {
      //     this.startPoint = row.index;
      //   }
      // } else {
      //   // 未按住了ctrl 、shift 键
      //   //清除所有选择
      //   // console.log("清除所有选择");
      //   this.tableData.forEach((e, index) => {
      //     e.choosed = false;
      //     e.index = index;
      //   });
      //   // console.log(this.tableData, row.index);
      //   // console.log(this.tableData[row.index].choosed);

      //   this.tableData[row.index].choosed = true;
      //   this.startPoint = row.index;
      // }

      //选中了多个点编辑时，排序最前的作为当前选中的
      // console.log('row.index <= this.startPoint', row.index, this.startPoint)
      // let lfind = -1
      // for (let i = 0; i < this.tableData.length; i++) {
      //   if (this.tableData[i].choosed) {
      //     lfind = i
      //     break
      //   }
      // }

      // if (lfind > -1) {
      // 弹出编辑框，只有在编辑框显示时，才去触发获取数据
      this.dataTransOpts.tableS.patient_register = deepCopy(row);
      this.tableDataCurrentRow = deepCopy(row);
      this.dataTransOpts.refresh.register_check_asbitem.M++; //触发所选组合项目刷新
      // }
    },

    //查询
    async Query() {
      // 查询时，清掉明细数据 （滚动时不清）
      this.dataTransOpts.tableS.patient_register.followUpId = "";
      this.tableDataCurrentRow = {}; // 清除选择
      this.tableData = [];

      // setTimeout(() => {
      //   this.dataTransOpts.refresh.register_check_asbitem.M++; //触发所选组合项目刷新
      // }, 10);

      this.loadOpts = Object.assign(this.loadOpts, this.loadOptsInit);
      await this.getPrList();
    },

    //数据量多时，滚动加载
    async load() {
      this.loadOpts.skipCount++;
      await this.getPrList();
    },

    // 获取列表数据
    async getPrList() {
      // console.log('getPrList', this.loadOpts)

      let body = {
          
        },
        customerOrgs = [];
      if (this.report.dataCusOrgOCX.length > 0) {
        if (this.report.dataCusOrgOCX.length > 1) {
          return this.$message({
          message: '只能选择一个单位',
          type: 'warning'
        });
        } else {
          this.report.dataCusOrgOCX.forEach((e) => {
            
            if (e.customerOrgId) {
              body.customerOrgId = e.customerOrgId;
              if (e.customerOrgId == this.dict.personOrgId) {
                body.customerOrgRegisterId = null;
                body.customerOrgGroupId = [];
              } else {
                body.customerOrgRegisterId = e.customerOrgRegister.id;
                body.customerOrgGroupId = e.customerOrgGroupIds;
              }
            }
              body.startDate=moment(e.startDate).format("yyyy-MM-DD"),
              body.endDate= moment(e.endDate).format("yyyy-MM-DD"),
              body.dateType=
                e.dateType == "summaryDate"
                  ? "3"
                  : e.dateType == "medicalStartDate"
                  ? "2"
                  : "1"
          });
        }
      }

      body.customerOrgs = customerOrgs;
      if (this.patientRegister.query.sex)
        body.sexId = this.patientRegister.query.sex;

      if (this.patientRegister.query.patientName)
        body.patientName = this.patientRegister.query.patientName;

      if (
        this.patientRegister.query.medicalTypeIds &&
        this.patientRegister.query.medicalTypeIds.length > 0
      )
        body.medicalTypeIds = this.patientRegister.query.medicalTypeIds;

      if (
        this.patientRegister.query.completeFlags &&
        this.patientRegister.query.completeFlags.length > 0
      )
        body.completeFlags = this.patientRegister.query.completeFlags;

      if (this.patientRegister.query.phone)
        body.phone = this.patientRegister.query.phone;

      if (this.patientRegister.query.isSmsComplete)
        body.isSmsComplete = this.patientRegister.query.isSmsComplete;

      if (this.patientRegister.query.isPhoneComplete)
        body.isPhoneComplete = this.patientRegister.query.isPhoneComplete;

      if (this.patientRegister.query.idCardNo)
        body = {
          idNo: this.patientRegister.query.idCardNo,
          skipCount: this.loadOpts.skipCount,
          maxResultCount: this.loadOpts.maxResultCount,
        };

      if (this.patientRegister.query.patientNo)
        body = {
          patientNo: this.patientRegister.query.patientNo,
          skipCount: this.loadOpts.skipCount,
          maxResultCount: this.loadOpts.maxResultCount,
        };

      if (this.patientRegister.query.patientRegisterNo)
        body = {
          patientRegisterNo: this.patientRegister.query.patientRegisterNo,
          skipCount: this.loadOpts.skipCount,
          maxResultCount: this.loadOpts.maxResultCount,
        };

      // console.log("/api/app/patientregister/getlistinfilter", body);

      postapi(
        "/api/app/PhoneFollowUp/GetPatientRegisterCriticalList",
        body
      ).then((res) => {
        if (res.code > -1) {
          let curLoad = res.data;
          // let oldCount = 0
          // 处理分组/套餐 排序混乱的问题
          // curLoad.forEach((e) => {
          //   if (e.customerOrgId == this.dict.personOrgId) {
          //     e.groupPack = e.medicalPackageId;
          //   } else {
          //     e.groupPack = e.customerOrgGroupId;
          //   }
          // });

          if (body.skipCount == 0) {
            //查询
            this.tableData = [];
          }

          this.tableData = this.tableData.concat(curLoad);
          // else {
          //   // 懒加载 ,原数据集不用清空
          //   oldCount = this.tableData.length
          // }
          // curLoad.forEach((e, index) => {
          //   this.tableData.push(Object.assign({ index: Number(oldCount) + Number(index), choosed: false }, e))
          // })

          //如果 有选中 记录，则刷新其对应的组合项目
          if (this.dataTransOpts.tableS.patient_register.id) {
            this.dataTransOpts.refresh.register_check_asbitem.M++;
          }
        }
      });
    },

    //滚动加载数据
    scrollFull() {
      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) + 1) *
              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
          }
        }
      });
    },

    btnUpBaseInfo() {
      let body = {
        patientRegisterId: this.upBaseInfo.patientRegisterId,
        // "patientName": "string",
        // "mobileTelephone": "string",
        // "idNo": "string"
      };
      body[this.upBaseInfo.colName] = this.upBaseInfo.value;

      postapi(
        "/api/app/PatientRegister/UpdatePatientRegisterBaseInfoByPatientRegisterId",
        body
      ).then((res) => {
        if (res.code > -1) {
          this.close_dialogWin_upBaseInfo();
        }
      });
    },
    // 修改基本信息
    fnUpBaseInfo(row, baseInfoType) {
      this.dataTransOpts.tableS.patient_register.id = row.id;
      this.upBaseInfo.visble = true;
      this.upBaseInfo.patientRegisterId = row.id;
      this.upBaseInfo.colName = baseInfoType;
      switch (baseInfoType) {
        case "idNo":
          this.upBaseInfo.label = "新身份证号";
          break;
        case "mobileTelephone":
          this.upBaseInfo.label = "新手机号";
          break;
        default:
          this.upBaseInfo.label = "新姓名";
          break;
      }
      this.upBaseInfo.value = row[baseInfoType];
    },

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

    //右击菜单
    onCellRightClick(row, column) {
      this.rClickRow = { ...row }; //右击的行记录
      this.rClickColumn = { ...column }; //右击的列（预留）
      // console.log(row, column.property);
    },
    onContextmenu(event) {
      //// console.log('onContextmenu',event);
      if (!this.rClickRow) return false;
      let row = { ...this.rClickRow };
      let items = []; //菜单项

      if (
        checkPagePriv(this.pagePriv.privs, "修改姓名") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "修改姓名",
          onClick: () => {
            this.fnUpBaseInfo(row, "patientName");
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "修改手机号") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "修改手机号",
          onClick: () => {
            this.fnUpBaseInfo(row, "mobileTelephone");
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "修改身份证号") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "修改身份证号",
          onClick: () => {
            this.fnUpBaseInfo(row, "idNo");
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "分诊排队") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "分诊排队",
          onClick: () => {
            this.fnQueue(row);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "发送检验申请") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "发送检验申请",
          onClick: () => {
            this.lisRequest(row);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "预览人员条码") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "预览人员条码",
          onClick: () => {
            this.guidePrintPromise("0008", true, row);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "预览检验条码") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "预览检验条码",
          onClick: () => {
            this.lisPrint(row, "0002", true);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "打印检验条码") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "打印检验条码",
          onClick: () => {
            this.lisPrint(row, "0002", false);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "预览Pacs条码") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "预览Pacs条码",
          onClick: () => {
            this.pacsPrint(row, "0004", true);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "打印Pacs条码") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "打印Pacs条码",
          onClick: () => {
            this.pacsPrint(row, "0004", false);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "导入检查结果") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "导入检查结果",
          onClick: () => {
            this.importResult("pacs", row);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "导入检验结果") &&
        row.completeFlag != "0"
      )
        items.push({
          label: "导入检验结果",
          onClick: () => {
            this.importResult("lis", row);
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "批量更新组合项目明细") &&
        this.multipleSelection.length > 0
      )
        items.push({
          label: "批量更新组合项目明细",
          onClick: () => {
            this.btnItemBatch();
          },
        });
      if (
        checkPagePriv(this.pagePriv.privs, "调整检查项目医生") &&
        this.multipleSelection.length > 0
      )
        items.push({
          label: "调整检查项目医生",
          onClick: () => {
            this.dataTransOpts.plus.PatientRegisterEditDoctorBatch++; //如果放在弹窗显示后面，在首次加载子组件时，会触发两次数据处理
            this.dialogWin.PatientRegisterEditDoctorBatch = true;
          },
        });
      items.push({ label: "----------------" });
      this.$contextmenu({
        items,
        event,
        //x: event.clientX,
        //y: event.clientY,
        customClass: "custom-class",
        zIndex: 3,
        minWidth: 80,
      });

      this.rClickRow = null;
      return false;
    },

    //批量更新分组按钮
    btnGroupBatch() {
      let customerOrgId = this.patientRegister.query.customerOrgId;
      if (!customerOrgId) {
        this.$message.warning({ showClose: true, message: "请选择单位" });
        return;
      }
      //取消勾选，换成选择的方式  start
      // this.multipleSelection = [];
      // this.tableData.forEach((e) => {
      //   if (e.choosed) this.multipleSelection.push(e);
      // });
      //取消勾选，换成选择的方式  end

      if (this.multipleSelection.length < 1) {
        this.$message.info({
          showClose: true,
          message: "请选择要操作的记录！",
        });
        return;
      }
      this.dataTransOpts.plus.PatientRegisterEditGroupBatch++;
      this.dialogWin.PatientRegisterEditGroupBatch = true;
    },

    //批量更新组合项目
    btnAsbBatch() {
      let customerOrgId = this.patientRegister.query.customerOrgId;
      if (!customerOrgId) {
        this.$message.warning({ showClose: true, message: "请选择单位" });
        return;
      }
      //取消勾选，换成选择的方式  start
      // this.multipleSelection = [];
      // this.tableData.forEach((e) => {
      //   if (e.choosed) this.multipleSelection.push(e);
      // });
      //取消勾选，换成选择的方式  end

      if (this.multipleSelection.length < 1) {
        this.$message.warning({
          showClose: true,
          message: "请选择要操作的记录",
        });
        return;
      }

      this.dataTransOpts.plus.PatientRegisterEditItemBatch++; //如果放在弹窗显示后面，在首次加载子组件时，会触发两次数据处理
      this.dialogWin.PatientRegisterEditItemBatch = true;
    },

    //批量更新组合项目
    async btnItemBatch() {
      if (this.multipleSelection.length < 1) {
        this.$message.warning({
          showClose: true,
          message: "请选择要操作的记录",
        });
        return;
      }

      this.elProgress.display = true;
      this.elProgress.percentage = 0;

      for (let i = 0; i < this.multipleSelection.length; i++) {
        let patientRegisterId = this.multipleSelection[i].id;
        try {
          await postapi("/api/app/RegisterCheckItem/SyncRegisterCheckItem", {
            patientRegisterId,
          });
        } catch (error) {
          console.log("printPromise", error);
        }

        this.elProgress.percentage = Math.floor(
          ((i + 1) * 100) / this.multipleSelection.length
        );
      }
      this.elProgress.display = false;
    },

    //检验申请
    async lisRequest(row) {
      let isPrintLisRequest = false;
      let res = null;
      if (row.completeFlag == "0") {
        this.$message.info({
          showClose: true,
          message: "预登记人员，不可执行此操作！",
        });
        return;
      }

      try {
        res = await postapi(
          `/api/app/lisrequest/setlisrequest?PatientRegisterId=${row.id}`
        );
        // console.log(`/ api / app / lisrequest / setlisrequest ? PatientRegisterId = ${ prId }`,res);
      } catch (error) {
        return;
      }
      if (res.code > -1) {
        isPrintLisRequest = true;
      }

      //重复申请，重打
      if (res.code == -1 && res.message.indexOf("已申请") > -1) {
        isPrintLisRequest = true;
      }

      if (!isPrintLisRequest) return;

      try {
        await this.$confirm("是否打印检验申请单?", "提示", {
          confirmButtonText: "是",
          cancelButtonText: "否",
          type: "info",
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false,
        });
      } catch (error) {
        return;
      }
      //打印检验申请单
      this.lisPrint(row, "0003", false);
    },

    //检验条码打印 改造成 promise
    lisPrint(row, ReportCode, isPreview) {
      return new Promise((resolve, reject) => {
        if (!this.$peisAPI) reject("此功能，需要在壳客户端才可运行！");
        if (!row.completeFlag || row.completeFlag == "0")
          reject("预登记人员，不可执行此操作！");

        let token = window.sessionStorage.getItem("token");
        let user = window.sessionStorage.getItem("user");
        let toOutShell = {
          ReportCode,
          token,
          IsMoreLabel: "Y",
          isBuildImage: "N",
          IsUploadPdf: "N",
          preViewCanPrint: "N",
          Parameters: [
            { Name: "printer", Value: user },
            { Name: "hisLog", Value: "pic/hisLog.jpg" },
          ],
          BusinessCode: row.id,
        };
        console.log("this.$peisAPI.toOutShell", toOutShell);
        if (isPreview) {
          this.$peisAPI
            .printPre(JSON.stringify(toOutShell))
            .then((res) => {
              console.log("this.$peisAPI.printPre", res);
              let lres = JSON.parse(res);
              if (lres.code > -1) {
                resolve(lres);
              } else {
                reject(lres.message);
              }
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          this.$peisAPI
            .print(JSON.stringify(toOutShell))
            .then((res) => {
              console.log("this.$peisAPI.print", res);
              let lres = JSON.parse(res);
              if (lres.code < 0) {
                reject(lres.message);
              } else {
                return postapi("/api/app/lisrequest/updatelisrequestisprint", {
                  operateType: 1,
                  patientRegisterId: row.id,
                });
              }
            })
            .then((res) => {
              if (res && res.code < 0) {
                reject(res.message);
              } else {
                resolve(res);
              }
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },

    //pacs条码打印
    pacsPrint(row, ReportCode, isPreview) {
      return new Promise((resolve, reject) => {
        if (!this.$peisAPI) reject("此功能，需要在壳客户端才可运行！");
        if (!row.completeFlag || row.completeFlag == "0")
          reject("预登记人员，不可执行此操作！");

        let token = window.sessionStorage.getItem("token");
        let user = window.sessionStorage.getItem("user");
        let toOutShell = {
          ReportCode,
          token,
          IsMoreLabel: "Y",
          isBuildImage: "N",
          IsUploadPdf: "N",
          preViewCanPrint: "N",
          Parameters: [
            { Name: "printer", Value: user },
            { Name: "hisLog", Value: "pic/hisLog.jpg" },
          ],
          BusinessCode: row.id,
        };
        console.log("this.$peisAPI.print", toOutShell);
        if (isPreview) {
          this.$peisAPI
            .printPre(JSON.stringify(toOutShell))
            .then((res) => {
              console.log("this.$peisAPI.printPre", res);
              let lres = JSON.parse(res);
              if (lres.code > -1) {
                resolve(lres);
              } else {
                reject(lres.message);
              }
            })
            .catch((err) => {
              reject(err);
            });
        } else {
          this.$peisAPI
            .print(JSON.stringify(toOutShell))
            .then((res) => {
              console.log("this.$peisAPI.print", res);
              let lres = JSON.parse(res);
              if (lres.code > -1) {
                resolve(lres);
              } else {
                reject(lres.message);
              }
            })
            .catch((err) => {
              reject(err);
            });
        }
      });
    },

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

    //通用导出
    btnExport(elId) {
      // 获取HTML元素（表格）
      // let table = document.getElementById(elId); //.cloneNode(true)
      this.$nextTick(() => {
        // let refsTable = this.$refs[elId]  //.cloneNode(true) true
        let table = document.getElementById(elId);
        // console.log('table,refsTable', table, refsTable)

        let tableData = table.innerHTML;
        let fileName = moment(new Date()).format("yyyyMMDDHHmmss");

        let blob = new Blob([tableData], { type: "text/plain;charset=utf-8" });

        FileSaver.saveAs(blob, fileName + ".xls");

        // 导出图片
        // 使用html2canvas将HTML元素转换为画布
        // let cloneTable = table.cloneNode(true) //[elId]
        /*
        html2canvas(table).then(canvas => {

          // 创建一个a元素用于下载
          const link = document.createElement('a');
          link.href = canvas.toDataURL('image/jpeg');
          link.download = fileName + '.jpg';
          document.body.appendChild(link);
          link.click();
          //document.body.removeChild(link);

          // // 创建一个PDF对象
          // var pdf = new jsPDF();    
          // // 设置PDF的尺寸
          // pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, canvas.width, canvas.height);    
          // // 导出PDF
          // pdf.save('员工信息表.pdf');

        });
        */
      });
    },

    btnDragColDesign() {
      this.dragColDesign = deepCopy(this.dragCol);
      this.dialogColSort = true;
      this.rowDrag();
    },

    btnDragColDesignOk() {
      this.dragCol = deepCopy(this.dragColDesign);
      this.dialogColSort = false;
    },
    //拖拽
    rowDrag() {
      this.$nextTick(() => {
        const el = document.querySelector("#elTable_dragCol tbody");
        // console.log('el0', el)
        const that = this;
        Sortable.create(el, {
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          //拖拽结束
          onEnd({ newIndex, oldIndex }) {
            that.isshow = false;
            const currRow = that.dragColDesign.splice(oldIndex, 1)[0];
            that.dragColDesign.splice(newIndex, 0, currRow);
            // console.log('el', el)
          },
        });
      });
    },
    handleExport() {
      exportToExcel("#phoneFollowUp", "随访列表", false);
      this.window.export=false
    },
  },

  //监听事件
  watch: {
    "patientRegister.query.customerOrgId": {
      // immediate: true, // 立即执行
      // deep: true, // 深度监听复杂类型内变化
      handler(newVal, oldVal) {
        //// console.log('watch:patientRegister.query.customerOrgId:',newVal,oldVal)
        // 单位变化时，清除当前列表信息
        if (newVal && newVal != oldVal) {
          this.tableData = [];
          this.dataTransOpts.tableM.register_check_asbitem = [];
        }
      },
    },

    //触发查询事件
    "patientRegister.query.times"(newVal, oldVal) {
      if (newVal != oldVal) {
        //alert('触发查询事件')
        this.Query();
      }
    },
    "window.export": {
      // immediate:true,
      handler(newVal, oldVal) {
        if (newVal){
          this.handleExport();
        }
      },
    }

    //新增后，触发赋值
    // "patientRegister.patientRegisterRd.id"(newVal, oldVal) {
    //   if (newVal != oldVal) {
    //     //// console.log('patientRegister.patientRegisterRd.customerOrgId',this.patientRegister.patientRegisterRd.customerOrgId)
    //     objCopy(this.patientRegister.patientRegisterRd, this.form);
    //   }
    // },
  },
};
</script>
<style scoped>
@import "../../assets/css/global_input.css";
@import "../../assets/css/global_table.css";
@import "../../assets/css/global.css";

.box {
  display: flex;
}

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

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