import {
  Component,
  OnInit,
  TemplateRef,
  ViewChild,
  ElementRef,
} from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { Router } from "@angular/router";

import { MainService } from "../../services/main.service";
import { WebsocketPhoneService } from "../../services/websocket-phone.service";
import { WebsocketSerService } from "../../services/websocket-ser.service";
import http from "../../../assets/js/http";

import { NzMessageService } from "ng-zorro-antd/message";
import { NzNotificationService } from "ng-zorro-antd/notification";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { SourceId } from "src/app/type/types";
import { ToolService } from 'src/app/services/tool.service';
@Component({
  selector: "app-fuwutai",
  templateUrl: "./fuwutai.component.html",
  styleUrls: ["./fuwutai.component.less"],
})
export class FuwutaiComponent implements OnInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  @ViewChild("remarksEle", { static: false }) remarksEle: ElementRef;
  @ViewChild("tabs", { static: false }) tabs: ElementRef;
  @ViewChild("tab", { static: false }) elementView: ElementRef;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef4", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef4: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef5", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef5: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef6", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef6: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef7", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef7: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef8", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef8: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef9", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef9: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef10", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef10: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef11", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef11: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef12", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef12: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef13", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef13: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef14", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef14: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    public router: Router,
    private mainService: MainService,
    private msg: NzMessageService,
    private notification: NzNotificationService,
    private phones: WebsocketPhoneService,
    private sers: WebsocketSerService,
    private tool: ToolService,
  ) {}
  validateFormZy!: FormGroup;
  validateFormQt!: FormGroup;
  // ---------------------------------------
  noWorkerPhone = false; //请求是否携带来电号码
  patientList; //患者信息列表
  isLoading: Boolean = false; //下拉框loading
  disX = 0; //移动的距离
  disStep = 0; //移动的步长
  applicationDepartmentList = []; //新建工单->申请科室列表（搜索）
  callNumber = ""; //来电号码
  workTypes = []; //任务类型
  workTypesArrange = {}; //整理后的任务类型
  workTypesFlag = false; //任务类型是否显示操作项
  currentTabIndex = ""; //获取任务类型的key
  radioValueZy: any = ""; //转运->类型
  deptZyList: any = {}; //转运->请求结果
  startDeptZy = ""; //转运->选中起点科室
  endDeptZy = ""; //转运->选中终点科室
  patientZy = ""; //转运->选中患者编码
  radioValueQt: any = ""; //转运->类型
  deptQtList: any = {}; //其他->请求结果
  startDeptQt = ""; //其他->选中起点科室
  endDeptQt = ""; //其他->选中终点科室
  workOrderRemark = ""; //工单备注
  // 新建工单弹框
  newOrderShow = false; //展示/隐藏新建工单弹框
  newOrderShowOpen = false; //展示/隐藏新建工单弹框(辅助项)
  isOkLoading = false; //确认按钮loading状态
  applyDept; //申请科室
  applyDeptMiddle; //申请科室(中间传递)
  taskBuild; //任务类型选择
  targetDept; //目标科室
  noArrives = []; //未到达列表
  newLoading = false; //loading
  //绑定分机
  bindingExtensionShow = false; //展示/隐藏绑定分机弹框
  binding = -1; //1-确定绑定，2-重新绑定，3-绑定分机
  phoneNumList = []; //所有分机列表
  phoneNumListBind = []; //已绑定分机列表
  phoneNumListSelected = []; //选中的分机列表
  phoneNumLoading = false; //分机弹窗切换页面loading
  //防抖
  changeInpSubject = new Subject();
  onSearchTaskBuildSubject = new Subject();
  searchHosDepartmentSubject = new Subject();
  searchHosDepartmentQtSubject = new Subject();
  searchPatientListSubject = new Subject();

  // 获取院区配置配置，是否核酸打印
  isShowNucleicAcidPrinting = false;
  getHospitalConfigList(key) {
    let postData = { idx: 0, sum: 1, hospitalConfig: { hosId: this.checkedHos, key } };
    this.mainService.getFetchDataList("simple/data", "hospitalConfig", postData).subscribe(result=>{
      if(result.status == 200){
        this.isShowNucleicAcidPrinting = result.list[0].value == 1;
      }else{
        this.isShowNucleicAcidPrinting = false;
      }
    });
  }

  // 打开选择楼栋多选框
  openChangeUnassignedBuilding(e) {
    if (e) {
      this.getUnassignedBuilding();
    }
  }
  // 获取楼栋-未派单
  unassignedBuildings = [];
  unassignedBuilding = [];
  bLoading = false;
  getUnassignedBuilding() {
    let postData: any = {
      hosId: this.checkedHos,
      unassignedOder: 1, //未派单
    };
    if (this.allUnassignedOrders) {
      postData.wokerIds = this.allUnassignedOrders;
    }
    this.bLoading = true;
    this.mainService
      .coopData("getBuildingOrFloor", "building", postData)
      .subscribe((result) => {
        this.bLoading = false;
        if (result.status == 200) {
          this.unassignedBuildings = result.data;
        }
      });
  }
  allUnassignedOrders = "";
  b2Loading = false;
  getUnassignedBuilding2() {
    if (this.user.user.scope) {
      this.user.user.scope.typeIds = this.user.user.scope.typeIds || [];
    } else {
      return;
    }
    let types = "";
    this.user.user.scope.typeIds.forEach((e) => {
      types += e.id + ",";
    });
    types = types.slice(0, types.length - 1);
    let postData = {
      workOrder: {
        serTaskTypes: types || "null",
        serGdState: 1,
        range: this.orderScopeRadio,
        platform: 3,
        searchDays: 1,
        keyWord: "",
      },
      idx: 0,
      sum: 9999,
    };
    this.b2Loading = true;
    this.mainService
      .getFetchDataList("ser", "workOrder", postData)
      .subscribe((result) => {
        this.b2Loading = false;
        if (result.status == 200) {
          this.allUnassignedOrders = result.list
            .map((item) => item.id)
            .toString();
        }
      });
    // -----------------------
  }
  // 选中未派单列表-全选
  changeAllUnassignedList(e) {
    this.unassignedList.forEach((v) => (v.checked = e));
    this.unassignedList.forEach((item1) => {
      this.unassignedListClone.forEach((item2) => {
        if (item1.id == item2.id) {
          item2.checked = item1.checked;
        }
      });
    });
    this.batchType = this.unassignedListClone.some((item) => item.checked);
  }
  // 选中待到达列表-全选
  changeAllArriveList(e) {
    this.arriveList.forEach((v) => (v.checked = e));
    this.arriveList.forEach((item1) => {
      this.arriveListClone.forEach((item2) => {
        if (item1.id == item2.id) {
          item2.checked = item1.checked;
        }
      });
    });
    this.batchType1 = this.arriveListClone.some((item) => item.checked);
  }
  // 添加备注
  addRemarks(item) {
    this.remarksEle.nativeElement.focus();
    this.workOrderRemark += item;
  }
  // 批量分派
  batchType = false; //是否开启批量派单
  batchDispatch() {
    let ids_types = [];
    let stateIds = [];
    this.unassignedList.forEach((item) => {
      if (item.checked) {
        if (item.gdState.value == 2) {
          //普通派单
          ids_types.push(`${item.id}_assign`);
        } else if (!item.worker && item.gdState.value != 2) {
          ids_types.push(`${item.id}_reassign`);
        }
        stateIds.push(item.gdState.id);
      }
    });
    this.router.navigateByUrl(
      "dispatchingDesk/allotWorker/" +
        ids_types.join("-") +
        "/" +
        stateIds.join("-") +
        "/2/" +
        this.checkedHos
    );
  }
  // 批量撤回
  batchType1 = false; //是否开启批量撤回
  batchClickType1 = false; //是否点击批量撤回
  batchWithdrawal() {
    this.batchClickType1 = true;
    let ids = [];
    this.arriveList.forEach((item) => {
      if (item.checked) {
        ids.push(item.id);
      }
    });
    this.openRecallModal(ids.join("-"));
  }
  // 批量分派选中
  allUnassignedList = false;
  batchDispatchSelect(e, id) {
    this.unassignedList.forEach((item) => {
      if (item.id == id) {
        item.checked = e;
      }
    });
    this.unassignedList.forEach((item1) => {
      this.unassignedListClone.forEach((item2) => {
        if (item1.id == item2.id) {
          item2.checked = item1.checked;
        }
      });
    });
    this.batchType = this.unassignedListClone.some((item) => item.checked);
    if (this.unassignedListClone.length) {
      this.allUnassignedList = this.unassignedListClone.every(
        (item) => item.checked
      );
    } else {
      this.allUnassignedList = false;
    }
  }
  // 批量撤回选中
  allArriveList = false;
  batchWithdrawalSelect(e, id) {
    this.arriveList.forEach((item) => {
      if (item.id == id) {
        item.checked = e;
      }
    });
    this.arriveList.forEach((item1) => {
      this.arriveListClone.forEach((item2) => {
        if (item1.id == item2.id) {
          item2.checked = item1.checked;
        }
      });
    });
    this.batchType1 = this.arriveListClone.some((item) => item.checked);
    if (this.arriveListClone.length) {
      this.allArriveList = this.arriveListClone.every((item) => item.checked);
    } else {
      this.allArriveList = false;
    }
  }

  // 获取科室
  applyStartDept;
  // 患者转运表单提交
  submitFormZy(go?): void {
    let newOrderShowFlag = true; //是否可以关闭弹窗
    for (const i in this.validateFormZy.controls) {
      this.validateFormZy.controls[i].markAsDirty();
      this.validateFormZy.controls[i].updateValueAndValidity();
      if (this.validateFormZy.controls[i].valid === false && i !== "goods") {
        //携带物品非必填ca
        // if (this.validateFormZy.controls[i].valid === false && i !== 'goods' && i !== 'patient') {//携带物品非必填
        newOrderShowFlag = false;
      }
      if (!this.validateFormZy.controls[i].valid) {
        this.isOkLoading = false;
        this.isGoLoading = false;
      }
    }
    if (newOrderShowFlag) {
      let goods = this.validateFormZy.controls.goods.value
        ? this.validateFormZy.controls.goods.value.filter(
            (item) => item.checked === true
          )
        : [];
      goods = goods.map((current) => current.value).join();
      let postData = {
        workOrder: {
          sourceId: SourceId.fuwutai,
          taskType: {
            id: this.validateFormZy.controls.taskType.value,
          },
          startDept: {
            id: this.validateFormZy.controls.startDept.value,
          },
          createDept: this.applyDept,
          endDepts: [
            {
              id: this.validateFormZy.controls.endDepts.value,
            },
          ],
          patient: {
            patientCode: this.validateFormZy.controls.patient.value,
          },
          goods: goods,
        },
      };
      if (!this.noWorkerPhone) {
        postData.workOrder["workOrderPhone"] = this.callNumber;
      }
      this.mainService.buildOrder(postData).subscribe((data) => {
        console.log(data);
        this.isOkLoading = false;
        this.isGoLoading = false;
        if (data["status"] == 200) {
          this.newOrderShow = false; //关闭弹窗
          if (go === "go") {
            this.applyDept = data["startDept"].id;
            this.applyStartDept = data["startDept"];
            this.callNumber = data["phone"];
            this.showPromptModal("建单", true, "", "closeGo");
          } else {
            this.showPromptModal("建单", true, "", "close");
          }
        } else {
          this.showPromptModal("建单", false, data["msg"]);
        }
      });
    }
  }
  // 标本配送表单提交
  submitFormBbps(go?) {
    let postData = {
      workOrder: {
        sourceId: SourceId.fuwutai,
        taskType: {
          id: this.workTypesArrange[this.currentTabIndex][0].taskType.id,
        },
        startDept: {
          id: this.applyDept,
        },
      },
    };
    if (!this.noWorkerPhone) {
      postData.workOrder["workOrderPhone"] = this.callNumber;
    }
    this.mainService.buildOrder(postData).subscribe((data) => {
      this.isOkLoading = false;
      this.isGoLoading = false;
      if (data["status"] == 200) {
        this.newOrderShow = false; //关闭弹窗
        if (go === "go") {
          this.applyDept = data["startDept"].id;
          this.applyStartDept = data["startDept"];
          this.callNumber = data["phone"];
          this.showPromptModal("建单", true, "", "closeGo");
        } else {
          this.showPromptModal("建单", true, "", "close");
        }
      } else {
        this.showPromptModal("建单", false, data["msg"]);
      }
    });
  }
  // 其他表单提交
  submitFormQt(go?) {
    for (const i in this.validateFormQt.controls) {
      this.validateFormQt.controls[i].markAsDirty();
      this.validateFormQt.controls[i].updateValueAndValidity();
      if (!this.validateFormQt.controls[i].valid) {
        this.isOkLoading = false;
        this.isGoLoading = false;
        return;
      }
    }
    let postData = {
      workOrder: {
        sourceId: SourceId.fuwutai,
        workOrderRemark: this.validateFormQt.controls.workOrderRemark.value,
        taskType: {
          id: this.validateFormQt.controls.taskTypeQt.value,
        },
        startDept: {
          id: this.validateFormQt.controls.startDeptQt.value,
        },
        createDept: this.applyDept,
        endDepts: [
          {
            id: this.validateFormQt.controls.endDeptsQt.value,
          },
        ],
      },
    };
    if (!this.noWorkerPhone) {
      postData.workOrder["workOrderPhone"] = this.callNumber;
    }
    this.mainService.buildOrder(postData).subscribe((data) => {
      this.isOkLoading = false;
      this.isGoLoading = false;
      if (data["status"] == 200) {
        this.newOrderShow = false; //关闭弹窗
        if (go === "go") {
          this.applyDept = data["startDept"].id;
          this.applyStartDept = data["startDept"];
          this.callNumber = data["phone"];
          this.showPromptModal("建单", true, "", "closeGo");
        } else {
          this.showPromptModal("建单", true, "", "close");
        }
      } else {
        this.showPromptModal("建单", false, data["msg"]);
      }
    });
  }
  // 核酸打印
  nucleicAcidLoading = false;
  nucleicAcidList: any = [];
  // nucleicAcidListPageIndex: number = 1;//表格当前页码
  // nucleicAcidListPageSize: number = 5;//表格每页展示条数
  // nucleicAcidListLength: number = 10;//表格总数据量
  // 获取列表数据
  getNucleicAcidBuildingSummary(idx?) {
    // if (idx) {
    //   this.nucleicAcidListPageIndex = 1;
    // }
    this.nucleicAcidLoading = true;
    this.mainService.getNucleicAcidBuildingSummary({}).subscribe((data:any) => {
      this.nucleicAcidLoading = false;
      let nucleicAcidList = data.data || [];
      for (let i = 0; i < nucleicAcidList.length; i++) {
        if(nucleicAcidList[i].deptData && Array.isArray(nucleicAcidList[i].deptData)){
          nucleicAcidList[i].deptNames = nucleicAcidList[i].deptData.map(v=>v.deptName).toString();
        }else{
          nucleicAcidList[i].deptData = [];
          nucleicAcidList[i].deptNames = '';
        }
      }
      this.nucleicAcidList = nucleicAcidList;
      console.log(this.nucleicAcidList)
      // this.nucleicAcidListLength = data.totalNum || 0;
    })
  }
  // 打印
  mapQrcodes:any = {};
  printDate:number = Date.now();
  printAucleicAcid(){
    this.isOkLoading = true;
    this.mainService.printNucleicAcid({}).subscribe((data:any) => {
      this.isOkLoading = false;
      if(data.state == 200){
        let mapQrcodes = {};
        data.data.forEach(v=>{
          mapQrcodes[v.buildId] = v.qrcode;
        })
        this.mapQrcodes = mapQrcodes;
        this.nucleicAcidPrintingCancel();
        setTimeout(()=>{
          this.printBtn.nativeElement.click();
        },0)
      }else{
        this.msg.create('error', `操作失败!`);
      }
    })
  }
  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      v !== '' && this.searchApplicationDepartment(v);
    });
    this.onSearchTaskBuildSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getTasktypeByPhone(v);
    });
    this.searchHosDepartmentSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getHosDepartment(v[0], v[1], v[2]);
    });
    this.searchHosDepartmentQtSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getHosDepartmentQt(v[0], v[1], v[2]);
    });
    this.searchPatientListSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getPatientList(v[0], v[1]);
    });
    //患者转运
    this.validateFormZy = this.fb.group({
      taskType: [null, [Validators.required]], //类型
      startDept: [null, [Validators.required]], //起点科室
      endDepts: [null, [Validators.required]], //终点科室
      patient: [null, [Validators.required]], //患者信息
      // patient: [null],//患者信息ca
      goods: [null], //携带物品
    });
    //其他
    this.validateFormQt = this.fb.group({
      taskTypeQt: [null, [Validators.required]], //类型
      startDeptQt: [null, [Validators.required]], //起点科室
      endDeptsQt: [null, [Validators.required]], //终点科室
      workOrderRemark: [null], //工单备注
    });


    this.getWebsocketSer();
    this.initRole();
    this.initLogin();
    this.retract();
    this.windowResize();
    this.refresh();
    this.initOrderScope();
    this.getOrderList(1);
    this.getOrderList(2);
    this.getOrderList(3);
    this.getOrderScope();
    this.initControlView();
    this.moveMenu();
    this.getPhoneNum();
    this.getUnassignedBuilding2();
  }
  ngOnDestroy() {
    clearInterval(this.refreshTimerId);
    this.phones.closeWs(true);
    this.sers.closeWs(true);
  }
  unassignedSearchCon: string = ""; //未分派搜索框内容
  arriveSearchCon: string = ""; //待到达搜索框内容
  executionSearchCon: string = ""; //执行中搜索框内容
  workerMessage: any = []; //顶部全部工单
  // 展示形式
  patientCareCol: number = 6; //顶部工单列数(4列-8人，7列-14人，6列-单排 ）
  hurseInfoHiding = '1'; //护工信息隐藏
  txtLabelCol: number = 1; //工单信息列数
  workerInfoTime: number = 30; //配送人员刷新时间
  orderInfoTime: number = 30; //工单刷新时间
  audioNotDispatched: boolean = true; //是否开启定时播报未派出工单提示音
  cotHeight: number; //工单初始化高度
  unassignedList: any = []; //未分派数据
  arriveList: any = []; //待到达数据
  executionList: any = []; //执行中数据
  unassignedListClone: any = null; //未分派数据clone
  arriveListClone: any = null; //待到达数据clone
  executionListClone: any = null; //执行中数据clone
  workerRefreshTime: number = 30; //配送人员刷新倒计时
  orderRefreshTime: number = 30; //工单刷新倒计时
  recallOrderShow: boolean = false; //撤回模态框
  delOrderShow: boolean = false; //删除模态框
  logoutModal: boolean = false; //退出模态框
  user = JSON.parse(localStorage.getItem("user")); //用户信息

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //是否展示提示框
  back = ""; //标识符

  btnLoading: boolean = false; //确认按钮loading状态
  recDelLoading: boolean = false; //撤回并删除loading状态
  saveLoading: boolean = false; //保存按钮loading状态

  mainRole: boolean = false; //回到系统管理权限
  initRole() {
    // let roles = JSON.parse(localStorage.getItem('user')).user.role;
    let menus = JSON.parse(localStorage.getItem("menu"));
    let that = this;
    console.log("菜单数量" + menus.length);
    if (menus.length >= 2) {
      that.mainRole = true;
      return;
    }
  }
  // 判断登录是否已失效
  initLogin() {
    let that = this;
    if (!localStorage.getItem("user")) {
      that.msg.error("您的登录已失效，请重新登录！", {
        nzDuration: 3000,
      });
      setTimeout(() => {
        that.router.navigateByUrl("login");
      }, 2000);
      return;
    }
  }

  // 连接websocket
  getWebsocketSer() {
    this.sers
      .connectWs(http.fwtWs, { userCount: this.user.user.account })
      .subscribe((result) => {
        console.log(result);
        if (result && result.content) {
          this.createBasicNotification(result);
        }
        this.windowResize();
      });
  }
  // 连接websocket---phone
  bindOkLoading = false;
  getWebsocketPhone() {
    this.bindOkLoading = true;
    let userCount =
      this.user.user.account + "|" + this.phoneNumListSelected.join("_");
    this.phones.connectWs(http.phoneWs, { userCount }).subscribe((data) => {
      // data = { status: 201, phone: '013581394341' };//ceshi
      console.log(data);
      this.bindOkLoading = false;
      if (data.status == 200 && data.phone) {
        localStorage.setItem("phones", data.phone);
        this.phoneNumListBind = data.phone.split("_");
        this.phoneNumListBind.forEach((item) => {
          let obj = this.phoneNumList.find((item1) => item1.value === item);
          if (obj) {
            obj.checked = true;
          }
        });
        this.binding = 2;
      } else if (data.status == 201 && data.phone) {
        let dataObj = {
          idx: 0,
          sum: 10,
          department: {
            searchType: 2,
            phone: data.phone,
          },
        };
        this.mainService
          .getFetchDataList("data", "department", dataObj)
          .subscribe((result) => {
            if (result.status == 200) {
              console.log(result);
              if (result.list.length > 0) {
                //绑定了科室
                // this.callNumber = '';
                if (!this.newOrderShow && !this.newOrderShowOpen) {
                  this.applyDeptMiddle = result.list[0];
                  this.showNewOrder("yes");
                }
                // this.changeApplicationDepartment();
              } else {
                //没绑定科室
                // this.callNumber = '';
                console.log(this.newOrderShow);
                if (!this.newOrderShow && !this.newOrderShowOpen) {
                  this.applyDept = null;
                  this.showNewOrder("no", data.phone);
                }
                // this.changeApplicationDepartment(data.phone);
              }
            }
          });
      } else if (data.status == 201 && data.phone === "") {
        //没绑定科室
        // this.callNumber = '';
        if (!this.newOrderShow && !this.newOrderShowOpen) {
          this.applyDept = null;
          this.showNewOrder("no", data.phone);
        }
        // this.changeApplicationDepartment(data.phone);
      }
      this.windowResize();
    });
  }
  //确定绑定
  bindingOk() {
    if (this.phoneNumListSelected.length > 0) {
      this.phones.closeWs(true);
      this.getWebsocketPhone();
    } else {
      localStorage.removeItem("phones");
      this.binding = 3;
      this.phoneNumListBind = [];
      this.phoneNumList.forEach((item) => {
        item.checked = false;
      });
      this.phones.closeWs(true);
    }
  }
  // 选择分机
  changePhones(value) {
    this.phoneNumListSelected = value;
  }

  onChange(value: number): void {
    console.log(`onChange: ${value}`);
  }

  onAfterChange(value: number): void {
    console.log(`onAfterChange: ${value}`);
  }
  // 来电咨询右侧的tab页
  // 服务台新建工单—根据申请科室id来查询转入院记录(科室id)
  rightTitle_tab = ["申请科室未到达工单", "转出院记录"];
  currentRTab = 0; //当前选中的
  loading5 = false;
  patientLogList = [];
  getPatientLog(id) {
    if (id == -1 || id === null || id === undefined) {
      this.patientLogList = [];
      return;
    }
    let postData = {
      patientLog: {
        sqDept: { id },
        hosId: this.checkedHos,
      },
      idx: 0,
      sum: 10000,
    };
    this.loading5 = true;
    this.mainService
      .getFetchDataList("api", "patientLog", postData)
      .subscribe((result) => {
        this.loading5 = false;
        if (result.status == 200) {
          this.patientLogList = result.list;
        }
      });
  }
  rightTitleHandler(i) {
    this.currentRTab = i;
    if (i === 0) {
      this.getWorkOrders(this.applyDept);
    } else if (i === 1) {
      this.getPatientLog(this.applyDept);
    }
  }
  // 服务台新建工单—根据申请科室id来查询未到达工单(科室id)
  loading4 = false;
  getWorkOrders(id) {
    if (id == -1 || id === null || id === undefined) {
      this.noArrives = [];
      return;
    }
    let types = "";
    this.user.user.scope.typeIds.forEach((e) => {
      types += e.id + ",";
    });
    types = types.slice(0, types.length - 1);
    let dataObj = {
      workOrder: {
        serTaskTypes: types,
        serGdState: 4,
        range: "0",
        platform: 3,
        searchDays: 100,
        startDept: {
          id: id,
        },
      },
      idx: 0,
      sum: 5,
    };
    this.loading4 = true;
    this.mainService
      .getFetchDataList("data", "workOrder", dataObj)
      .subscribe((data) => {
        this.loading4 = false;
        if (data.status == 200) {
          this.noArrives = data.list;
        }
      });
  }
  // 定时刷新数据
  refreshTimerId; //定时刷新定时器
  refresh() {
    this.refreshTimerId = setInterval(() => {
      // 如果没选择复选框
      if (!this.batchType && !this.batchType1) {
        this.orderRefreshTime--;
      }
      this.workerRefreshTime--;
      if (this.orderRefreshTime == 0) {
        this.getUnassignedBuilding2();
        this.getOrderList(1, true);
        this.getOrderList(2);
        this.getOrderList(3);
        if (this.currentRTab === 0) {
          this.getWorkOrders(this.applyDept);
        } else if (this.currentRTab === 1) {
          this.getPatientLog(this.applyDept);
        }
        this.orderRefreshTime = this.orderInfoTime;
      }
      if (this.workerRefreshTime == 0) {
        this.checkTab(this.typeId);
        this.workerRefreshTime = this.workerInfoTime;
      }
    }, 1000);
  }
  resetList() {
    this.unassignedListClone = null;
    this.arriveListClone = null;
    this.batchType = false;
    this.batchType1 = false;
  }
  // 刷新工单列表
  refreshList(e) {
    if (!e.promptContent) {
      return;
    }
    this.getUnassignedBuilding2();
    this.resetList();
    this.getOrderList(1);
    this.getOrderList(2);
    this.getOrderList(3);
    if (this.currentRTab === 0) {
      this.getWorkOrders(this.applyDept);
    } else if (this.currentRTab === 1) {
      this.getPatientLog(this.applyDept);
    }
  }

  // 切换顶部tab栏
  typeId = -1; //当前选中tab ID
  checkTab(typeId) {
    let that = this;
    that.typeId = typeId;
    let postData = {
      groups: [typeId],
      idx: 0,
      sum: 100,
      hosId: this.checkedHos,
    };
    if (typeId == -1) {
      let groups = [];
      that.scopeGroups.forEach((e) => {
        groups.push(e.id);
      });
      postData.groups = groups;
    }
    if (this.hurseInfoHiding == '1'){
      that.workerMessage = [];
      that.initTopCount();
      return;
    }
    that.mainService.getSerInfo("getWorkInfo", postData).subscribe((data) => {
      that.workerMessage = data.data ? data.data : [];
      that.initTopCount();
    });
    // that.workerMessage = [];
    // that.initTopCount();
  }

  // 获取三个状态数据数据
  loading1 = true;
  loading2 = true;
  loading3 = true;
  getOrderList(stateId, isAudio?) {
    let that = this;
    let keyWords = "";
    if (stateId == 1) {
      keyWords = this.unassignedSearchCon || "";
    } else if (stateId == 2) {
      keyWords = this.arriveSearchCon || "";
    } else if (stateId == 3) {
      keyWords = this.executionSearchCon || "";
    }
    if (that.user.user.scope) {
      that.user.user.scope.typeIds = that.user.user.scope.typeIds || [];
    }
    if (!that.user.user.scope || !that.user.user.scope.typeIds) {
      that.loading1 = that.loading2 = that.loading3 = false;
      return;
    }
    let types = "";
    that.user.user.scope.typeIds.forEach((e) => {
      types += e.id + ",";
    });
    types = types.slice(0, types.length - 1);
    let postData = {
      workOrder: {
        serTaskTypes: types || "null",
        serGdState: stateId,
        range: that.orderScopeRadio,
        platform: 3,
        searchDays: 1,
      },
      idx: 0,
      sum: 60,
    };
    postData.workOrder["keyWord"] = keyWords;
    if (stateId == 1) {
      if (this.unassignedBuilding.length) {
        postData.workOrder["deptIds"] = this.unassignedBuilding.toString();
      }
      that.loading1 = true;
    } else if (stateId == 2) {
      that.loading2 = true;
    } else if (stateId == 3) {
      that.loading3 = true;
    }
    console.log(postData);
    that.mainService
      .getFetchDataList("ser", "workOrder", postData)
      .subscribe((data) => {
        if (stateId == 1) {
          // 未分派
          that.unassignedList = data.list || [];
          // if (that.unassignedListClone === null) {
          that.unassignedList.forEach((item) => {
            item.checked = false;
          });
          that.batchType = false;
          that.allUnassignedList = false;
          that.unassignedListClone = JSON.parse(
            JSON.stringify(that.unassignedList)
          );
          // } else {
          //   that.unassignedList.forEach((item1) => {
          //     that.unassignedListClone.forEach((item2) => {
          //       if (item1.id == item2.id) {
          //         item1.checked = item2.checked;
          //       }
          //     });
          //   });
          //   this.batchType = this.unassignedListClone.some(
          //     (item) => item.checked
          //   );
          // }
          if (
            this.audioNotDispatched &&
            that.unassignedList.length > 0 &&
            isAudio
          ) {
            //语音播报开启
            let audio = document.createElement("audio");
            audio.src = "./../../assets/audio/audioNotDispatched.mp3";
            audio.addEventListener("canplay", function () {
              //监听audio是否加载完毕
              audio.play();
            });
          }
          that.loading1 = false;
        } else if (stateId == 2) {
          // 待到达
          that.arriveList = data.list || [];
          // if (that.arriveListClone === null) {
          that.arriveList.forEach((item) => {
            item.checked = false;
          });
          that.batchType1 = false;
          that.allArriveList = false;
          that.arriveListClone = JSON.parse(JSON.stringify(that.arriveList));
          // } else {
          // that.arriveList.forEach((item1) => {
          //   that.arriveListClone.forEach((item2) => {
          //     if (item1.id == item2.id) {
          //       item1.checked = item2.checked;
          //     }
          //   });
          // });
          // this.batchType1 = this.arriveListClone.some((item) => item.checked);
          // }
          that.loading2 = false;
        } else if (stateId == 3) {
          // 执行中
          that.executionList = data.list || [];
          that.loading3 = false;
        }

        if (keyWords) {
          that.loading1 = that.loading2 = that.loading3 = false;
        }
      });
  }

  // 页面resize
  windowResize() {
    let fixedMenu = document.getElementById("fixedMenu");
    if (!fixedMenu) return;
    let top = document.querySelector("#top");
    window.addEventListener("resize", () => {
      let wh = window.innerHeight;
      let _y = parseFloat(fixedMenu.style.top);
      if (!_y) return;
      if (_y > wh - fixedMenu.clientHeight) {
        _y = wh - fixedMenu.clientHeight;
      }
      fixedMenu.style.top = _y + "px";
    });
  }

  // 计算顶部行数
  showRowNum: number; // 已展示行数
  maxNum: number; //可展示行数最大值
  initTopCount() {
    let that = this;
    that.maxNum = Math.ceil(that.workerMessage.length / that.patientCareCol);
    that.showRowNum = that.patientCareCol == 6 ? 4 : 2;
    console.log(that.maxNum, that.showRowNum);
    that.cotHeight = 140;
  }

  // 展开顶部列表
  unfold() {
    if (this.showRowNum < this.maxNum && this.patientCareCol != 6) {
      this.cotHeight += 70;
      this.showRowNum++;
    } else if (this.showRowNum < this.maxNum && this.patientCareCol == 6) {
      this.cotHeight += 35;
      this.showRowNum++;
    } else {
      return;
    }
  }

  // 收起顶部列表
  retract() {
    this.showRowNum = this.patientCareCol == 6 ? 4 : 2;
    this.cotHeight = 140;
  }

  // 查看工单详情
  openDetails(data) {
    if (data.taskType.associationType.value == 'specimen' || data.taskType.associationType.value == 'specimenPlan') {
      // 标本类
      this.router.navigateByUrl("dispatchingDesk/detailSample/" + data.id);
    } else if (data.taskType.associationType.value == 'inspect' || data.taskType.associationType.value == 'patientTransport') {
      // 送患者
      this.router.navigateByUrl("dispatchingDesk/detailPatients/" + data.id);
    } else if (data.taskType.associationType.value == 'drugsBag' || data.taskType.associationType.value == 'jPBag') {
      // 药品配送/静配
      this.router.navigateByUrl("dispatchingDesk/detailDrug/" + data.id);
    } else if (data.taskType.associationType.value == 'ordinary') {
      // 万能交接服务
      this.router.navigateByUrl("dispatchingDesk/detailOrdinary/" + data.id);
    } else {
      // 其他
      this.router.navigateByUrl("dispatchingDesk/detailOthers/" + data.id);
    }
  }
  // 选择楼栋
  changeUnassignedBuilding(e) {
    this.getOrderList(1);
  }
  // 未分派搜索
  searchUnassigned() {
    // let that = this;
    // if (!that.unassignedSearchCon) return;
    this.getOrderList(1);
  }

  // 待到达搜索
  searchArrive() {
    // let that = this;
    // if (!that.arriveSearchCon) return;
    this.getOrderList(2);
  }

  // 执行中搜索
  searchExecution() {
    // let that = this;
    // if (!that.executionSearchCon) return;
    this.getOrderList(3);
  }

  // 派单,flag是否是下班后进入未分派的单子
  allotWorker(id, stateId, flag?) {
    if (flag == 1) {
      this.router.navigateByUrl(
        "dispatchingDesk/allotWorker/" +
          id +
          "/" +
          stateId +
          "/1/" +
          this.checkedHos
      );
    } else {
      this.router.navigateByUrl(
        "dispatchingDesk/allotWorker/" +
          id +
          "/" +
          stateId +
          "/0/" +
          this.checkedHos
      );
    }
  }

  // 右侧菜单
  showLastItems: boolean = false;
  // 下拉
  fixedMenuXiala() {
    this.showLastItems = true;
  }

  // 上拉
  fixedMenuShangla() {
    this.showLastItems = false;
    this.fixedTab = "";
  }
  // 退出系统
  logOut(): void {
    this.logoutModal = true;
  }
  // 确认退出
  confirmLogout() {
    this.btnLoading = true;
    // 假退出
    this.btnLoading = false;
    this.closeLogoutModal();
    let hospital = this.tool.getCurrentHospital();
    if(hospital){
      this.router.navigate(["login", hospital.id]);
    }else{
      this.router.navigateByUrl("login");
    }
    localStorage.removeItem("user");
    localStorage.removeItem("menu");
    localStorage.removeItem("phones");
    localStorage.removeItem("index");
    // 假退出
    this.mainService.logOut().subscribe((data) => {
      this.btnLoading = false;
      this.closeLogoutModal();
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("phones");
        localStorage.removeItem("index");
      }
    });
  }

  // 关闭模态框
  closeLogoutModal() {
    this.logoutModal = false;
  }
  // 切换右侧菜单Tab
  fixedTab: string = "";
  checkFixedTab(type: string) {
    if (type == "toSystem") {
      this.router.navigateByUrl("main");
      return;
    }
    if (type == "logout") {
      this.logOut();
    }
    if (type == "nucleicAcidPrinting") {
      this.getNucleicAcidBuildingSummary();
    }
    if (this.fixedTab == type) {
      this.fixedTab = "";
    } else {
      this.fixedTab = type;
    }
  }

  // 护工信息展示形式
  changPatientCareCol(e) {
    this.initTopCount();
  }

  ngAfterViewInit() {
    // 快捷键打开新建工单
    document.addEventListener("keydown", (e) => {
      if (e.ctrlKey && e.key == "s") {
        this.showNewOrder();
        e.preventDefault();
      }
    });
  }
  // 获取配置文件写死的任务类型ID(送病人回病房9)，选择此任务类型的话，患者信息从终点科室获取
  getConfigTasktypeLoading: boolean = false;
  getConfigTasktype() {
    let postData = {
      idx: 0,
      sum: 1,
      hospitalConfig: {
        hosId: this.checkedHos,
        key: "transDeptTypeId",
      },
    };
    this.getConfigTasktypeLoading = true;
    return this.mainService
      .getFetchDataList("simple/data", "hospitalConfig", postData)
      .toPromise();
  }
  // 获取配置文件写死的任务类型ID(转科，给转出院记录用6)
  patientLogTasktypeLoading: boolean = false;
  patientLogTasktype() {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: {
        keyconfig: "transDeptTypeId",
      },
    };
    this.patientLogTasktypeLoading = true;
    return this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .toPromise();
  }
  // 打开新建工单
  deathTasktypeId; //获取这个写死的任务类型的id,送病人回病房
  deathTasktypeIdPatient; //获取这个写死的任务类型的id,转出院记录
  async showNewOrder(des?, phone?) {
    // 送病人回病房
    let deathTasktypeResult: any = await this.getConfigTasktype();
    this.getConfigTasktypeLoading = false;
    if (deathTasktypeResult.status == 200) {
      this.deathTasktypeId = deathTasktypeResult.list[0].value;
    } else {
      return;
    }
    // 转出院记录
    let deathTasktypePatientResult: any = await this.patientLogTasktype();
    this.patientLogTasktypeLoading = false;
    if (deathTasktypePatientResult.status == 200) {
      this.deathTasktypeIdPatient =
        deathTasktypePatientResult.list[0].valueconfig;
    } else {
      return;
    }

    this.taskBuild = null;
    this.newOrderShow = true;
    this.newOrderShowOpen = true;
    this.fixedTab = "newOrder";
    this.currentRTab = 0;
    console.log(des);
    if (des === "no") {
      //没绑定科室
      this.searchApplicationDepartment("", phone);
      this.noWorkerPhone = false;
    } else if (des === "yes") {
      //绑定了科室
      this.searchApplicationDepartment("ks");
      this.noWorkerPhone = false;
    } else if (des === "go") {
      //继续建单
      this.searchApplicationDepartment("go");
      this.noWorkerPhone = false;
    } else {
      //正常初始化
      this.searchApplicationDepartment();
      this.noWorkerPhone = true;
    }
    this.getSearchTaskList("").subscribe((result) => {
      if (result.status == 200) {
        this.searchTaskLoading = false;
        this.searchTaskList = result.data;
        this.searchTaskList.forEach((item) => {
          item.sid = item.associationTypeId + "_" + item.id;
        });
        this.getAutoWorkTypes();
      }
    });
  }
  // 获取可选择的任务类型列表
  searchTaskList;
  searchTaskLoading = false;
  getSearchTaskList(keyword) {
    this.searchTaskLoading = true;
    return this.mainService.getTaskTypeBySearchKey({
      searchKey: keyword,
      hosId: this.checkedHos,
    });
  }
  //打开绑定分机
  showBindingExtension() {
    if (this.fixedTab == "bindingExtension") {
      this.fixedTab = "";
      this.bindingExtensionShow = false;
    } else {
      this.bindingExtensionShow = true;
      this.fixedTab = "bindingExtension";
    }
    if (this.phoneNumListBind.length) {
      this.binding = 2; //重新绑定
    } else {
      this.binding = 3; //绑定分机
    }
    this.getPhoneNumList();
  }
  //获取所有分机号码列表
  getPhoneNumList() {
    this.phoneNumLoading = true;
    let postData = {
      idx: 0,
      sum: 100,
      hospitalConfig: { hosId: this.checkedHos },
    };
    this.mainService
      .getFetchDataList("simple/data", "hospitalConfig", postData)
      .subscribe((result) => {
        this.phoneNumLoading = false;
        this.phoneNumList = result.list.filter(
          (item) => item.key.includes("phone_num_port") && item.value
        );
        this.phoneNumList.map((item) => {
          return { ...item, checked: false };
        });
        this.phoneNumListBind.forEach((item) => {
          let obj = this.phoneNumList.find((item1) => item1.value === item);
          if (obj) {
            obj.checked = true;
          }
        });
      });
  }
  getPhoneNum(flag = true) {
    if (!flag) {
      //切换院区的时候清除掉缓存中的号码
      localStorage.removeItem("phones");
    }
    this.phoneNumListBind = localStorage.getItem("phones")
      ? localStorage.getItem("phones").split("_")
      : [];
    this.phoneNumListSelected = localStorage.getItem("phones")
      ? localStorage.getItem("phones").split("_")
      : [];
    if (this.phoneNumListBind.length) {
      this.getWebsocketPhone();
    }
  }
  // 绑定分机，重新绑定
  bindingHandle() {
    this.binding = 1;
    this.phoneNumList.forEach((item) => {
      item.checked = false;
    });
    this.phoneNumList.forEach((item) => {
      this.phoneNumListBind.forEach((v) => {
        if (item.value == v) {
          item.checked = true;
        }
      });
    });
  }
  // 点击tab切换
  tabClick(key) {
    this.currentTabIndex = key;
    this.radioValueQt = null;
    this.startDeptQt = null;
    this.endDeptQt = null;
    this.radioValueZy = null;
    this.startDeptZy = null;
    this.endDeptZy = null;
    this.patientZy = null;
    this.goodsNow = [];
    this.workOrderRemark = "";
    this.deptZyList["startDept"] = [];
    this.deptZyList["endDept"] = [];
    this.deptZyList["startStatus"] = 0;
    this.deptZyList["endStatus"] = 0;
    this.deptQtList["startDept"] = [];
    this.deptQtList["endDept"] = [];
    this.deptQtList["startStatus"] = 0;
    this.deptQtList["endStatus"] = 0;
  }
  // 获取患者信息
  searchPatientList(id, searchWords) {
    this.searchPatientListSubject.next([id, searchWords]);
  }
  // 获取患者信息
  isLoadingPatient: boolean = false;
  getPatientList(id, searchWords) {
    let dataObj = { searchWords, deptId: id };
    this.isLoadingPatient = true;
    this.mainService.getPatientList(dataObj).subscribe((result) => {
      this.isLoadingPatient = false;
      if (result["state"] == 200) {
        this.patientList = result["data"];
        if (this.patientList.length) {
          this.patientList = this.patientList.filter((item) => !!item.bednum);
        }
      }
    });
  }

  // tab任务类型向左移动
  toLeft() {
    let maxStep = Object.keys(this.workTypesArrange).length - 5;
    this.disStep = Math.max(-maxStep, --this.disStep);
    this.disX = (this.disStep * this.elementView.nativeElement.offsetWidth) / 5;
  }
  // tab任务类型向右移动
  toRight() {
    this.disStep = Math.min(0, ++this.disStep);
    this.disX = (this.disStep * this.elementView.nativeElement.offsetWidth) / 5;
  }

  // 边输边搜节流阀
  // WS;//边输入边搜索的定时器
  WSNum = 0;
  changeInp(e) {
    this.changeInpSubject.next(e);
  }
  // 申请科室列表（搜索）
  isLoadingApply: boolean = false;
  searchApplicationDepartment(e?, phone?) {
    let keyWord = "";
    if (e && e !== "ks" && e !== "go") {
      keyWord = e;
    }
    let dataObj = {
      idx: 0,
      sum: 20,
      department: {
        cascadeHosId: this.checkedHos,
        keyWord: keyWord,
      },
    };
    this.WSNum++;
    this.isLoadingApply = true;
    this.mainService
      .getFetchDataList("data", "department", dataObj)
      .subscribe((data) => {
        this.WSNum--;
        if (this.WSNum === 0) {
          this.isLoadingApply = false;
        }
        if (data.status == 200) {
          this.applicationDepartmentList = data.list;
          if (e === undefined) {
            //初始化
            // this.applyDept = this.applicationDepartmentList[0] && this.applicationDepartmentList[0].id
            // this.callNumber = this.applicationDepartmentList[0] && this.applicationDepartmentList[0].phone
            this.changeApplicationDepartment("");
          } else if (e === "ks") {
            //绑定了科室
            let obj = this.applicationDepartmentList.find(
              (item) => item.id == this.applyDeptMiddle.id
            );
            if (!obj) {
              this.applicationDepartmentList.push(this.applyDeptMiddle);
            }
            this.applyDept = this.applyDeptMiddle.id;
            this.changeApplicationDepartment("ks");
          } else if (e === "go") {
            //继续建单
            let obj = this.applicationDepartmentList.find(
              (item) => item.id == this.applyStartDept.id
            );
            if (!obj) {
              this.applicationDepartmentList.push(this.applyStartDept);
            }
            this.applyDept = this.applyStartDept.id;
            this.changeApplicationDepartment("go");
          } else if (e === "") {
            //没绑定科室
            this.changeApplicationDepartment(phone);
          }
        }
      });
  }
  // 申请科室列表（搜索）失去焦点的时候
  changeApply(e) {
    console.log(e, this.applicationDepartmentList);
    this.changeApplicationDepartment("same");
  }
  // 申请科室列表（搜索）失去焦点的时候
  changeApplicationDepartment(phone?) {
    this.radioValueQt = null;
    this.startDeptQt = null;
    this.endDeptQt = null;
    this.radioValueZy = null;
    this.startDeptZy = null;
    this.endDeptZy = null;
    this.patientZy = null;
    this.goodsNow = [];
    this.patientList = [];
    this.workOrderRemark = "";
    this.deptZyList["startDept"] = [];
    this.deptZyList["endDept"] = [];
    this.deptZyList["startStatus"] = 0;
    this.deptZyList["endStatus"] = 0;
    this.deptQtList["startDept"] = [];
    this.deptQtList["endDept"] = [];
    this.deptQtList["startStatus"] = 0;
    this.deptQtList["endStatus"] = 0;
    console.log(phone);
    if (
      phone !== undefined &&
      phone !== "same" &&
      phone !== "ks" &&
      phone !== "go"
    ) {
      this.callNumber = phone;
      this.applyDept = null;
      this.noArrives = []; //申请科室未到达工单
      // this.workTypesArrange = [];
    } else if (phone === "ks") {
      let filter = this.applicationDepartmentList.filter(
        (item) => item.id == this.applyDept
      );
      this.callNumber = filter[0].phone;
      console.log(this.callNumber); //ceshi
      if (this.currentTabIndex == "255") {
        //患者转运
        //获取患者信息
        this.getPatientList(this.applyDept, "");
      }
      if (this.currentRTab === 0) {
        this.getWorkOrders(this.applyDept);
      } else if (this.currentRTab === 1) {
        this.getPatientLog(this.applyDept);
      }
    } else if (phone === "go") {
      if (this.currentTabIndex == "255") {
        //患者转运
        //获取患者信息
        this.getPatientList(this.applyDept, "");
      }
      if (this.currentRTab === 0) {
        this.getWorkOrders(this.applyDept);
      } else if (this.currentRTab === 1) {
        this.getPatientLog(this.applyDept);
      }
    } else if (phone === "same") {
      if (this.currentTabIndex == "255") {
        //患者转运
        //获取患者信息
        this.getPatientList(this.applyDept, "");
      }
      if (this.currentRTab === 0) {
        this.getWorkOrders(this.applyDept);
      } else if (this.currentRTab === 1) {
        this.getPatientLog(this.applyDept);
      }
    }
  }

  // 新建工单->获取新建类型
  getAutoWorkTypes() {
    this.newLoading = true;
    this.mainService.getAutoWorkTypes(this.checkedHos).subscribe((data) => {
      this.newLoading = false;
      if (data["status"] == 200) {
        this.workTypes = data["data"];
        this.workTypesArrange = [];
        // 整理后的任务类型
        this.workTypes.forEach((item) => {
          if (this.workTypesArrange[item.associationTypeId]) {
            this.workTypesArrange[item.associationTypeId].push(item);
          } else {
            this.workTypesArrange[item.associationTypeId] = [];
            this.workTypesArrange[item.associationTypeId].push(item);
          }
        });
        // 任务类型是否显示操作项
        this.workTypesFlag = Object.keys(this.workTypesArrange).length >= 5;
        // 默认选中第一项
        if (Object.keys(this.workTypesArrange).length > 0) {
          this.tabClick(Object.keys(this.workTypesArrange)[0]);
        }
      }
    });
  }
  // 终点科室选中
  endDeptZyChange() {
    if (!this.applyDept || !this.endDeptZy) {
      return;
    }
    // 终点科室患者信息列表,id是送病人回病房的任务类型，写死了
    if (this.radioValueZy == this.deathTasktypeId) {
      //获取患者信息
      this.patientZy = null;
      this.getPatientList(this.endDeptZy, "");
    } else {
      //获取患者信息
      console.log(this.deptZyList);
      if (
        this.deptZyList.startStatus != 206 &&
        this.deptZyList.endStatus != 206
      ) {
        this.patientZy = null;
      }
      this.getPatientList(this.applyDept, "");
    }
  }
  //搜索院区下面的科室(患者转运)
  searchHosDepartment(id, type, dept?) {
    if (dept) {
      this.searchHosDepartmentSubject.next([id, type, dept]);
    } else {
      this.searchHosDepartmentSubject.next([id, type]);
    }
  }
  // 搜索院区下面的科室(患者转运)
  getHosDepartment(id, type, dept?) {
    //id院区,type起点科室'start',终点科室'end'。科室名称dept。
    let value = "";
    if (dept) {
      value = dept;
    }
    if (type === "start" && this.deptZyList["startStatus"] == 202) {
      //固定科室范围，禁止搜索
      return;
    } else if (type === "end" && this.deptZyList["endStatus"] == 202) {
      //固定科室范围，禁止搜索
      return;
    }
    let postData = {
      idx: 0,
      sum: 10,
      department: {
        dept: value,
        cascadeHosId: id
      },
    };
    if (type == "start" && this.deptZyList["startStatus"] == 205) {
      postData.department["type"] = { id: this.deptZyList["startTypeId"] };
    } else if (type == "end" && this.deptZyList["endStatus"] == 205) {
      postData.department["type"] = { id: this.deptZyList["endTypeId"] };
    }
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data["status"] == 200) {
          if (type === "start") {
            this.deptZyList["startDept"] = data.list;
          } else if (type === "end") {
            this.deptZyList["endDept"] = data.list;
          }
        }
      });
  }
  //搜索院区下面的科室(其他)
  searchHosDepartmentQt(id, type, dept?) {
    if (dept) {
      this.searchHosDepartmentQtSubject.next([id, type, dept]);
    } else {
      this.searchHosDepartmentQtSubject.next([id, type]);
    }
  }
  // 搜索院区下面的科室(其他)
  getHosDepartmentQt(id, type, dept?) {
    //id院区,type起点科室'start',终点科室'end'。科室名称dept。
    let value = "";
    if (dept) {
      value = dept;
    }
    if (type === "start" && this.deptQtList["startStatus"] == 202) {
      //固定科室范围，禁止搜索
      return;
    } else if (type === "end" && this.deptQtList["endStatus"] == 202) {
      //固定科室范围，禁止搜索
      return;
    }
    let postData = {
      idx: 0,
      sum: 10,
      department: {
        dept: value,
        cascadeHosId: id
      },
    };
    if (type == "start" && this.deptQtList["startStatus"] == 205) {
      postData.department["type"] = { id: this.deptQtList["startTypeId"] };
    } else if (type == "end" && this.deptQtList["endStatus"] == 205) {
      postData.department["type"] = { id: this.deptQtList["endTypeId"] };
    }
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data["status"] == 200) {
          if (type === "start") {
            this.deptQtList["startDept"] = data.list;
          } else if (type === "end") {
            this.deptQtList["endDept"] = data.list;
          }
        }
      });
  }
  // 转运类型选中类型（单选）触发
  goodsNow; //携带的物品列表
  radioChangeZy(value) {
    //任务类型id
    if (value === "" || value === null) {
      return;
    }
    this.startDeptZy = null;
    this.endDeptZy = null;
    this.patientZy = null;
    // 返回值的status是201 则是默认发起科室，把申请科室作为值
    // 返回值的status是202 则是固定科室范围，会返回科室列表
    // 返回值的status是203 则是固定科室，会返回单个科室
    // 返回值的status是204 则让前端自己调用科室搜索接口
    // 返回值的status是205 则是固定科室类型，会返回科室列表
    // 返回值的status是206 则是默认患者所在科室，把患者所在科室作为值
    this.mainService.getdeptList(value).subscribe((data) => {
      this.deptZyList = data;
      console.log(this.deptZyList);
      // 起点科室
      if (data["startStatus"] == 201 || data["startStatus"] == 206) {
        if (this.applyDept) {
          //选择了申请科室,则起点科室就是申请科室
          this.deptZyList["startDept"] = this.applicationDepartmentList.filter(
            (item) => item.id == this.applyDept
          );
          this.startDeptZy = this.applyDept;
        }
      } else if (data["startStatus"] == 203) {
        this.startDeptZy = data["startDept"][0]["id"];
      } else if (data["startStatus"] == 204 || data["startStatus"] == 205) {
        this.getHosDepartment(this.checkedHos, "start", "");
      }
      // 终点科室
      if (data["endStatus"] == 201 || data["endStatus"] == 206) {
        if (this.applyDept) {
          //选择了申请科室,则终点科室就是申请科室
          this.deptZyList["endDept"] = this.applicationDepartmentList.filter(
            (item) => item.id == this.applyDept
          );
          this.endDeptZy = this.applyDept;
        }
      } else if (data["endStatus"] == 203) {
        this.endDeptZy = data["endDept"][0]["id"];
      } else if (data["endStatus"] == 204 || data["endStatus"] == 205) {
        this.getHosDepartment(this.checkedHos, "end", "");
      }
      // 终点科室患者信息列表,id是送病人回病房的任务类型
      if (
        (data["endStatus"] == 201 || data["endStatus"] == 203) &&
        this.radioValueZy == this.deathTasktypeId
      ) {
        if (this.currentTabIndex == "255") {
          //患者转运
          //获取患者信息
          this.getPatientList(this.endDeptZy, "");
        }
      }
    });
    // 获取携带物品
    let arr = this.workTypesArrange[this.currentTabIndex];
    this.goodsNow = arr.filter(
      (item) => item.id == value
    )[0].taskType.carryEquipmentIds;
    if (this.goodsNow) {
      this.goodsNow = this.goodsNow.map((item) => {
        return {
          label: item.name,
          value: item.id,
          checked: false,
        };
      });
    } else {
      this.goodsNow = [];
    }
  }
  radioChangeQt(value) {
    //任务类型id
    if (value === "" || value === null) {
      return;
    }
    this.startDeptQt = null;
    this.endDeptQt = null;
    // 返回值的status是201 则是默认发起科室，把申请科室作为值
    // 返回值的status是202 则是固定科室范围，会返回科室列表
    // 返回值的status是203 则是固定科室，会返回单个科室
    // 返回值的status是204 则让前端自己调用科室搜索接口
    // 返回值的status是205 则是固定科室类型，会返回科室列表
    this.mainService.getdeptList(value).subscribe((data) => {
      this.deptQtList = data;
      this.deptQtList.taskType.customRemarks = this.deptQtList.taskType
        .customRemarks
        ? this.deptQtList.taskType.customRemarks.split("$")
        : [];
      // 起点科室
      if (data["startStatus"] == 201) {
        if (this.applyDept) {
          //选择了申请科室,则起点科室就是申请科室
          this.deptQtList["startDept"] = this.applicationDepartmentList.filter(
            (item) => item.id == this.applyDept
          );
          this.startDeptQt = this.applyDept;
        }
      } else if (data["startStatus"] == 203) {
        this.startDeptQt = data["startDept"][0]["id"];
      } else if (data["startStatus"] == 204 || data["startStatus"] == 205) {
        this.getHosDepartmentQt(this.checkedHos, "start", "");
      }
      // 终点科室
      if (data["endStatus"] == 201) {
        if (this.applyDept) {
          //选择了申请科室,则终点科室就是申请科室
          this.deptQtList["endDept"] = this.applicationDepartmentList.filter(
            (item) => item.id == this.applyDept
          );
          this.endDeptQt = this.applyDept;
        }
      } else if (data["endStatus"] == 203) {
        this.endDeptQt = data["endDept"][0]["id"];
      } else if (data["endStatus"] == 204 || data["endStatus"] == 205) {
        this.getHosDepartmentQt(this.checkedHos, "end", "");
      }
    });
  }

  //新建工单->确定提交
  isGoLoading = false;
  newOrderOk(go?): void {
    if (go !== "go") {
      this.isOkLoading = true;
    } else {
      this.isGoLoading = true;
    }
    if (this.currentTabIndex == "255") {
      //患者转运
      go === "go" ? this.submitFormZy(go) : this.submitFormZy();
    } else if (this.currentTabIndex == "256") {
      //标本配送
      go === "go" ? this.submitFormBbps(go) : this.submitFormBbps();
    } else if (this.currentTabIndex == "259") {
      //其他配送
      go === "go" ? this.submitFormQt(go) : this.submitFormQt();
    }
  }

  nucleicAcidPrintingCancel():void {
    this.fixedTab = '';
  }

  newOrderCancel(): void {
    this.newOrderShow = false;
    this.newOrderShowOpen = false;
    this.currentTabIndex = "";
    this.fixedTab = "";
    this.fixedMenuShangla();
    this.radioValueQt = null;
    this.startDeptQt = null;
    this.endDeptQt = null;
    this.radioValueZy = null;
    this.startDeptZy = null;
    this.endDeptZy = null;
    this.patientZy = null;
    this.goodsNow = [];
    this.patientList = [];
    this.workOrderRemark = "";
    this.deptZyList["startDept"] = [];
    this.deptZyList["endDept"] = [];
    this.deptZyList["startStatus"] = 0;
    this.deptZyList["endStatus"] = 0;
    this.deptQtList["startDept"] = [];
    this.deptQtList["endDept"] = [];
    this.deptQtList["startStatus"] = 0;
    this.deptQtList["endStatus"] = 0;
  }

  // 携带物品
  changeGoods(value: object[]): void {
    console.log(value);
  }

  // 撤回
  // 打开撤回模态框
  openRecallModal(id) {
    this.coopId = id;
    this.recallOrderShow = true;
  }
  // 确认撤回
  confirmRec() {
    let that = this;
    that.btnLoading = true;
    let postData: any = {};
    let flags = "";
    this.coopId = this.coopId + "";
    if (this.coopId.includes("-")) {
      //批量
      flags = "batchExcuteWorkOrder";
      let ids = this.coopId.split("-");
      postData.workOrders = [];
      ids.forEach((item) => {
        postData.workOrders.push({ id: item, type: "recall" });
      });
    } else {
      flags = "excuteWorkOrder/recall";
      postData = {
        workOrder: {
          id: this.coopId,
        },
      };
    }
    that.mainService.coopWorkerOrder(flags, postData).subscribe((data) => {
      that.btnLoading = false;
      that.closeRecallOrderModal();
      if (data.status == 200) {
        that.showPromptModal("撤回", true, "");
      } else {
        that.showPromptModal("撤回", false, data.msg);
      }
    });
  }
  // 撤回并删除
  recAndDel() {
    let that = this;
    that.recDelLoading = true;
    that.mainService.delOrder(that.coopId).subscribe((data) => {
      that.recDelLoading = false;
      console.log(data);
      that.closeRecallOrderModal();
      if (data.status == 200) {
        that.showPromptModal("删除", true, "");
      } else {
        that.showPromptModal("删除", false, data.msg);
      }
    });
  }
  // 关闭撤回模态框
  closeRecallOrderModal() {
    this.recallOrderShow = false;
    this.batchClickType1 = false;
  }

  // 删除
  // 打开模态框
  coopId; //当前操作id
  openDelModal(id) {
    this.coopId = id;
    this.delOrderShow = true;
  }
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService.delOrder(that.coopId).subscribe((data) => {
      that.btnLoading = false;
      console.log(data);
      that.closeDelOrderModal();
      if (data.status == 200) {
        that.showPromptModal("删除", true, "");
      } else {
        that.showPromptModal("删除", false, data.msg);
      }
    });
  }

  // 关闭模态框
  closeDelOrderModal() {
    this.delOrderShow = false;
  }
  // 新建工单
  // 提交选择转入科室的模态框
  submitFormHand(id) {
    // 有转入科室
    this.createLoading = true;
    let postData = {
      workOrder: {
        sourceId: SourceId.fuwutai,
        taskType: {
          id: this.deathTasktypeIdPatient, //转科
        },
        startDept: {
          //起点科室
          id: this.createOrderObj.sqDept.id,
        },
        createDept: this.applyDept, //申请科室
        endDepts: [
          //终点科室
          {
            id: id,
          },
        ],
        patient: {
          patientCode: this.createOrderObj.patient.patientCode,
        },
      },
    };
    this.mainService.buildOrder(postData).subscribe((result) => {
      this.createLoading = false;
      this.deptFlag = false;
      if (result["status"] == 200) {
        this.showPromptModal("建单", true, "");
      } else {
        this.showPromptModal("建单", false, result["msg"]);
      }
    });
  }
  // 隐藏选择转入科室的模态框
  deptFlagHand(e) {
    this.deptFlag = false;
  }
  // 打开模态框,服务台右侧转入院记录建单
  createOrderObj; //当前操作id
  createLoading = false;
  deptFlag = false;
  patientLogBuild(obj) {
    this.createOrderObj = obj;
    this.deptFlag = true;
  }

  // 工单范围数据
  hosList = []; //院区
  taskTypes = []; //当前权限下所有工单类型
  userGroups = []; //当前权限下所有人员分组
  hosTaskTypes = {}; //当前权限下所有院区对应的任务类型
  hosGroups = {}; //当前权限下所有院区对应的人员分组
  getOrderScope() {
    this.hosList = this.user.infoPermission.hospitals;
    this.taskTypes = this.user.infoPermission.taskTypes;
    this.userGroups = this.user.infoPermission.groups;
    // this.checkedHos = this.user.infoPermission.hospitals ? this.user.infoPermission.hospitals[0].id : null;
    // this.orderScopeRadio = '0';
    this.hosList.forEach((e) => {
      let arrT = [],
        arrG = [];
      this.taskTypes.forEach((el) => {
        if (el.hosId.id == e.id) {
          arrT.push(el);
          this.hosTaskTypes["hos" + e.id] = arrT;
        }
      });

      this.userGroups.forEach((ele) => {
        if (ele.hospital.id == e.id) {
          arrG.push(ele);
          this.hosGroups["hos" + e.id] = arrG;
        }
      });
    });
    console.log(this.hosTaskTypes, this.hosGroups);

    // 工单范围全选按钮是否选中
    this.allTypeChecked = false;
    if (this.user.user.scope && this.user.user.scope.typeIds) {
      if (
        this.user.user.scope.typeIds.length ==
        this.hosTaskTypes["hos" + this.checkedHos].length
      ) {
        this.allTypeChecked = true;
      }
    }
    this.allGroupChecked = false;
    if (this.user.user.scope && this.user.user.scope.groupIds) {
      if (
        this.user.user.scope.groupIds.length ==
        this.hosGroups["hos" + this.checkedHos].length
      ) {
        this.allGroupChecked = true;
      }
    }
  }
  // 院区选择
  checkedHos;

  // 工单类型全选
  allTypeChecked: boolean = false; //工单类型全选框
  updateAllTypeChecked() {
    let arr = [];
    this.hosTaskTypes["hos" + this.checkedHos].forEach((e) => {
      arr.push(e.id);
    });
    this.changeTaskTypes(this.allTypeChecked ? arr : []);
    let obj = {};
    arr.forEach((e) => {
      obj[e] = this.allTypeChecked;
    });
    this.initTypes = obj;
  }

  // 工单类型
  checkedTypes = []; //已选中taskTypes的ID数组
  changeType: boolean = false; //是否改变工单类型
  hosTypesChecked = {}; //当前权限下所有院区下选中的工单类型
  changeTaskTypes(val) {
    this.checkedTypes = val;
    this.changeType = true;
    this.hosTypesChecked["hos" + this.checkedHos] = val;
    console.log(this.hosTypesChecked);
    if (val.length == this.hosTaskTypes["hos" + this.checkedHos].length) {
      this.allTypeChecked = true;
    } else {
      this.allTypeChecked = false;
    }
  }

  // 人员分组全选
  allGroupChecked: boolean = false; //工单类型全选框
  updateAllGroupChecked() {
    let arr = [];
    this.hosGroups["hos" + this.checkedHos].forEach((e) => {
      arr.push(e.id);
    });
    this.changeGroups(this.allGroupChecked ? arr : []);
    let obj = {};
    arr.forEach((e) => {
      obj[e] = this.allGroupChecked;
    });
    this.initGroups = obj;
  }
  // 人员分组
  checkedGroups = [];
  changeGroup: boolean = false; //是否改变分组
  hosGroupsChecked = {}; //当前权限下所有院区下选中的人员分组
  changeGroups(val) {
    this.checkedGroups = val;
    this.changeGroup = true;
    this.hosGroupsChecked["hos" + this.checkedHos] = val;
    console.log(this.hosGroupsChecked);
    if (val.length == this.hosGroups["hos" + this.checkedHos].length) {
      this.allGroupChecked = true;
    } else {
      this.allGroupChecked = false;
    }
  }

  // 工单范围
  orderScopeRadio;
  // 工单范围院区切换
  getTypeAndGroup() {
    this.allTypeChecked = false;
    this.allGroupChecked = false;
    for (let k1 in this.initTypes) {
      this.initTypes[k1] = false;
    }
    for (let k1 in this.initGroups) {
      this.initGroups[k1] = false;
    }
    this.orderScopeRadio = "0";
  }

  // 保存工单范围设置
  saveOrderScope() {
    let that = this;
    that.saveLoading = true;
    let types = [];
    if (!this.changeType) {
      // 没有改变当前工单类型设置，取初始化设置，
      for (var i in that.initTypes) {
        if (that.initTypes[i]) {
          types.push(Number(i));
        }
      }
    } else {
      // that.checkedTypes.forEach(function (val) {
      //   types.push(Number(val))
      // })
      let arr = this.hosTypesChecked["hos" + this.checkedHos] || [];
      arr.forEach(function (val) {
        types.push(Number(val));
      });
    }

    let groups = [];
    if (!this.changeGroup) {
      // 没有改变当前分组设置，取初始化设置，
      for (var k in that.initGroups) {
        if (that.initGroups[k]) {
          groups.push(Number(k));
        }
      }
    } else {
      // that.checkedGroups.forEach(function (val) {
      //   groups.push(Number(val))
      // })
      let arr = this.hosGroupsChecked["hos" + this.checkedHos] || [];
      arr.forEach(function (val) {
        groups.push(Number(val));
      });
    }
    types = [...new Set(types)];
    groups = [...new Set(groups)];

    let groupsId = [];
    groups.forEach((e) => {
      groupsId.push({ id: e });
    });
    let typesId = [];
    types.forEach((e) => {
      typesId.push({ id: e });
    });

    let postData = {
      workerOrderScope: {
        hospitalId: { id: that.checkedHos - 0 },
        typeIds: typesId,
        groupIds: groupsId,
        range: that.orderScopeRadio - 0,
        userId: that.user.user.id,
      },
    };
    if (that.user.user.scope && that.user.user.scope.id) {
      postData.workerOrderScope["id"] = that.user.user.scope.id;
    }
    console.log(postData);
    // return
    that.mainService
      .coopTypeConfig("addData", "workerOrderScope", postData)
      .subscribe((data) => {
        that.saveLoading = false;
        if (data.status == 200) {
          that.showPromptModal("保存", true, "");
          // 关闭phone的websocket
          this.phones.closeWs(true);
          this.getPhoneNum(false);
          that.user.user.scope = data.data;
          localStorage.setItem("user", JSON.stringify(that.user));
          that.initOrderScope();
          that.getOrderScope();
          that.initControlView();
        } else {
          that.showPromptModal("保存", false, data.msg);
        }
      });
  }
  // 确认工单范围设置
  confirmOrderScope() {
    let that = this;
    that.btnLoading = true;
    let types = [];
    if (!that.changeType) {
      // 没有改变当前工单类型设置，取初始化设置，
      for (var i in that.initTypes) {
        if (that.initTypes[i]) {
          types.push(Number(i));
        }
      }
    } else {
      that.hosTypesChecked["hos" + that.checkedHos].forEach(function (val) {
        types.push(Number(val));
      });
    }

    let groups = [];
    if (!that.changeGroup) {
      // 没有改变当前分组设置，取初始化设置，
      for (var k in that.initGroups) {
        if (that.initGroups[k]) {
          groups.push(Number(k));
        }
      }
    } else {
      that.hosGroupsChecked["hos" + that.checkedHos].forEach(function (val) {
        groups.push(Number(val));
      });
    }
    types = [...new Set(types)];
    groups = [...new Set(groups)];

    that.user.user.scope.range = that.orderScopeRadio - 0;
    that.hosList.forEach((e) => {
      if (e.id == that.checkedHos) {
        that.user.user.scope.hospitalId = e;
      }
    });
    let arrT = [],
      arrG = [];
    console.log(that.hosTaskTypes, types);
    that.hosTaskTypes["hos" + that.checkedHos].forEach((e) => {
      types.forEach((el) => {
        if (e.id == el) {
          arrT.push(e);
        }
      });
    });
    that.hosGroups["hos" + that.checkedHos].forEach((e) => {
      groups.forEach((el) => {
        if (e.id == el) {
          arrG.push(e);
        }
      });
    });
    that.user.user.scope.typeIds = arrT;
    that.user.user.scope.groupIds = arrG;

    console.log(that.user);
    that.initOrderScope();
    that.getOrderList(1);
    that.getOrderList(2);
    that.getOrderList(3);
    that.getOrderScope();
    that.initControlView();
    that.msg.success("修改成功！", {
      nzDuration: 1000,
    });
    that.btnLoading = false;

    that.fixedTab = "";
    that.fixedMenuShangla();
  }
  // 工单范围设置回显
  initTypes = {}; //工单类型
  initGroups = {}; //人员分组
  scopeGroups = []; //当前所属人员分组
  scopeTypes = []; //当前所属人员类型
  initOrderScope() {
    if (!this.user || !this.user.user || !this.user.user.scope) return;
    let scopeInfo = this.user.user.scope;
    this.checkedHos = scopeInfo.hospitalId ? scopeInfo.hospitalId.id : null;
    this.orderScopeRadio = scopeInfo.range + "";
    if (!this.taskTypes.length) {
      this.initTypes = {};
    } else {
      this.taskTypes.forEach((val, idx) => {
        this.initTypes[val.id] = false;
      });
    }
    if (!scopeInfo.typeIds) {
      this.initTypes = {};
      this.allTypeChecked = false;
    } else {
      scopeInfo.typeIds.forEach((val, idx) => {
        this.initTypes[val.id] = true;
      });
    }

    console.log(this.initTypes);

    if (!this.userGroups || !this.userGroups.length) {
      this.initGroups = {};
    } else {
      this.userGroups.forEach((val, idx) => {
        this.initGroups[val.id] = false;
      });
    }
    if (!scopeInfo.groupIds || !scopeInfo.groupIds.length) {
      this.initGroups = {};
    } else {
      scopeInfo.groupIds.forEach((val, idx) => {
        this.initGroups[val.id] = true;
      });
    }
    this.scopeGroups = scopeInfo.groupIds || [];
    this.scopeTypes = scopeInfo.typeIds || [];
    console.log(this.scopeGroups, this.initGroups);
    console.log(this.scopeTypes, this.initTypes);
    this.getHospitalConfigList('allowNucleicAcidPrinting');
  }

  // 初始化展示形式
  controlView = {}; //展示形式
  initControlView() {
    let that = this;
    let postData = {
      controlView: { userId: that.user.user.id, hosId: this.checkedHos },
      idx: 0,
      sum: 1,
    };
    that.mainService
      .coopTypeConfig("fetchDataList", "controlView", postData)
      .subscribe((data) => {
        that.controlView = data.list[0] ? data.list[0] : [];
        if (!data.list.length) return;
        switch (data.list[0].workerNum) {
          case 1:
            that.patientCareCol = 6;
            break;
          case 2:
            that.patientCareCol = 7;
            break;
          case 3:
            that.patientCareCol = 4;
            break;
        }
        this.hurseInfoHiding = data.list[0].hurseInfoHiding ? "1" : "0";
        that.txtLabelCol = data.list[0].labelNum;
        that.orderRefreshTime = that.orderInfoTime = data.list[0].orderInfoTime;
        that.workerRefreshTime = that.workerInfoTime =
          data.list[0].workerInfoTime;
        that.audioNotDispatched = data.list[0].unsendOrderVoice !== false;
        that.checkTab(this.typeId);
      });
  }

  // 保存展现形式
  saveControlView() {
    let that = this;
    that.saveLoading = true;
    let wn;
    switch (that.patientCareCol) {
      case 6:
        wn = 1;
        break;
      case 7:
        wn = 2;
        break;
      case 4:
        wn = 3;
        break;
    }

    let postData = {
      controlView: {
        hosId: this.checkedHos,
        userId: that.user.user.id,
        workerNum: wn,
        labelNum: that.txtLabelCol,
        workerInfoTime: that.workerInfoTime,
        orderInfoTime: that.orderInfoTime,
        unsendOrderVoice: that.audioNotDispatched,
        hurseInfoHiding: that.hurseInfoHiding === "1",
      },
    };
    if (that.controlView["id"]) {
      postData.controlView["id"] = that.controlView["id"];
    }

    console.log(postData);
    that.mainService
      .coopTypeConfig("addData", "controlView", postData)
      .subscribe((data) => {
        that.saveLoading = false;
        if (data.status == 200) {
          that.showPromptModal("保存", true, "");
          that.initControlView();
        } else {
          that.showPromptModal("保存", false, data.msg);
        }
      });
  }

  // 第一次打开调度台页面初始化范围设置
  showInitModal: boolean = true;
  cancelInit() {
    this.showInitModal = false;
  }

  closeModel(e) {
    if (e === "close") {
      this.newOrderShowOpen = false; //此时可出现新的弹窗
    } else if (e === "closeGo") {
      this.showNewOrder("go");
    }
  }
  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?, back?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    this.back = back || "";
    setTimeout(() => {
      this.getUnassignedBuilding2();
      this.resetList();
      this.getOrderList(1);
      this.getOrderList(2);
      this.getOrderList(3);
      if (this.currentRTab === 0) {
        this.getWorkOrders(this.applyDept);
      } else if (this.currentRTab === 1) {
        this.getPatientLog(this.applyDept);
      }
      this.promptModalShow = true;
      this.fixedTab = "";
      this.fixedMenuShangla();
    }, 100);
  }

  // 格式化时分秒
  // （时间小于一分钟则显示秒，时间大于一分钟则显示分钟数，如超出一小时则显示小时和分钟。）time: 秒
  formatTime(time) {
    let timeStr = "";
    if (time >= 0 && time < 60) {
      // 秒
      timeStr = time + "秒";
    } else if (time >= 60 && time < 3600) {
      // 分钟
      timeStr = Math.floor(time / 60) + "分钟";
    } else if (time >= 3600) {
      // 时 + 分
      let h = "";
      let m = "";
      h = Math.floor(time / 3600) + "小时";
      m = time % 3600 >= 60 ? Math.floor((time % 3600) / 60) + "分钟" : "";
      timeStr = h + m;
    }
    return timeStr;
  }

  // 菜单拖拽
  moveMenu() {
    let fixedMenu = document.getElementById("fixedMenu");
    if (!fixedMenu) return;
    fixedMenu.onmousedown = function (e) {
      fixedMenu.style.cursor = "move";
      let y = e.clientY - fixedMenu.offsetTop;
      document.onmousemove = function (ev) {
        var _y = ev.clientY - y > 0 ? ev.clientY - y : 0;
        var wh = window.innerHeight;
        if (_y > wh - fixedMenu.clientHeight) {
          _y = wh - fixedMenu.clientHeight;
        }
        fixedMenu.style.top = _y + "px";
      };
      document.onmouseup = function () {
        fixedMenu.style.cursor = "default";
        this.onmousemove = null;
        this.onmouseup = null;
      };
      // return false;
    };
  }

  @ViewChild("msgTemplate", { static: false }) msgTemplate: TemplateRef<any>; //消息通知模板
  // 消息提醒
  createBasicNotification(msgs): void {
    this.notification.template(this.msgTemplate, {
      nzDuration: 0,
      nzData: msgs,
    });
  }
  // tab头部分组向左移动
  disXHead = 0;
  headToLeft() {
    let num = Math.floor(this.tabs.nativeElement.offsetWidth / 126);
    let maxStep = this.scopeGroups.length - (num - 1);
    this.disStep = Math.max(-maxStep, --this.disStep);
    this.disXHead = this.disStep * 126;
  }
  // tab头部分组向右移动
  headToRight() {
    this.disStep = Math.min(0, ++this.disStep);
    this.disXHead = this.disStep * 126;
  }
  //服务台建单任务类型搜索查询
  onSearchTaskBuild(e) {
    this.onSearchTaskBuildSubject.next(e);
  }
  //获取任务类型
  getTasktypeByPhone(e) {
    this.getSearchTaskList(e).subscribe((result) => {
      if (result.status == 200) {
        this.searchTaskLoading = false;
        this.searchTaskList = result.data;
        this.searchTaskList.forEach((item) => {
          item.sid = item.associationTypeId + "_" + item.id;
        });
      }
    });
  }
  //服务台建单任务类型回车,0_1,0是关联类型，1是任务类型
  changeTaskBuild(e) {
    let arr = e.split("_");
    this.currentTabIndex = arr[0];
    if (this.currentTabIndex == "255") {
      //患者其他服务业务
      this.radioValueZy = +arr[1];
    } else if (this.currentTabIndex == "259") {
      //其他临床服务
      this.radioValueQt = +arr[1];
    }
  }
}
