import { Component, OnInit, TemplateRef, ViewChild, OnDestroy  } from "@angular/core";
import { NavigationEnd, Router } from "@angular/router";
import { MainService } from "../../services/main.service";

import { NzMessageService } from "ng-zorro-antd/message";
import { WebsocketMainService } from "../../services/websocket-main.service";
import http from "../../../assets/js/http";
import { Subject, forkJoin } from "rxjs";
import { debounceTime, filter, map } from "rxjs/operators";
import { SourceId } from "src/app/type/types";
import { addDays, differenceInCalendarDays, getHours, getMinutes, setMinutes, parse, format, addHours, startOfDay, endOfDay } from 'date-fns';
import { UploadFile } from 'ng-zorro-antd';
import { NzNotificationService } from "ng-zorro-antd/notification";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import cloneDeep from 'lodash-es/cloneDeep'
import { HttpRequest, HttpClient, HttpResponse } from '@angular/common/http';
import { WebsocketIncomingService } from 'src/app/services/websocket-incoming.service';

declare const tlwsa: any;
declare const TLWSA: any;

// 日期禁用
function range(start: number, end: number): number[] {
  const result: number[] = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}

@Component({
  selector: "app-main",
  templateUrl: "./main.component.html",
  styleUrls: ["./main.component.less"],
})
export class MainComponent implements OnInit, OnDestroy {
  userInfo: any = JSON.parse(localStorage.getItem("user"));
	user: any = JSON.parse(localStorage.getItem("user"));
  menus: any = JSON.parse(localStorage.getItem("menu"));
  currentHospital; //当前院区
  routerEventsListener; //监听路由
	homeRole: boolean = false; //首页权限
	speediness: boolean = false; //新增报修权限
  deskRole: boolean = false; //调度台权限
  nurseRole: boolean = false; //护士端权限
  pharmacyRole: boolean = false; //药房端权限
  largeScreenRole: boolean = false; //综合大屏权限
  largeScreenRole2: boolean = false; //运送陪检大屏权限
  largeScreenRole3: boolean = false; //运维大屏权限
  specimenViewRole: boolean = false; //业务视图权限
  specimenViewRole2: boolean = false; //标本视图权限
	specimenRoomView: boolean = false; //标本间权限
	pathology: boolean = false; //病理科权限
	sampling: boolean = false; //门诊病理采样端权限
	communicationBook: boolean = false; //病理交接本权限
  disinfectionSupplyRole: boolean = false; //全局业务查看权限
  realtimeBroadcastRole: boolean = false; //故障实时播报
  inspectClosedLoopViewRole: boolean = false; //陪检闭环视图
	webRepairs: boolean = false; //web报修端权限
  incidentConfigRole: boolean = false; //事件配置权限
  otherConfigRole: boolean = false; //三方配置权限
  pageConfigRole: boolean = false; //业务页面控制权限
  nurseConfigRole: boolean = false; //护士端配置控制权限
  PCCommutesToWork: boolean = false; //PC上下班权限
  newStatisticsRole: boolean = false; //新版统计权限
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    public router: Router,
    private mainService: MainService,
    private msg: NzMessageService,
    private notification: NzNotificationService,
    private webs: WebsocketMainService,
    public tool: ToolService,
		public incomingService: WebsocketIncomingService,
		private http: HttpClient,
		// private eventSubscription: Subscription
  ) {}

	eventData:any
  ngOnInit() {
		this.getEvent();
		this.initHospitalAndDuty(this.tool.getCurrentHospital());
    this.highlightMenuByUrl();
    this.routerEventsListener = this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe((event) => {
        this.highlightMenuByUrl();
      });
    this.currentHospital = this.tool.getCurrentHospital();
    this.initLogin();
    this.initMenu();
    this.getWebsocket();
  }

	getEvent(){
		// 全局监听
		let that = this;
		that.tool.getEventObservable().subscribe(res => {
			that.eventData = res;
			console.log('全局的监听触发111111', that.eventData);
			if(that.eventData.message == '建单'){
				that.speedinessAdd()
			}
		});
	}

  // 离开管理端
  ngOnDestroy() {
    //取消路由监听
    this.routerEventsListener.unsubscribe();
    // 断掉连接
    this.webs.closeWs(true);

		// if (this.eventSubscription) {
			// this.eventSubscription.unsubscribe();
		// }
  }

  // 菜单图标名称是否包含transport-
  isTransportIcon(icon:any) {
    if(icon){
      return icon.indexOf("transport-") > -1;
    }else{
      return false;
    }
  }

  //上下班
  loading3 = false;
  workModal: boolean = false; //模态框
  showWorkModal() {
    this.workModal = true;
  }
  hideWorkModal() {
    this.workModal = false;
  }
  confirmWork() {
    this.loading3 = true;
    if (this.userInfo.user.online) {
      // 判断当前启用的工作方案是自主还是综合排班
      this.getUserWorkDept().then((ress:any) => {
        if (ress.status == 200) {
          let workType = ress.settings ? ress.settings.workType : -1; //1是综合，2是自主
          // 自主下班,并且是科室绑定人员,科室绑定分组，绑定分组
          if (workType == 2) {
            this.loading3 = false;
            this.msg.info('不支持此上班模式！');
          } else {
            this.mainService.onOrOffLine({
              type: "off",
            }).subscribe((res:any) => {
              if (res.status == 200) {
                this.getCurrentUserNow();
              } else {
                this.loading3 = false;
                this.msg.error('操作失败');
              }
            });
          }
        } else if (ress.status == 500) {
          //500的时候自选下班
          this.customOff();
        } else {
          this.loading3 = false;
          this.msg.error('操作失败');
        }
      });
    } else {
      this.getWorkScheme();
    }
  }

  // 获取启动中的工作分配方案
  workSchemeType:any = ""; //启动中工作分配方案类型
  getWorkScheme() {
    let postData = {
      idx: 0,
      workScheme: {
        status: 1,
        hosId: this.currentHospital.id
      },
      sum: 1,
    };
    this.mainService.getFetchDataList("simple/data", "workScheme", postData).subscribe((res) => {
      if (res.status == 200) {
        if(Array.isArray(res.list) && res.list.length){
          this.workSchemeType = res.list[0].workType;
          if (this.workSchemeType == 2) {
            this.loading3 = false;
            this.msg.info('不支持此上班模式！');
          } else if (this.workSchemeType == 1) {
            this.mainService.onOrOffLine({
              type: "on",
            }).subscribe((res:any) => {
              if (res.status == 200) {
                this.getCurrentUserNow();
              } else {
                this.loading3 = false;
                this.msg.error('操作失败');
              }
            });
          }
        }
      } else {
        this.loading3 = false;
        this.msg.error('操作失败');
      }
    });
  }

  // 下班
  customOff() {
    this.mainService.onOrOffLine({
      type: "off",
      customWorking: "off",
    }).subscribe((res:any) => {
      if (res.status == 200) {
        this.getCurrentUserNow();
      } else {
        this.loading3 = false;
        this.msg.error('操作失败');
      }
    });
  }

  // 获取执行中列表
  getWorkingNum() {
    return this.mainService.coopWorkerOrder("executingOrders", {
      idx: 0,
      sum: 1,
    }).toPromise();
  }

  // 获取启动中的工作分配方案
  getUserWorkDept() {
    return this.mainService.getUserWorkDept({}).toPromise();
  }

  // 获取当前用户信息
  getCurrentUserNow() {
    this.mainService.getCurrentUser1().subscribe((data:any) => {
      this.loading3 = false;
      if (data.status == 200) {
        let user = JSON.parse(localStorage.getItem("user"));
        user.user = data.data;
        this.userInfo.user = data.data;
        localStorage.setItem("user", JSON.stringify(user));
        this.hideWorkModal();
        this.msg.success('操作成功！');
      }
    });
  }

  // 上下班
  types = "";
  async GoWork() {
    let workingNum = 0;
    if (this.userInfo.user.online) {
      this.maskFlag = this.msg.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      let workingNumResult = await this.getWorkingNum();
      this.msg.remove(this.maskFlag);
      this.maskFlag = false;
      if (workingNumResult.status == 200) {
        workingNum = workingNumResult.data.data.length;
      }
      if (workingNum) {
        this.types = "您还<b style='color:red'>有未完成的工单</b>，确定下班后，<b style='color:red'>未完成工单将不计算积分。</b>";
      } else {
        this.types = "确定是否下班 ?";
      }
    } else {
      this.types = "确定是否上班 ?";
    }
    this.showWorkModal();
  }

  // 根据url高亮菜单baba
  highlightMenuByUrl() {
    console.log(this.router.url);
    let navOne, navTwo;
    let link = this.router.url.split("/").slice(-1)[0];
    let menus = JSON.parse(localStorage.getItem("menu"));
    if (link == "home") {
      this.toMenu("首页");
    } else {
      menus.forEach((oneNav) => {
        if (oneNav.childrens) {
          let findTwoNav = oneNav.childrens.find(
            (twoNav) => twoNav.link == link
          );
          if (findTwoNav) {
            navTwo = findTwoNav;
            navOne = oneNav;
            this.toMenu(navTwo.title, navTwo, navOne);
          }
        }
      });
    }
  }

  // 一级导航点击
  clickMenuOne(data) {
    let menus = JSON.parse(localStorage.getItem("menu"));
    data.flag = !data.flag;
    menus.find((item) => item.id == data.id).flag = data.flag;
    localStorage.setItem("menu", JSON.stringify(menus));
  }
  initMenu() {
    let menus = JSON.parse(localStorage.getItem("menu"));
    let arr = [];
    menus.forEach((e) => {
			if (e.link == "home") {
			  this.homeRole = true;
			  console.log("首页权限");
			}
      if (e.link == "nurse") {
        this.nurseRole = true;
        console.log("护士端权限");
      }
      if (e.link == "dispatchingDesk") {
        this.deskRole = true;
        console.log("调度台权限");
      }
      if (e.link == "pharmacy") {
        this.pharmacyRole = true;
        console.log("药房端权限");
      }
      if (e.link == "largeScreen") {
        this.largeScreenRole = true;
        console.log("综合大屏权限");
      }
      if (e.link == "largeScreen2") {
        this.largeScreenRole2 = true;
        console.log("运送陪检大屏权限");
      }
			if (e.link == "largeScreen3") {
        this.largeScreenRole3 = true;
        console.log("运维大屏权限");
      }
      if (e.link == "specimenView") {
        this.specimenViewRole = true;
        console.log("业务视图权限");
      }
      if (e.link == "specimenView2") {
        this.specimenViewRole2 = true;
        console.log("标本视图权限");
      }
			if (e.link == "specimenRoomView") {
			  this.specimenRoomView = true;
			  console.log("标本间权限");
			}
			if (e.link == "pathology") {
			  this.pathology = true;
			  console.log("病理科权限");
			}
			if (e.link == "pathologySample") {
			  this.sampling = true;
			  console.log("门诊病理采样端权限");
			}
			if (e.link == "pathologyCommunicationBook") {
			  this.communicationBook = true;
			  console.log("病理交接本权限");
			}
      if (e.link == "disinfectionSupply") {
        this.disinfectionSupplyRole = true;
        console.log("全局业务查看权限");
      }
      if (e.link == "realtimeBroadcast") {
        this.realtimeBroadcastRole = true;
        console.log("故障实时播报权限");
      }
      if (e.link == "inspectClosedLoopView") {
        this.inspectClosedLoopViewRole = true;
        console.log("陪检闭环视图权限");
      }
      if (e.link == "incidentConfig") {
        this.incidentConfigRole = true;
        console.log("事件配置权限");
      }
      if (e.link == "otherConfig") {
        this.otherConfigRole = true;
        console.log("三方配置权限");
      }
      if (e.link == "pageConfig") {
        this.pageConfigRole = true;
        console.log("业务页面控制权限");
      }
      if (e.link == "nurseConfig") {
        this.nurseConfigRole = true;
        console.log("护士端配置控制权限");
      }
      if (e.link == "PCCommutesToWork") {
        this.PCCommutesToWork = true;
        console.log("PC上下班");
      }
      if (e.type == "newStatistics") {
        this.newStatisticsRole = true;
        console.log("新版统计");
      }
			if (e.link == "webRepairs") {
			  this.webRepairs = true;
			  console.log("PC上下班");
			}
			if (e.title == "故障管理") {
				let item = e.childrens.find(i=>i.link=="incidentManagement")
				if(item){
					let item2 = item.childrens.find(i=>i.link=="add")
					if(item2){
						this.speediness = true
						console.log("新增故障工单权限");
					}
				}
			}
      if (!e.link) {
        arr.push(e);
      }
    });
    this.menus = arr.filter(v => v.type === 'default');
  }

  // 判断登录是否已失效
  initLogin() {
    if (!this.userInfo) {
      this.msg.error("您的登录已失效，请重新登录！", {
        nzDuration: 3000,
      });
      setTimeout(() => {
        this.router.navigateByUrl("login");
      }, 2000);
      return;
    }
  }

  // 新密码失去焦点
  enoughRegFlag = true; //弱
  mediumRegFlag = false; //中
  strongRegFlag = false; //强
  blurNewPwd(){
    let enoughReg = /^.{0,6}$/;//密码强度-弱
    let strongReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\!\@\#\$\%\^\&\*]).{9,}$/;//密码强度-强
    this.enoughRegFlag = enoughReg.test(this.upModalData.newPwd);
    this.strongRegFlag = strongReg.test(this.upModalData.newPwd);
    this.mediumRegFlag = !this.enoughRegFlag && !this.strongRegFlag;
    console.log(this.enoughRegFlag,this.mediumRegFlag,this.strongRegFlag);
  }

  // 跳转页面
  menuLabel: string; //当前菜单名称
  indexFlag = localStorage.getItem("index") === "true" ? true : false; //首页高亮
  toMenu(title, item?, data?) {
    sessionStorage.setItem("title", title);
    this.menuLabel = sessionStorage.getItem("title");
    if (item && data) {
      // 首页取消高亮
      this.indexFlag = false;
      localStorage.setItem("index", "false");
      // 操作本地存储
      let menus = JSON.parse(localStorage.getItem("menu"));
      menus.forEach((item1) => {
        item1.flagBg = false;
        if (item1.childrens) {
          item1.childrens.forEach((value) => {
            value.flag = false;
          });
        }
      });
      let obj = menus.find((value) => value.id == data.id);
      obj.flagBg = true;
      obj.flag = true;
      obj.childrens.find((value) => value.id == item.id).flag = true;
      localStorage.setItem("menu", JSON.stringify(menus));
      // 操作菜单一级 二级
      this.menus = menus.filter((item) => !item.link);
    } else {
      // 首页高亮
      this.indexFlag = true;
      localStorage.setItem("index", "true");
      // 操作本地存储
      let menus = JSON.parse(localStorage.getItem("menu"));
      menus.forEach((item1) => {
        item1.flagBg = false;
        // item1.flag = false;
        if (item1.childrens) {
          item1.childrens.forEach((value) => {
            value.flag = false;
          });
        }
      });
      localStorage.setItem("menu", JSON.stringify(menus));
      // 操作菜单一级 二级
      this.menus = menus.filter((item) => !item.link);
    }
  }

  // 子路由跳转事件
  activeRoute() {
    this.menuLabel = sessionStorage.getItem("title");
  }

	/* 新增报修 start*/
	// 打开新建工单
	currentTabIndex:any = '故障报修'
	noWorkerPhone = false; //请求是否携带来电号码
	patientList; //患者信息列表
	isLoading: Boolean = false; //下拉框loading
	disX = 0; //移动的距离
	disStep = 0; //移动的步长
	applicationDepartmentList = []; //新建工单->申请科室列表（搜索）
	callNumber = ""; //来电号码
	workTypes = []; //任务类型
	workTypesArrange = []; //整理后的任务类型
	workTypesFlag = false; //任务类型是否显示操作项
	radioValueZy: any = ""; //转运->类型
	radioValueZyPre: any = ""; //转运->类型
	deptZyList: any = {}; //转运->请求结果
	startDeptZy = ""; //转运->选中起点科室
	endDeptZy = ""; //转运->选中终点科室
	patientZy = ""; //转运->选中患者编码
	radioValueQt: any = ""; //转运->类型
	deptQtList: any = {}; //其他->请求结果
	startDeptQt = ""; //其他->选中起点科室
	endDeptQt = ""; //其他->选中终点科室
	workOrderRemark = ""; //工单备注
	workOrderRemarkZy = ""; //工单备注
	// 新建工单弹框
	newOrderShow = false; //展示/隐藏新建工单弹框
	newOrderShowOpen = false; //展示/隐藏新建工单弹框(辅助项)
	isOkLoading = false; //确认按钮loading状态
	applyDept; //申请科室
	applyDeptMiddle; //申请科室(中间传递)
	taskBuild; //任务类型选择
	residenceNo; //住院号
	targetDept; //目标科室
	noArrives = []; //未到达列表
	newLoading = false; //loading
	//防抖
	changeInpSubject = new Subject();
	changeCommonInpSubject = new Subject();
	onSearchTaskBuildSubject = new Subject();
	searchHosDepartmentSubject = new Subject();
	searchHosDepartmentQtSubject = new Subject();
	searchPatientListSubject = new Subject();
	inspectSubject = new Subject();
	changeAssetInpSubject = new Subject();
	
	// 运维相关
	incidentModel:any = {};
	incidentMsg:any = {};

	// 初始化增删改按钮
	coopBtns: any = {};

	工单范围设置回显
	checkedHos;// 配送-院区选择
	checkedHosDTO;// 配送-院区选择
	scopeGroups = []; //配送-当前所属人员分组
	orderScopeRadio;// 配送-工单范围

	itsmCheckedHos;// 运维-院区选择
	itsmScopeGroups = []; //运维-当前所属人员分组
	itsmOrderScopeRadio;// 运维-工单范围
	coopData:any;
	hsmsData: any = {
	  checkedHos: undefined,
	  scopeGroups: [],
	  orderScopeRadio: '0',
	}; //转运工单范围相关信息

	itsmData: any = {
	  checkedHos: [],
	  scopeGroups: [],
	  orderScopeRadio: '0',
	}; //运维工单范围相关信息
	flagList:any = {
	  itsmFlag1: false,
	  hsmsFlag1: false,
	  itsmFlag2: false,
	  hsmsFlag2: false,
	  itsmFlag3: false,
	  hsmsFlag3: false,
	}
	tabs:any;
	showInitModal:boolean = false;

	// 定时刷新数据
	refreshTimerId; //定时刷新定时器
	refresh() {
	  clearTimeout(this.refreshTimerId);
	  this.refreshTimerId = setTimeout(() => {
	    this.refresh()
	    this.orderRefreshTime--;
	    if (this.orderRefreshTime == 0) {
	      if (this.currentRTab === 0) {
	        this.getWorkOrders(this.applyDept);
	      } else if (this.currentRTab === 1) {
	        this.getPatientLog(this.applyDept);
	      } else if (this.currentRTab === 2) {
	        this.getItsmOrders(this.incidentModel.department);
	      } else if (this.currentRTab === 3) {
	        this.getDictionaryList();
	      }
	      this.orderRefreshTime = this.orderInfoTime;
	    }
	  }, 1000);
	}

	showOrderScope() {
	  this.showInitModal = true;
		this.refresh()
	}

	initOrderScope() {
	  // let scopeInfo = this.user.user.scope;
		// let hsoObj = this.user.user.currentHospital;
	  // this.currentHospital.id = hsoObj.hospitalId ? hsoObj.hospitalId.id : undefined;
	  // this.checkedHosDTO = scopeInfo.hospitalId || undefined;
	  // this.orderScopeRadio = scopeInfo.range + "";
	  // let groupIds = scopeInfo.groupIds || [];
	  // let dutyGroupList = scopeInfo.dutyGroupList || [];
	  // this.scopeGroups = dutyGroupList.concat(groupIds);
	  // if(this.scopeGroups.length){
	  //   this.typeId = this.scopeGroups[0].id;
	  // }
	  // this.hsmsData = {
	  //   checkedHos: this.currentHospital.id,
	  //   checkedHosDTO: this.checkedHosDTO,
	  //   scopeGroups: this.scopeGroups,
	  //   orderScopeRadio: this.orderScopeRadio || '0',
	  //   hsmsSwitch: scopeInfo.hsmsSwitch === 1,
	  // }
	  // this.flagList.hsmsFlag1 = this.hsmsData.hsmsSwitch;
	  // this.flagList.hsmsFlag2 = this.hsmsData.hsmsSwitch;
	  // this.flagList.hsmsFlag3 = this.hsmsData.hsmsSwitch;
	  // this.itsmCheckedHos = scopeInfo.dutyList || [];
	  // this.itsmOrderScopeRadio = scopeInfo.dutyRange + "";
	  // this.itsmScopeGroups = scopeInfo.dutyGroupList || [];
	  // this.itsmData = {
	  //   checkedHos: this.itsmCheckedHos,
	  //   scopeGroups: this.itsmScopeGroups,
	  //   orderScopeRadio: this.itsmOrderScopeRadio || '0',
	  //   mdv2Switch: scopeInfo.mdv2Switch === 1,
	  //   allDuty: scopeInfo.allDuty === undefined ? 1 : scopeInfo.allDuty,
			// showReassign: scopeInfo.showReassign == null || scopeInfo.showReassign == 0 ? 0 : 1,
	  // }
	  // this.flagList.itsmFlag1 = this.itsmData.mdv2Switch;
	  // this.flagList.itsmFlag2 = this.itsmData.mdv2Switch;
	  // this.flagList.itsmFlag3 = this.itsmData.mdv2Switch;
		this.showNewOrder();
	  this.getHospitalConfigList('allowNucleicAcidPrinting');
	  this.getConfigTasktype();
	  this.patientLogTasktype();
	}

	// 获取院区配置配置，是否核酸打印
	getHospitalConfigList(key) {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  let postData = { idx: 0, sum: 1, hospitalConfig: { hosId: this.currentHospital.id, 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;
	    }
	  });
	}

	// 获取配置文件写死的任务类型ID(送病人回病房9)，选择此任务类型的话，患者信息从终点科室获取
	getConfigTasktypeLoading: boolean = false;
	getConfigTasktype() {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  let postData = {
	    idx: 0,
	    sum: 1,
	    hospitalConfig: {
	      hosId: this.currentHospital.id,
	      key: "rebackPatientTypeId",
	    },
	  };
	  this.getConfigTasktypeLoading = true;
	  this.mainService.getFetchDataList("simple/data", "hospitalConfig", postData).subscribe(res => {
	    this.getConfigTasktypeLoading = false;
	      if (res && res.status == 200) {
	        this.deathTasktypeId = res.list.length ? res.list[0].value : undefined;
	      } else {
	        this.msg.error('请求数据失败');
	      }
	  });
	}
	// 获取配置文件写死的任务类型ID(转科，给转出院记录用6)
	patientLogTasktypeLoading: boolean = false;
	patientLogTasktype() {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  let postData = {
	    idx: 0,
	    sum: 1,
	    systemConfiguration: {
	      keyconfig: "transDeptTypeId",
	    },
	  };
	  this.patientLogTasktypeLoading = true;
	  this.mainService.getFetchDataList("simple/data", "systemConfiguration", postData).subscribe(res => {
	    this.patientLogTasktypeLoading = false;
	    if (res.status == 200) {
	      this.deathTasktypeIdPatient = res.list.length ? res.list[0].valueconfig : undefined;
	    } else {
	      this.msg.error('请求数据失败');
	    }
	  });
	}

	// 重置新建工单数据
	solutionId:any;
	resetOrderData(){
	  this.applicationRequesterList = [];
	  this.fileList = [];
	  this.repairImgs = [];
	  this.isRelatedDepartment = true;
	  this.solutionId = undefined;
	  delete this.incidentMsg.requesterPhone;
	}
	// 重置新建工单数据-继续建单-编辑-报修转事件
	resetOrderData2(){
	  this.fileList = [];
	  this.repairImgs = [];
	  if(this.incidentModel.repairIncidentType === 'public'){
	    this.isRelatedDepartment = false;
	  }else{
	    this.isRelatedDepartment = true;
	  }
	}

	// 获取院区配置配置，是否核酸打印
	currentRTab:any;
	rightTitle_tab:any = [];
	inspectToday:any;
	isShowNucleicAcidPrinting = false;
	deathTasktypeId; //获取这个写死的任务类型的id,送病人回病房
	deathTasktypeIdPatient; //获取这个写死的任务类型的id,转出院记录
	showNewOrder(des = '', phone = '', isInit = false, buildType = '') {
	  this.buildType = buildType;
		console.log(123,buildType)
	  // if(this.itsmData.mdv2Switch){
			console.log(456, this.itsmData)
	    if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
	      this.resetOrderData();
	    }else{
	      this.resetOrderData2();
	    }
	    this.searchApplicationHospital();
	    this.searchApplicationCategory();
	    this.searchApplicationPriority();
	    this.searchApplicationSource();
	    this.getRepairIncidentType();
	    isInit ? this.searchApplicationDepartment('itsm', undefined, undefined, undefined, true) : this.searchApplicationDepartment('itsm');
	    isInit && ((this.isRelatedDepartment && this.incidentModel.department) || (!this.isRelatedDepartment && this.incidentModel.hosId) || this.buildType === '报修转事件' ) && this.incidentModel.hosId && this.searchApplicationBuilding();
	    isInit && this.incidentModel.area && this.searchApplicationFloor();
	    if(!this.hsmsData.hsmsSwitch){
	      this.taskBuild = null;
	      this.residenceNo = null;
	      this.newOrderShow = true;
	      this.newOrderShowOpen = true;
	      this.fixedTab = "newOrder";
	      this.currentRTab = 0;
	      this.rightTitle_tab = [];
	      this.incidentModel = isInit ? this.incidentModel : { repairIncidentType: 'dept' };
	      this.incidentMsg = isInit ? this.incidentMsg : {};
	      this.isBuildOrderAgagin = false;
	      this.applyDept = null;
	      this.countRemarkIndex = -1;
	      this.incidentModel.department = isInit ? this.incidentModel.department : null;

	      //正常初始化
	      this.getAutoWorkTypes(false, isInit);
				this.newOrderShowOpen = true
	    }
	  // }

	  // 预约相关重置
	  this.yyDateZy = new Date();
	  this.yyDate = new Date();
	  this.yyTimeZy = null;
	  this.yyTime = null;
	  this.isYyInspect = false;
	  this.clickYYZyFlag = false;
	  this.clickYYFlag = false;
	  this.inspectToday = new Date();

	//   if(!isInit && this.hsmsData.hsmsSwitch){
	//     if(!this.deathTasktypeId){
	//       // 送病人回病房
	//       this.msg.error('【送病人回病房】未配置');
	//       return;
	//     }

	//     if(!this.deathTasktypeIdPatient){
	//       // 转出院记录
	//       this.msg.error('【转出院记录】未配置');
	//       return;
	//     }
	//   }

	  this.taskBuild = null;
	  this.residenceNo = null;
	  this.newOrderShow = true;
	  this.newOrderShowOpen = true;
	  this.fixedTab = "newOrder";
	  this.currentRTab = 0;
	  this.rightTitle_tab = [];
	  this.incidentModel = isInit ? this.incidentModel : { repairIncidentType: 'dept' };
	  this.incidentMsg = isInit ? this.incidentMsg : {};
	  this.isBuildOrderAgagin = false;
	  this.applyDept = null;
	  this.countRemarkIndex = -1;
	  this.incidentModel.department = isInit ? this.incidentModel.department : null;
	  console.log(des);
	  if (des === "no") {
	    //没绑定科室
	    this.searchApplicationDepartment("hsms", "", phone);
	    this.noWorkerPhone = false;
	  } else if (des === "yes") {
	    //绑定了科室
	    this.searchApplicationDepartment("hsms", "&ks&");
	    this.noWorkerPhone = false;
	  } else if (des === "&go&") {
	    //继续建单
	    this.searchApplicationDepartment("hsms", "&go&");
	    this.noWorkerPhone = false;
	  } else {
	    //正常初始化
	    this.searchApplicationDepartment("hsms");
	    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 + "_" + item.associationTypeValue;
	      });
	      // if(phone){
	      //   this.getAutoWorkTypes(true, isInit);
	      // }else{
	      //   this.getAutoWorkTypes(false, isInit);
	      // }
	      this.getAutoWorkTypes(false, isInit);
	    }
	  });
	}
	// 获取可选择的任务类型列表
	searchTaskList;
	searchTaskLoading = false;
	getSearchTaskList(keyword, countRemark = '') {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  this.searchTaskLoading = true;
	  return this.mainService.getTaskTypeBySearchKey({
	    searchKey: keyword || undefined,
	    countRemark: countRemark || undefined,
	    hosId: this.currentHospital.id,
	  });
	}

	rightTitleHandler(i) {
	  this.currentRTab = i;
	  if (i === 0) {
	    this.getWorkOrders(this.applyDept);
	  } else if (i === 1) {
	    this.getPatientLog(this.applyDept);
	  } else if (i === 2) {
	    this.getItsmOrders(this.incidentModel.department);
	  } else if (i === 3) {
	    this.getDictionaryList();
	  }
	}
	patientLogList:any;
	loading5:boolean = false
	getPatientLog(id) {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  if (id == -1 || id === null || id === undefined) {
	    this.patientLogList = [];
	    return;
	  }
	  let postData = {
	    patientLog: {
	      sqDept: { id },
	      hosId: this.currentHospital.id,
	    },
	    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;
	      }
	    });
	}
	// 服务台新建工单—根据申请科室id来查询未到达工单(科室id)
	loading4 = false;
	getWorkOrders(id) {
	  // if(!this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  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: null,
	      // serGdState: 4,
	      range: "0",
	      platform: 3,
	      searchDays: 100,
				createDept: this.applyDept
	      // 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;
	      }
	    });
	}
	// 服务台新建工单—根据申请科室id来查询
	loading6 = false;
	itsmOrders:any[] = [];
	getItsmOrders(id) {
	  // if(!this.itsmData.mdv2Switch){
	  //   return;
	  // }
	  if ((id == -1 || id === null || id === undefined ) && this.incidentModel.repairIncidentType === 'dept') {
	    this.itsmOrders = [];
	    return;
	  }
	  if(!this.incidentModel.department && this.incidentModel.repairIncidentType === 'dept'){
	  	this.itsmOrders = [];
	  	return;
	  }
	  let postData = {
	    incident: {
	      "deleteFlag": 0,
	      queryTask: 'all',
	      department: {
	        id,
	      },
	  		requester:{
	  			id:null
	  		}
	    },
	    idx: 0,
	    sum: 6,
	  };
	  if(this.incidentModel.repairIncidentType === 'public'){
	  	if(!this.incidentModel.requester){
	  		this.itsmOrders = [];
	  		return
	  	}
	  	postData.incident.requester.id = this.incidentModel.requester || null
			delete postData.incident.department
		}else{
	  	delete postData.incident.requester
	  }
	  this.loading6 = true;
	  this.mainService
	    .getFetchDataList("simple/data", "incident", postData)
	    .subscribe((data) => {
	      this.loading6 = false;
	      if (data.status == 200) {
	        this.itsmOrders = data.list;
	      }
	    });
	}
	//获取知识库状态/类型
	getDictionaryList() {
	  let solutionStatus$ = this.mainService.getDictionary('list', 'solution_status', true);
	  let solutionType$ = this.mainService.getDictionary('list', 'solution_type', true);
	  forkJoin(solutionStatus$, solutionType$).subscribe((data:any[]) => {
	    let solutionStatusList = data[0] || [];
	    let solutionTypeList = data[1] || [];

	    this.solutionStatus = solutionStatusList.find(item => item.value == 3);
	    	console.log('this.solutionStatus:', this.solutionStatus)
	    this.solutionType = solutionTypeList.find(item => item.value == 1);
	    	console.log('this.solutionType:', this.solutionType)

	    this.getKnowageList();
	  })
	}
	solutionStatus;//知识库状态
	solutionType;//知识库类型
	// 服务台新建工单—知识库
	loading7 = false;
	knowageList:any[] = [];
	getKnowageList() {
	  // if(!this.itsmData.mdv2Switch){
	  //   return;
	  // }

	  if(!(this.incidentModel.category && this.solutionStatus && this.solutionType)){
	    this.loading7 = false;
	    this.knowageList = [];
	    return;
	  }
	  this.loading7 = true;
	  let postData:any = {
	    idx: 0,
	    sum: 9999,
	    solution: {
	      categoryId: this.incidentModel.category,
				status: this.solutionStatus,
				type: this.solutionType,
	    },
	  };

	  this.mainService
	    .getFetchDataList('simple/data', 'solution', postData)
	    .subscribe((result) => {
	      this.loading7 = false;
	      if(result.status == 200){
	        this.knowageList = result.list || [];
	      }else{
	        this.msg.error(result.msg || '请求数据失败！');
	      }
	    });
	}
	
	// 引入知识库
	importKnowage(item){
	  console.log(item)
	  this.incidentModel = {...this.incidentModel, description:  `引用知识库解决，知识库编号：${item.solutionNumber}`};
	  this.solutionId = item.id;
	}
	// 知识库查看-知道了
	isShowKnowledge:boolean = false;
	showKnowledgeModal(data) {
	  this.coopData = data || {};
	  this.isShowKnowledge = true;
	}
	
	cancelKnowledgeModal(flag) {
	  this.isShowKnowledge = false;
	}
	
	// 获取患者信息
	searchPatientList(id, searchWords) {
	  this.searchPatientListSubject.next([id, searchWords]);
	}
	// 获取患者信息
	isLoadingPatient: boolean = false;
	getPatientList(id, searchWords, patient?) {
	  if(patient){
	    this.patientList = [patient];
	    return;
	  }
	  if(!id){
	    this.patientList = [];
	    return;
	  }
	  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);
	      // }
	    }
	  });
	}

	// 根据住院号获取患者信息
	getPatientByResidenceNo(residenceNo) {
	  let postData = {
	    residenceNo,
	    hosId: this.currentHospital.id,
	    idx: 0,
	    sum: 2,
	  };
	  this.mainService.listMsgByMain('listPatient',postData).subscribe((result) => {
	    if (result["status"] == 200) {
	      let patientList = result["list"];
	      if (patientList.length) {
	        patientList = patientList.filter((item) => !!item.bedNum);
	      }
	      if(patientList.length === 1){
	        let patient = patientList[0];
	        patient.bednum = patient.bedNum;
	        patient.patientname = patient.patientName;
	        patient.department && (this.applicationDepartmentList = [patient.department]);
	        patient.department && (this.applyDept = patient.department.id);
	        // patient.department && (this.patientList = [patient]);
	        patient.department && (this.patientZy = patient.patientCode);
	        console.log(this.patientList)
	      }else{
	        this.msg.warning('未查询到患者');
	      }
	    }
	  });
	}

	// tab任务类型向左移动
	elementView:any;
	toLeft() {
	  let maxStep = 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(type, e) {
	  this.changeInpSubject.next([type, e]);
	}
	changeCommonInp(type, e) {
	  this.changeCommonInpSubject.next([type, e]);
	}
	// 院区列表
	applicationHospitalList:any[] = [];
	searchApplicationHospital() {
		this.applicationHospitalList = this.tool.getHospitalList().filter(i=> !i.parent && !i.type);
		this.incidentModel.hosId = this.currentHospital.id;
	  // let dataObj = {
	  //   idx: 0,
	  //   sum: 9999,
	  //   hospital: {
	  //     selectType:'level1',
	  //   },
	  // };
	  // this.isLoading = true;
	  // this.mainService
	  //   .getFetchDataList("data", "hospital", dataObj)
	  //   .subscribe((data) => {
	  //     this.isLoading = false;
	  //     if (data.status == 200) {
	  //       this.applicationHospitalList = data.list;
			// 		this.incidentModel.hosId = this.currentHospital.id;
	  //     }
	  //   });
	}
	// 选择院区
	changeApplyHospital(e){
	  console.log(e);

	//   this.incidentModel.department = undefined;
	  this.searchApplicationDepartment('itsm');
		if(this.cmdbRepair){
			this.incidentModel.assetId = null;
			this.getAssetData()
		}
	  if(this.buildType !== '报修转事件'){
	    this.incidentModel.requester = undefined;
	    this.searchApplicationRequester();
	  }
	  this.applicationRequesterList = [];

	  this.incidentModel.area = undefined;
	  this.searchApplicationBuilding();

	  this.incidentModel.place = undefined;
	  this.applicationFloorList = [];

	  this.incidentModel.houseNumber = undefined;
	  this.incidentModel.duty = undefined;

	  // 根据院区和故障现象带出责任部门，优先级，维修人/组
	  if(this.incidentModel.category && e && this.buildType !== '编辑事件'){
	    let postData = {
	      idx: 0,
	      sum: 9999,
	      incidentCategoryConfig: {
	        categoryId: this.incidentModel.category,
	        hosId: e,
	      },
	    };
	    console.log(postData);
	    // return;
	    this.isLoading = true;
	    this.mainService
	      .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
	      .subscribe((data) => {
	        this.isLoading = false;
	        if (data.status == 200) {
	          let list = data.list || [];
	          if(list.length > 0){
	            console.log(list[0]);
	            this.incidentCategoryConfig = list[0];
	          }else{
	            this.incidentCategoryConfig = {};
	          }

	          // 根据院区和故障现象带出责任部门，优先级，维修人/组
	          this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
	          this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

	          // 回显维修人/组
	          this.showGroupOrUser();
	        }
	      });
	  }else{
	    this.incidentModel.group = undefined;
	    this.applicationGroupList = [];
	    this.incidentModel.user = undefined;
	    this.applicationUserList = [];
	  }
	}
	// 申请人列表（搜索）
	applicationRequesterList:any[] = [];
	isRelatedDepartment:boolean = true;
	searchApplicationRequester(keyWord?) {
	  // 关联查询，且没选择申请科室
	  if(this.isRelatedDepartment && !this.incidentModel.department){
	    this.applicationRequesterList = [];
	    return;
	  }
	  // 不关联查询，且没选择院区
	  if(!this.isRelatedDepartment && !this.incidentModel.hosId){
	    this.applicationRequesterList = [];
	    return;
	  }
	  let postData = {
	    idx: 0,
	    sum: 20,
	    user: {
				statisticalHosId: this.isRelatedDepartment ? undefined :  this.incidentModel.hosId,
	      // hospital: this.isRelatedDepartment ? undefined : { id: this.incidentModel.hosId },
	      dept: this.isRelatedDepartment ? { id: this.incidentModel.department } : undefined,
	      name: keyWord,
	      // simpleQuery: true,
	    },
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "user", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationRequesterList = data.list;
	      }
	    });
	}
	// 修改申请人
	changeApplyRequester(e){
	  console.log(e)
	  let userObj = this.applicationRequesterList.find(v => v.id == e);
	  // 选择申请人回显申请人电话
	  if(userObj){
	    this.incidentMsg.requesterPhone = userObj.phone;
	  }
		if(this.incidentModel.repairIncidentType === 'public'){
			this.getItsmOrders('')
			if(this.cmdbRepair){
				this.incidentModel.assetId = null;
				this.getAssetData()
			}
		}
	}
	// 故障现象列表
	applicationCategoryList:any[] = [];
	searchApplicationCategory(keyWord?) {
		let list = this.tool.getUserInfoPermission().dutyList
	  let dutyIds = list.map(i => {
			return i.id
		})
	  // if(this.buildType === '编辑事件'){
	  //   dutyIds = this.incidentModel.duty.id.toString();
	  // }else{
	  //   dutyIds = this.itsmData.checkedHos.length ? (this.itsmData.checkedHos.map(v => v.id).toString() || undefined) : undefined;
	  // }
	  let postData = {
	    category: {
				// hosId: this.currentHospital.id,
	      category: keyWord,
	      selectType: 'mutlQuery',
	      hierarchy: 3,//只差有三级的故障现象列表
	      dutyIds: dutyIds.toString(),
	    },
	  };
	  console.log(postData);
	  // return;
	  this.isLoading = true;
	  this.mainService
	    .incidentPost("listIncidentCategory", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationCategoryList = data.data;
	      }
	    });
	}
	// 修改故障现象
	incidentCategoryConfig:any = {};//当前匹配的故障现象规则
	changeApplyCategory(e, isCoverage = false){
	  console.log(e)
	  // 知识库
	  this.getKnowageList();
	  if(e && !isCoverage){
	    // 根据故障现象带出故障描述
	    if(this.incidentModel.description){
	      this.incidentModel.description = this.incidentModel.description + '；' + this.applicationCategoryList.find(v => v.id == e).mutiCategory;
	    }else{
	      this.incidentModel.description = this.applicationCategoryList.find(v => v.id == e).mutiCategory;
	    }
	  }
	  // 根据院区和故障现象带出责任部门，优先级，维修人/组
	  if(this.incidentModel.hosId && e && this.buildType !== '编辑事件'){
	    let postData = {
	      idx: 0,
	      sum: 9999,
	      incidentCategoryConfig: {
	        categoryId: e,
	        hosId: this.incidentModel.hosId,
	      },
	    };
	    console.log(postData);
	    // return;
	    this.isLoading = true;
	    this.mainService
	      .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
	      .subscribe((data) => {
	        this.isLoading = false;
	        if (data.status == 200) {
	          let list = data.list || [];
	          if(list.length > 0){
	            console.log(list[0]);
	            this.incidentCategoryConfig = list[0];
	          }else{
	            this.incidentCategoryConfig = {};
	          }

	          // 根据院区和故障现象带出责任部门，优先级，维修人/组
	          this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
	          this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

	          // 回显维修人/组
	          this.showGroupOrUser();
	        }
	      });
	  }else{
	    this.incidentModel.group = undefined;
	    this.applicationGroupList = [];
	    this.incidentModel.user = undefined;
	    this.applicationUserList = [];
	  }
	}

	// 直接解决-弹窗
	directOrderModalShow = false; //弹窗开关
	showDirectOrder() {
		console.log(669696)
	  this.directOrderModalShow = true;
	}
	// 关闭弹窗
	closeDirectOrderModelOrder(e) {
	  this.directOrderModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmDirectOrderModelOrder(incidentModel){
	  console.log(incidentModel);
	  this.maskFlag = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;
	  this.incidentModel = {...this.incidentModel, ...incidentModel};

	  let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
	  let postData:any = {
	    solutionId: this.solutionId,
			alarmId:null,
	    "incident": {
	      "id": this.incidentModel.id || undefined,
	      "deleteFlag": 0,
	      "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
	      "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
	      "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
	      "alarmType": false,
	      "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
	      "contactsInformation": this.incidentModel.contactsInformation,
	      "contacts": this.incidentModel.contacts,
	      "hosId": this.incidentModel.hosId || undefined,
	      "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
	      "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
	      "houseNumber": this.incidentModel.houseNumber,
	      "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
	      "priorityId": this.incidentModel.priorityId || undefined,
	      "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
	      // "title": category.mutiCategory,
	      "description": this.incidentModel.description,
	      "directProcess": 1,
	      "handleDescription": this.incidentModel.handleDescription,
	      "handlingPersonnelUser": {id: this.tool.getCurrentUserId()},
	      "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
	      "closecode": this.incidentModel.closecode ? { id: this.incidentModel.closecode } : undefined,
	      "acceptUser": { id: this.tool.getCurrentUserId() },
	      "callID": this.incidentModel.callID || undefined,
	      "incomingPhone": this.incidentModel.incomingPhone || undefined,
	      "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
				"assetId": this.incidentModel.assetId || undefined
	    },
	  };

	  if(this.buildType){
	    if(this.buildType === '报修转事件'){
	      postData.incident.fromWx = true;
	    }
	    if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
	      postData.incident = Object.assign({}, postData.incident);
	    }else{
	      postData.incident = Object.assign({}, this.editOrder, postData.incident);
	    }
	  }
		let url = null
		if(this.eventData){
			postData.alarmId = this.eventData.data.id
			url = this.mainService.addAlarmIncident(postData)
		}else{
			delete postData.alarmId
			url = this.mainService
	    .flowPost("incident/task/accept", postData)
		}
	  url.subscribe((result) => {
	      this.msg.remove(this.maskFlag);
	      this.maskFlag = false;

	      if (result.state == 200) {
	        // 图片上传
	        if(this.fileList.length){
	          console.log(this.fileList.map(v => v.originFileObj));
	          this.fileList.map(v => v.originFileObj).forEach(async file => {
	            await this.uploadImages(file, result.data.id);
	          })
	        }
	        this.directOrderModalShow = false;
	        // this.msg.success('直接解决成功');
	        this.isBuildOrderAgaginFn();
	      } else {
	        this.msg.error(result.msg || '直接解决失败');
	      }
	    });
	}

	// 回显维修人/组
	showGroupOrUser(){
	  // 先判断科室绑定人/组
	  if(this.incidentModel.department && this.incidentModel.category && this.incidentModel.duty){
	    let postData = {
	      idx: 0,
	      sum: 10,
	      incidentAssignManager: {
	        deptId: this.incidentModel.department,
	        categoryId: this.incidentModel.category,
	        hosId: this.incidentModel.duty.id,
	        operationType: 'queryConfig',
	      },
	    };

	    this.mainService
	      .getFetchDataList("simple/data", "incidentAssignManager", postData)
	      .subscribe((result) => {
	        if (result.status == 200) {
	          var deptBinduserConfig = result.list.length ? result.list[0] : null;//获取第一条配置
	          if(deptBinduserConfig){
	            console.log('deptBinduserConfig:', deptBinduserConfig)
	            // 如果有科室绑定人员的配置
	            if(deptBinduserConfig.handleGroupDTO){
	              this.incidentModel.group = deptBinduserConfig.handleGroupDTO.id;
	              this.applicationGroupList = [deptBinduserConfig.handleGroupDTO];
	            }else{
	              this.incidentModel.group = undefined;
	              this.applicationGroupList = [];
	            }

	            if(deptBinduserConfig.handleUserDTO){
	              this.incidentModel.user = deptBinduserConfig.handleUserDTO.id;
	              this.applicationUserList = [deptBinduserConfig.handleUserDTO];
	            }else{
	              this.incidentModel.user = undefined;
	              this.applicationUserList = [];
	            }
	          }else{
	            if(this.incidentModel.category){
	              // 选择了故障现象
	              if(this.incidentCategoryConfig.groupId && this.incidentCategoryConfig.groupDTO){
	                this.incidentModel.group = this.incidentCategoryConfig.groupId;
	                this.applicationGroupList = [this.incidentCategoryConfig.groupDTO];
	              }else{
	                this.incidentModel.group = undefined;
	                this.applicationGroupList = [];
	              }

	              if(this.incidentCategoryConfig.userId && this.incidentCategoryConfig.userDTO){
	                this.incidentModel.user = this.incidentCategoryConfig.userId;
	                this.applicationUserList = [this.incidentCategoryConfig.userDTO];
	              }else{
	                this.incidentModel.user = undefined;
	                this.applicationUserList = [];
	              }
	            }
	          }
	        }
	      });
	  }else{
	    if(this.incidentModel.category){
	      // 选择了故障现象
	      if(this.incidentCategoryConfig.groupId && this.incidentCategoryConfig.groupDTO){
	        this.incidentModel.group = this.incidentCategoryConfig.groupId;
	        this.applicationGroupList = [this.incidentCategoryConfig.groupDTO];
	      }else{
	        this.incidentModel.group = undefined;
	        this.applicationGroupList = [];
	      }

	      if(this.incidentCategoryConfig.userId && this.incidentCategoryConfig.userDTO){
	        this.incidentModel.user = this.incidentCategoryConfig.userId;
	        this.applicationUserList = [this.incidentCategoryConfig.userDTO];
	      }else{
	        this.incidentModel.user = undefined;
	        this.applicationUserList = [];
	      }
	    }
	  }
	}

	// 图片相关
	showUploadList = {
	  showPreviewIcon: true,
	  showRemoveIcon: true,
	  hidePreviewIconInNonImage: true
	};
	fileList = [
	  // {
	  //   uid: -1,
	  //   name: 'xxx.png',
	  //   status: '1',
	  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
	  // }
	];
	previewImage: string | undefined = '';
	previewVisible = false;

	handlePreview = (file: UploadFile) => {
		console.log('file1:', file)
	  this.previewImage = file.url || file.thumbUrl;
	  this.previewVisible = true;
	};

	beforeUpload = (file: UploadFile): boolean => {
		console.log('file2:', file)
	  this.fileList = [...this.fileList, file];
	  setTimeout(async () => {
	    file.url = await this.getBase64(file);
	  }, 0);
	  console.log('this.fileList:', this.fileList)
	  return true;
	};

	getBase64(file: any): Promise<any> {
	  return new Promise((resolve, reject) => {
	    const reader = new FileReader();
	    reader.readAsDataURL(file);
	    reader.onload = () => resolve(reader.result);
	    reader.onerror = error => reject(error);
	  });
	}

	// 临时上传图片
	temporarilyUrl = this.mainService.returnUploadUrl('temporarily', 0);
	// 处理组列表
	applicationGroupList:any[] = [];
	searchApplicationGroup(keyWord?) {
	  if(!this.incidentModel.duty){
	    this.incidentModel.group = undefined;
	    this.applicationGroupList = [];
	    this.incidentModel.user = undefined;
	    this.applicationUserList = [];
	    return;
	  }
	  let postData = {
	    idx: 0,
	    sum: 20,
	    group2: {
	      groupName: keyWord,
	      hospitals: this.incidentModel.duty ? this.incidentModel.duty.id.toString() : undefined,
	      type: 3,
	    },
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "group2", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationGroupList = data.list;
	      }
	    });
	}
	// 修改处理组
	changeApplyGroup(e){
	  console.log(e);
	  this.incidentModel.user = undefined;
	  this.searchApplicationUser();
	}
	// 处理人列表
	applicationUserList:any[] = [];
	searchApplicationUser(keyWord?) {
	  let postData = {
	    idx: 0,
	    sum: 20,
	    user: {
	      name:keyWord,
				groupdata: this.incidentModel.group ? { id: this.incidentModel.group } : undefined,
	      roleCodes: 'first-line support',
	      engineer: 1,
	      simpleQuery: true,
	    },
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "user", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationUserList = data.list;
	      }
	    });
	}
	// 优先级列表
	applicationPriorityList:any[] = [];
	searchApplicationPriority(keyWord?) {
	  let postData = {
	    idx: 0,
	    sum: 9999,
	    priority: {},
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "priority", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationPriorityList = data.list;
	        // 回显报修来源
	        // let source = this.applicationSourceList.find(v => v.value === 'phone');
	        // if(!this.incidentModel.source && source){
	        //   this.incidentModel.source = source.id;
	        // }
	      }
	    });
	}
	// 报修来源列表
	applicationSourceList:any[] = [];
	searchApplicationSource(keyWord?) {
	  this.mainService.getDictionary("list", "incident_source").subscribe((data) => {
	    this.applicationSourceList = data || [];
	  });
	}
	// 报修类型列表
	repairIncidentTypeList:any[] = [];
	getRepairIncidentType() {
	  this.mainService.getDictionary("list", "repair_incident_type").subscribe((data) => {
	    this.repairIncidentTypeList = data || [];
	  });
	}
	// 选择报修类型
	changeRepairIncidentType(value){
	  // this.incidentModel.department = undefined;
	  this.incidentMsg.deptManyPhone = '';
		this.incidentModel.requester = null;
	  this.isRelatedDepartment = value !== 'public';
	  this.changeApplyRelatedDepartment(this.isRelatedDepartment);
		this.rightTitleHandler(2);
	}
	// 楼栋列表
	applicationBuildingList:any[] = [];
	searchApplicationBuilding(keyWord?, buildingId?) {
	  let postData = {
	    idx: 0,
	    sum: 9999,
	    building: {
	      cascadeHosId: this.incidentModel.hosId,
	    },
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "building", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationBuildingList = data.list;
	        if(buildingId){
	          let hasBuildingId = this.applicationBuildingList.some(v => v.id == buildingId);
	          if(hasBuildingId){
	            this.incidentModel.area = buildingId;
	          }else{
	            this.incidentModel.area = undefined;
	          }
	        }
	      }
	    });
	}
	// 修改楼栋
	changeApplyBuilding(e){
	  console.log(e)
	  this.incidentModel.place = undefined;
	  this.searchApplicationFloor();
	}
	// 楼层列表
	applicationFloorList:any[] = [];
	searchApplicationFloor(keyWord?, floorId?, buildingId?) {
	  let postData = {
	    idx: 0,
	    sum: 9999,
	    floor: {
	      buildId: buildingId || this.incidentModel.area || undefined,
	      hosId: this.incidentModel.hosId,
	    },
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "floor", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationFloorList = data.list;
	        if(floorId){
	          let hasFloorId = this.applicationFloorList.some(v => v.id == floorId);
	          if(hasFloorId){
	            this.incidentModel.place = floorId;
	          }else{
	            this.incidentModel.place = undefined;
	          }
	        }
	      }
	    });
	}
	// 修改关联查
	changeApplyRelatedDepartment(e){
	  if(this.buildType !== '报修转事件'){
	    this.incidentModel.requester = undefined;
	  }
	  this.searchApplicationRequester();
	}
	// 申请科室列表（搜索）
	isLoadingApply: boolean = false;
	applicationDeptList:any[] = [];
	applyStartDept:any;
	searchApplicationDepartment(type, e?, phone?, deptId?, isInit?) {
	  // if(!this.hsmsData.hsmsSwitch && !this.itsmData.mdv2Switch){
	  //   return;
	  // }
	  let keyWord = "";
	  if (e && e !== "&ks&" && e !== "&go&") {
	    keyWord = e;
	  }
	  let cascadeHosId;
	  if(type == 'itsm'){
	    cascadeHosId = this.incidentModel.hosId || undefined;
	  }else{
	    cascadeHosId = this.currentHospital.id;
	  }
	  let dataObj = {
	    idx: 0,
	    sum: 20,
	    department: {
	      searchType: type == 'itsm' ? undefined : 1,// 简单查询
	      cascadeHosId,
	      keyWord: keyWord,
	      flag: 1,
	    },
	  };
	  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) {
	        if(type == 'hsms'){
	          this.applicationDepartmentList = data.list;
	          deptId && this.changeApply(deptId);
	          if (e === undefined) {
	            //初始化
	            this.changeApplicationDepartment();
	          } else if (e === "&ks&") {
	            //绑定了科室
	            // 配送--start
	            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&");
	            // 配送--end
	          } 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);
	          }
	        }else if(type == 'itsm'){
						if(this.eventData){
							this.applicationRequesterList.push({
								name: this.userInfo.user.name,
								id: this.userInfo.user.id,
								account: this.userInfo.user.account
							})
							this.incidentModel.requester = this.userInfo.user.id;
							let id = this.eventData.data.alarmId?this.eventData.data.alarmId:''
							let ly = this.eventData.data.alarmSource?this.eventData.data.alarmSource:''
							let dd = this.eventData.data.alarmLocation?this.eventData.data.alarmLocation:''
							let jjd = this.eventData.data.alarmUrgency?this.eventData.data.alarmUrgency.name:''
							let time = this.eventData.data.alarmActiveTime?format(new Date(this.eventData.data.alarmActiveTime), 'yyyy-MM-dd HH:mm:ss'):''
							let ip = this.eventData.data.alarmIp?this.eventData.data.alarmIp:''
							let ms = this.eventData.data.alarmDescription?this.eventData.data.alarmDescription:''
							let content = this.eventData.data.alarmContent?this.eventData.data.alarmContent:''
							this.incidentModel.description =
							'告警id：' + id + ';' +
							'告警来源：' + ly + ';' +
							'\n' +
							'告警地点：' + dd + ';' +
							'\n' +
							'紧急度：' + jjd + ';' +
							'告警时间：' + time + ';' +
							'\n' +
							'告警ip：' + ip + ';' +
							'\n' +
							'告警描述：' + ms + ';' +
							'\n' +
							'告警内容：' + content
						}
	          this.applicationDeptList = data.list;
	          let ids = this.applicationDeptList.map(v => v.id);
	          isInit && !ids.includes(this.incidentModel.department) && (this.applicationDeptList.unshift({id: this.incidentModel.department, dept: this.incidentMsg.deptName}))
	          console.log(this.applicationDeptList);
	          console.log(this.incidentModel);
	          console.log(this.incidentMsg);
	          deptId && this.changeApplyDept(deptId);
	        }
	      }
	    });
	}
	openChangeApply(flag){
	  flag && this.searchApplicationDepartment('hsms')
	}
	openChangeApplyDept(flag){
	  flag && this.searchApplicationDepartment('itsm');
	}
	openChangeApplyRequester(flag){
	  flag && this.searchApplicationRequester();
	}
	openChangeApplyCategory(flag){
	  flag && this.searchApplicationCategory();
	}
	openChangeApplyGroup(flag){
	  flag && this.searchApplicationGroup()
	}
	openChangeApplyUser(flag){
	  flag && this.searchApplicationUser()
	}
	// 配送-选择科室
	changeApply(e) {
	  console.log(e, this.applicationDepartmentList);
		if(this.cmdbRepair){
			this.incidentModel.assetId = null;
			this.getAssetData()
		}
	  this.changeApplicationDepartment("&same&");
	  if(this.applyDept && this.currentTabIndex !== '故障报修'){
	    this.rightTitle_tab = [
	      { id: 0, name: '近期配送' },
	      // { id: 1, name: '转出院记录' },
	    ]
	    this.rightTitleHandler(this.rightTitle_tab[0].id);
	  }

	  let deptObj = this.applicationDepartmentList.find(v => v.id == e);

	  if(this.incidentModel.department != e){
	    this.incidentModel.department = e;
	    this.searchApplicationDepartment('itsm', deptObj ? deptObj.dept : '', undefined, e);
	  }
	}
	// 运维-选择科室
	changeApplyDept(e) {
	  console.log(e, this.applicationDeptList);
		this.refresh();
	  if(this.incidentModel.department && this.currentTabIndex === '故障报修'){
			this.rightTitle_tab = [
	      { id: 2, name: '近期维修' },
	      { id: 3, name: '知识库' },
	    ]
	    this.rightTitleHandler(this.rightTitle_tab[0].id);
	  }

	  let deptObj = this.applicationDeptList.find(v => v.id == e);

	  if(this.applyDept != e){
	    this.applyDept = e;
	    this.searchApplicationDepartment('hsms', deptObj ? deptObj.dept : '', undefined, e);
	  }

	  // 选择科室回显一级院区
	  if(!this.incidentModel.hosId){
	    if(deptObj){
	      this.incidentModel.hosId = deptObj.hospital.parent ? deptObj.hospital.parent.id : deptObj.hospital.id;
	    }

	    this.incidentModel.area = undefined;
	    this.searchApplicationBuilding();

	    this.incidentModel.place = undefined;
	    this.applicationFloorList = [];
	  }

	  // 选择科室回显科室电话，楼栋，楼层，地址
	  if(deptObj){
	    console.log('deptObj:', deptObj)
	    this.incidentMsg.deptManyPhone = deptObj.manyPhone;
	    let buildingId = deptObj.building ? deptObj.building.id : undefined;
	    buildingId && this.searchApplicationBuilding('', buildingId);
	    let floorId = deptObj.floor ? deptObj.floor.id : undefined;
	    buildingId && floorId && this.searchApplicationFloor('', floorId, buildingId);
	    this.incidentModel.houseNumber = deptObj.address;
	  }

	  // 刷新申请人列表
	  if(this.buildType !== '报修转事件'){
	    this.incidentModel.requester = undefined;
	  }
	  this.searchApplicationRequester();

	  // 根据院区和故障现象带出责任部门，优先级，维修人/组
	  if(this.incidentModel.category && this.incidentModel.hosId && this.buildType !== '编辑事件'){
	    let postData = {
	      idx: 0,
	      sum: 9999,
	      incidentCategoryConfig: {
	        categoryId: this.incidentModel.category,
	        hosId: this.incidentModel.hosId,
	      },
	    };
	    console.log(postData);
	    // return;
	    this.isLoading = true;
	    this.mainService
	      .getFetchDataList("simple/data", "incidentCategoryConfig", postData)
	      .subscribe((data) => {
	        this.isLoading = false;
	        if (data.status == 200) {
	          let list = data.list || [];
	          if(list.length > 0){
	            console.log(list[0]);
	            this.incidentCategoryConfig = list[0];
	          }else{
	            this.incidentCategoryConfig = {};
	          }

	          // 根据院区和故障现象带出责任部门，优先级，维修人/组
	          this.incidentModel.duty = this.incidentCategoryConfig.dutyDTO;
	          this.incidentModel.priorityId = this.incidentCategoryConfig.priority;

	          // 回显维修人/组
	          this.showGroupOrUser();
	        }
	      });
	  }else{
	    // 回显维修人/组
	    this.showGroupOrUser();
	  }
	}
	// 申请科室列表（搜索）失去焦点的时候
	changeApplicationDepartment(phone?) {
	  this.radioValueQt = null;
	  this.startDeptQt = null;
	  this.endDeptQt = null;
	  this.radioValueZy = null;
	  this.radioValueZyPre = null;
	  this.startDeptZy = null;
	  this.endDeptZy = null;
	  this.patientZy = null;
	  this.goodsNow = [];
	  this.workOrderInspectScore = undefined;
	  // this.patientList = [];
	  this.workOrderRemark = "";
	  this.workOrderRemarkZy = "";
	  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.incidentModel.incomingPhone = this.callNumber = this.incidentModel.contactsInformation = phone;
	    this.applyDept = null;
	    this.noArrives = []; //近期配送
	  } else if (phone === "&ks&") {
	    let filter = this.applicationDepartmentList.filter(
	      (item) => item.id == this.applyDept
	    );
	    console.log('filter', filter)
	    // this.incidentModel.incomingPhone = this.callNumber = this.incidentModel.contactsInformation = filter[0].phone;
	    console.log(this.callNumber); //ceshi
	    if (this.currentTabIndex == "患者转运") {
	      //患者转运
	      //获取患者信息
	      this.getPatientList(this.applyDept, "");
	    }
	    if (this.currentRTab === 0) {
	      this.getWorkOrders(this.applyDept);
	    } else if (this.currentRTab === 1) {
	      this.getPatientLog(this.applyDept);
	    } else if (this.currentRTab === 2) {
	      this.getItsmOrders(this.incidentModel.department);
	    } else if (this.currentRTab === 3) {
	      this.getDictionaryList();
	    }
	  } else if (phone === "&go&") {
	    if (this.currentTabIndex == "患者转运") {
	      //患者转运
	      //获取患者信息
	      this.getPatientList(this.applyDept, "");
	    }
	    if (this.currentRTab === 0) {
	      this.getWorkOrders(this.applyDept);
	    } else if (this.currentRTab === 1) {
	      this.getPatientLog(this.applyDept);
	    } else if (this.currentRTab === 2) {
	      this.getItsmOrders(this.incidentModel.department);
	    } else if (this.currentRTab === 3) {
	      this.getDictionaryList();
	    }
	  } else if (phone === "&same&") {
	    if (this.currentTabIndex == "患者转运") {
	      //患者转运
	      //获取患者信息
	      this.getPatientList(this.applyDept, "");
	    }
	    if (this.currentRTab === 0) {
	      this.getWorkOrders(this.applyDept);
	    } else if (this.currentRTab === 1) {
	      this.getPatientLog(this.applyDept);
	    } else if (this.currentRTab === 2) {
	      this.getItsmOrders(this.incidentModel.department);
	    } else if (this.currentRTab === 3) {
	      this.getDictionaryList();
	    }
	  }
	}

	// 引入电话号码
	importPhone(phone, isTransform){
	  if(isTransform){
	    this.incidentModel.contactsInformation = phone.split(',')[0];
	  }else{
	    this.incidentModel.contactsInformation = phone;
	  }
	}

	// 是否连续建单
	isBuildOrderAgagin:boolean = false;
	maskFlag:any = false;
	// 运维-直接解决
	directOrder(){
	  if(this.publicRepair && this.applicantMustFillIn==1 && !this.incidentModel.requester){
	    this.msg.warning('请选择申请人!');
	    return;
	  }

	  if(!this.incidentModel.category){
	    this.msg.warning('请选择故障现象!');
	    return;
	  }

	  let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
	  if(!this.incidentModel.duty){
	    this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
	    return;
	  }

	  if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
	    this.msg.warning('请选择申请科室!');
	    return;
	  }

	  if(!this.incidentModel.contactsInformation){
	    this.msg.warning('请填写联系电话!');
	    return;
	  }

	  if(!this.incidentModel.priorityId){
	    this.msg.warning('请选择优先级!');
	    return;
	  }

		if(!this.incidentModel.source){
		  this.msg.warning('请选择报修来源!');
		  return;
		}

	  if(!this.incidentModel.description){
	    this.msg.warning('请选择故障描述!');
	    return;
	  }
	  this.showDirectOrder();
	}
	// 图片上传
	uploadImages(file, id){
	  const formData = new FormData();
	  formData.append('file', file);
	  formData.append('fileName', file.name);
	  const req = new HttpRequest('Post', this.mainService.returnUploadUrl('wechatRequesterIncident', id), formData, {
	    reportProgress: true
	  });
	  return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).toPromise();
	}
	// 运维-建单并派单
	assignOrder(){
	  if(this.publicRepair && this.applicantMustFillIn==1 && !this.incidentModel.requester){
	    this.msg.warning('请选择申请人!');
	    return;
	  }

	  if(!this.incidentModel.category){
	    this.msg.warning('请选择故障现象!');
	    return;
	  }

	  let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
	  console.log('故障现象对象=>>>>>',category)
		if(!this.incidentModel.duty){
	    this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
	    return;
	  }

	  if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
	    this.msg.warning('请选择申请科室!');
	    return;
	  }

	  if(!this.incidentModel.contactsInformation){
	    this.msg.warning('请填写联系电话!');
	    return;
	  }

	  if(!this.incidentModel.priorityId){
	    this.msg.warning('请选择优先级!');
	    return;
	  }

		if(!this.incidentModel.source){
		  this.msg.warning('请选择报修来源!');
		  return;
		}

	  if(!this.incidentModel.description){
	    this.msg.warning('请选择故障描述!');
	    return;
	  }

	  if(!this.incidentModel.group && this.buildType !== '编辑事件'){
	    this.msg.warning('请选择处理组!');
	    return;
	  }

	  this.maskFlag = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;

	  let postData:any = {
	    solutionId: this.solutionId,
			alarmId:null,
	    "incident": {
	      "id": this.incidentModel.id || undefined,
	      "deleteFlag": 0,
	      "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
	      "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
	      "contactsInformation": this.incidentModel.contactsInformation,
	      "contacts": this.incidentModel.contacts,
	      "hosId": this.incidentModel.hosId || undefined,
	      "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
	      "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
	      "houseNumber": this.incidentModel.houseNumber,
	      "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
	      "priorityId": this.incidentModel.priorityId || undefined,
	      "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
	      // "title": category.mutiCategory,
	      "description": this.incidentModel.description,
	      "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
	      "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
	      "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
	      "acceptUser": { id: this.tool.getCurrentUserId() },
	      "callID": this.incidentModel.callID || undefined,
	      "incomingPhone": this.incidentModel.incomingPhone || undefined,
	      "candidateGroups": this.incidentModel.group || undefined,
	      "assignee": this.incidentModel.user || undefined,
	      "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
				"assetId": this.incidentModel.assetId || undefined
	    }
	  };
	  if(this.buildType){
	    if(this.buildType === '报修转事件'){
	      postData.incident.fromWx = true;
	    }
	    if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
	      postData.incident = Object.assign({}, postData.incident);
	    }else{
	      postData.incident = Object.assign({}, this.editOrder, postData.incident);
	    }
	  }
	  console.log('哈哈哈哈哈哈=====', this.eventData);
	  // return;
		let url = null
		if(this.eventData){
			postData.alarmId = this.eventData.data.id
			url = this.mainService.addAlarmIncident(postData)
		}else{
			delete postData.alarmId
			url = this.mainService
		  .flowPost("incident/task/accept", postData)
		}
		url.subscribe((result) => {
	      this.msg.remove(this.maskFlag);
	      this.maskFlag = false;

	      if (result.state == 200) {
	        // 图片上传
	        if(this.fileList.length){
	          console.log(this.fileList.map(v => v.originFileObj));
	          this.fileList.map(v => v.originFileObj).forEach(async file => {
	            await this.uploadImages(file, result.data.id);
	          })
	        }
	        // this.msg.success('建单并派单成功');
	        this.isBuildOrderAgaginFn();
	      } else {
	        this.msg.error(result.msg || '建单并派单失败');
	      }
	    });
	}

	// 运维-暂存
	temporaryStorage(){
	  this.maskFlag = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;

	  let category;
	  if(this.incidentModel.category){
	    category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
	  }

	  let postData:any = {
	    solutionId: this.solutionId,
	    "incident": {
	      "id": this.incidentModel.id || undefined,
	      "deleteFlag": 0,
	      "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
	      "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
	      "contactsInformation": this.incidentModel.contactsInformation,
	      "contacts": this.incidentModel.contacts,
	      "hosId": this.incidentModel.hosId || undefined,
	      "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
	      "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
	      "houseNumber": this.incidentModel.houseNumber,
	      "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
	      "priorityId": this.incidentModel.priorityId || undefined,
	      "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
	      // "title": category ? category.mutiCategory : '',
	      "description": this.incidentModel.description,
	      "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
	      "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
	      "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
	      "acceptUser": { id: this.tool.getCurrentUserId() },
	      "callID": this.incidentModel.callID || undefined,
	      "incomingPhone": this.incidentModel.incomingPhone || undefined,
	      "candidateGroups": this.incidentModel.group || undefined,
	      "assignee": this.incidentModel.user || undefined,
	      "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
	    }
	  };
	  if(this.buildType){
	    if(this.buildType === '报修转事件'){
	      postData.incident.fromWx = true;
	    }

	    if(this.buildType !== '继续建单' && this.buildType !== '编辑事件' && this.buildType !== '报修转事件'){
	      postData.incident = Object.assign({}, postData.incident);
	    }else{
	      postData.incident = Object.assign({}, this.editOrder, postData.incident);
	    }
	  }
	  console.log(postData);
	  // return;

	  this.mainService
	    .flowPost("incident/task/storage", postData)
	    .subscribe((result) => {
	      this.msg.remove(this.maskFlag);
	      this.maskFlag = false;

	      if (result.state == 200) {
	        // 图片上传
	        if(this.fileList.length){
	          console.log(this.fileList.map(v => v.originFileObj));
	          this.fileList.map(v => v.originFileObj).forEach(async file => {
	            await this.uploadImages(file, result.data.id);
	          })
	        }
	        // this.msg.success('暂存成功');
	        this.isBuildOrderAgaginFn();
	      } else {
	        this.msg.error(result.msg || '暂存失败');
	      }
	    });
	}

	// 运维-保存
	saveOrder(){
	  if(this.publicRepair && this.applicantMustFillIn==1 && !this.incidentModel.requester){
	    this.msg.warning('请选择申请人!');
	    return;
	  }

	  if(!this.incidentModel.category){
	    this.msg.warning('请选择故障现象!');
	    return;
	  }

	  let category = this.applicationCategoryList.find(v => v.id == this.incidentModel.category);
	  if(!this.incidentModel.duty){
	    this.msg.warning(`故障现象【${category.mutiCategory}】没有设置责任部门!`);
	    return;
	  }

	  if(this.incidentModel.repairIncidentType === 'dept' && !this.incidentModel.department){
	    this.msg.warning('请选择申请科室!');
	    return;
	  }

	  if(!this.incidentModel.contactsInformation){
	    this.msg.warning('请填写联系电话!');
	    return;
	  }

	  if(!this.incidentModel.priorityId){
	    this.msg.warning('请选择优先级!');
	    return;
	  }

		if(!this.incidentModel.source){
		  this.msg.warning('请选择报修来源!');
		  return;
		}

	  if(!this.incidentModel.description){
	    this.msg.warning('请选择故障描述!');
	    return;
	  }
	  this.maskFlag = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;

	  let postData:any = {
	    solutionId: this.solutionId,
	    "incident": {
	      "id": this.incidentModel.id || undefined,
	      "deleteFlag": 0,
	      "duty": this.incidentModel.duty ? { id: this.incidentModel.duty.id } : undefined,
	      "department": this.incidentModel.department ? { id: this.incidentModel.department } : undefined,
	      "contactsInformation": this.incidentModel.contactsInformation,
	      "contacts": this.incidentModel.contacts,
	      "hosId": this.incidentModel.hosId || undefined,
	      "area": this.incidentModel.area ? { id: this.incidentModel.area } : undefined,
	      "place": this.incidentModel.place ? { id: this.incidentModel.place } : undefined,
	      "houseNumber": this.incidentModel.houseNumber,
	      "category": this.incidentModel.category ? { id: this.incidentModel.category } : undefined,
	      "priorityId": this.incidentModel.priorityId || undefined,
	      "source": this.incidentModel.source ? { id: this.incidentModel.source } : undefined,
	      // "title": category ? category.mutiCategory : '',
	      "description": this.incidentModel.description,
	      "yyTime": this.incidentModel.yyTime ? format(new Date(this.incidentModel.yyTime), 'yyyy-MM-dd HH:mm:ss') : undefined,
	      "requester": this.incidentModel.requester ? { id: this.incidentModel.requester } : undefined,
	      "repairIncidentType": this.incidentModel.repairIncidentType ? this.repairIncidentTypeList.find(v => v.value === this.incidentModel.repairIncidentType) : undefined,
	      "acceptUser": { id: this.tool.getCurrentUserId() },
	      "callID": this.incidentModel.callID || undefined,
	      "incomingPhone": this.incidentModel.incomingPhone || undefined,
	      "hjzxRecordId": this.incidentModel.hjzxRecordId || undefined,
	    }
	  };
	  if(this.buildType){
	    postData.incident = Object.assign({}, this.editOrder, postData.incident);
	  }
	  console.log(postData);
	  // return;

	  this.mainService
	    .flowPost("incident/task/edit", postData)
	    .subscribe((result) => {
	      this.msg.remove(this.maskFlag);
	      this.maskFlag = false;

	      if (result.state == 200) {
	        // 图片上传
	        if(this.fileList.length){
	          console.log(this.fileList.map(v => v.originFileObj));
	          this.fileList.map(v => v.originFileObj).forEach(async file => {
	            await this.uploadImages(file, result.data.id);
	          })
	        }
	        // this.msg.success('编辑成功');
	        this.isBuildOrderAgaginFn();
	      } else {
	        this.msg.error(result.msg || '编辑失败');
	      }
	    });
	}

	// 是否连续建单
	isBuildOrderAgaginFn(){
	  if(this.isBuildOrderAgagin){
	    // 清除故障现象，维修人/组
	    this.incidentModel.category = undefined;
	    this.incidentModel.user = undefined;
	    this.incidentModel.group = undefined;
	    this.showPromptModal("操作", true, "", "");
	  }else{
			this.goType = null;
	    this.newOrderShow = false; //关闭弹窗
	    this.newOrderShowOpen = false; //此时可出现新的弹窗
	    this.showPromptModal("操作", true, "", "");
	  }
	}

	// 选择统计备注
	countRemarkIndex:number = -1;
	addCountRemark(countRemark, index, i){
	  if(this.countRemarkIndex == i){
	    this.countRemarkIndex = -1;
	  }else{
	    this.countRemarkIndex = i;
	  }

	  this.getSearchTaskList('', this.countRemarkIndex > -1 ? countRemark : '').subscribe((result) => {
	    if (result.status == 200) {
	      this.searchTaskLoading = false;
	      this.workTypes = result['data'] || [];
	      // 整理后的任务类型
	      this.isShowResidenceNo = false;
	      this.workTypesArrange[index].value = [];
	      // for (const value of this.workTypesArrange) {
	      //   value.value = [];
	      // }
	      this.workTypes.forEach((item) => {
	        if(item.associationTypeValue === 'patientTransport' || item.associationTypeValue === 'inspect'){
	          // // 患者其他服务
	          // let obj = this.workTypesArrange.find(v => v.key === '患者转运');
	          // if(obj){
	          //   obj.value.push(item);
	          // }else{
	          //   this.workTypesArrange.unshift({ key: '患者转运', value: [item] });
	          //   this.isShowResidenceNo = true;
	          // }
	        }else if(item.associationTypeValue === 'other' || item.associationTypeValue === 'specimen' || item.associationTypeValue === 'ordinary'){
	          // 物品配送
	          let obj = this.workTypesArrange.find(v => v.key === '物品配送');
	          if(obj){
	            obj.value.push(item);
	          }else{
	            this.workTypesArrange.unshift({ key: '物品配送', value: [item] });
	          }
	        }
	      });
	      console.log('workTypesArrange', this.workTypesArrange);
	      // 任务类型是否显示操作项
	      let arr = this.workTypesArrange;
	      this.workTypesFlag = arr.length >= 5;
	    }
	  });
	}

	// 新建工单->获取新建类型
	countRemarkList:any[] = [];
	isShowResidenceNo = false;
	getAutoWorkTypes(isFirst, isInit) {
	  this.workTypesArrange = [];
	  // 运维
	  // if(this.itsmData.mdv2Switch){
	    this.workTypesArrange = [{key:'故障报修', value: []}];
	    // if(!this.hsmsData.hsmsSwitch){
	    //   console.log('workTypesArrange', this.workTypesArrange);
	    //   // 是否显示操作项
	    //   this.workTypesFlag = this.workTypesArrange.length >= 5;
	    // }
	  // }
	}
	// 查类型
	getTaskTypeCountRemarkList(){
	  this.mainService.getTaskTypeCountRemarkList({
	      hosId: this.currentHospital.id,
	      typeValues: 'other,specimen,ordinary',
	  }).subscribe((data) => {
	    if (data["status"] == 200){
	      this.countRemarkList = data.data || [];
	    }
	  })
	}
	// 终点科室选中
	endDeptZyChange() {
	  if (!this.applyDept || !this.endDeptZy) {
	    return;
	  }
	  // 终点科室患者信息列表,id是送病人回病房的任务类型
	  if (this.radioValueZy == this.deathTasktypeId) {
	    //获取患者信息
	    this.patientZy = null;
	    this.getPatientList(this.endDeptZy, "");
	  }
	}
	//搜索院区下面的科室(患者转运)
	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) {
		  //固定科室范围，禁止搜索
			this.mainService.getdeptList(this.radioValueZy).subscribe((data:any) => {
				let arr = data;
				if(value!=''){
					data = arr.startDept.filter(i=>i.dept.indexOf(value) !=-1)
					this.deptZyList.startDept = data
				}else{
					this.deptZyList.startDept = arr.startDept
				}
			})
		  return;
		} else if (type === "end" && this.deptZyList["endStatus"] == 202) {
		  //固定科室范围，禁止搜索
			this.mainService.getdeptList(this.radioValueZy).subscribe((data:any) => {
				let arr = data;
				if(value!=''){
					data = arr.endDept.filter(i=>i.dept.indexOf(value) !=-1)
					this.deptZyList.endDept = data
				}else{
					this.deptZyList.endDept = arr.endDept
				}
			})
		  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) {
	    //固定科室范围，禁止搜索
			this.mainService.getdeptList(this.psValue).subscribe((data:any) => {
				let arr = data;
				if(value!=''){
					data = arr.startDept.filter(i=>i.dept.indexOf(value) !=-1)
					this.deptQtList.startDept = data
				}else{
					this.deptQtList.startDept = arr.startDept
				}
			})
	    return;
	  } else if (type === "end" && this.deptQtList["endStatus"] == 202) {
	    //固定科室范围，禁止搜索
			this.mainService.getdeptList(this.psValue).subscribe((data:any) => {
				let arr = data;
				if(value!=''){
					data = arr.endDept.filter(i=>i.dept.indexOf(value) !=-1)
					this.deptQtList.endDept = data
				}else{
					this.deptQtList.endDept = arr.endDept
				}
			})
	    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;
	        }
	      }
	    });
	}
	// 获取大于x，并且是n的倍数的数字
	getLgNumber(x: number, n:number): number{
	  for(let i = x; i < 60; i++){
	    if(i % n === 0){
	      return i;
	    }
	  }
	  return 0;
	}
	// 禁用小时
	disabledHours = (): number[] => {
	  let now = new Date();
	  let nHour = now.getHours();
	  let nMinute = now.getMinutes();
	  if (nMinute > (60 - this.inspectAndPatientTransportConfig.timeMod)) {
	    return range(0, nHour + 1);
	  } else {
	    return range(0, nHour);
	  }
	}
	// 禁用分钟
	disabledMinutes = (hour: number): number[] => {
	  let now = new Date();
	  let nHour = now.getHours();
	  let nMinute = now.getMinutes();
	  if (hour === nHour || hour === undefined) {
	    return this.integralDivision(0, nMinute, this.inspectAndPatientTransportConfig.timeMod);
	  } else {
	    return [];
	  }
	}

	// start和end之间能被n整除的所有数字集合
	integralDivision(start:number, end:number, n:number): number[]{
	  let arr = [];
	  for(let i = start; i <= end; i++){
	    if(i % n === 0){
	      arr.push(i);
	    }
	  }
	  return arr;
	}
	//修改预约建单时间的日期
	yyDateChange(e) {
	  // 获取年月日
	  let yyDate = new Date(e);
	  let year = yyDate.getFullYear();
	  let month = yyDate.getMonth();
	  let date = yyDate.getDate();
	  // 获取当前时间的年月日
	  let now = new Date();
	  let nYear = now.getFullYear();
	  let nMonth = now.getMonth();
	  let nDate = now.getDate();
	  if (year != nYear || month != nMonth || date != nDate) {
	    this.disabledHours = () => [];
	    this.disabledMinutes = (hour) => [];
	  } else {
	    // 禁用小时
	    this.disabledHours = () => {
	      let now = new Date();
	      let nHour = now.getHours();
	      let nMinute = now.getMinutes();
	      if (nMinute > (60 - this.inspectAndPatientTransportConfig.timeMod)) {
	        return range(0, nHour + 1);
	      } else {
	        return range(0, nHour);
	      }
	    };
	    // 禁用分钟
	    this.disabledMinutes = (hour) => {
	      let now = new Date();
	      let nHour = now.getHours();
	      let nMinute = now.getMinutes();
	      if (hour === nHour || hour === undefined) {
	        return this.integralDivision(0, nMinute, this.inspectAndPatientTransportConfig.timeMod);
	      } else {
	        return [];
	      }
	    };
	  }
	}
	// 下一日(患者其他服务)
	nextDayZy() {
	  this.yyDateZy = addDays(this.yyDateZy, 1);
	  this.yyDateChange(this.yyDateZy);
	}
	// 下一日(其他临床服务)
	nextDay() {
	  this.yyDate = addDays(this.yyDate, 1);
	  this.yyDateChange(this.yyDate);
	}
	// 禁用日期(患者其他服务)
	disabledyyDateZy = (current: Date): boolean => {
	  return differenceInCalendarDays(current, new Date()) < 0;
	};
	// 禁用日期(其他)
	disabledyyDate = (current: Date): boolean => {
	  return differenceInCalendarDays(current, new Date()) < 0;
	};
	yyTimeZyChange(e) {
	  if (this.yyTimeZy) {
	    let now = new Date();
	    // 禁用日期(转运)
	    if (getHours(this.yyTimeZy) < getHours(now)) {
	      this.disabledyyDateZy = (current: Date): boolean => {
	        return differenceInCalendarDays(current, new Date()) < 1;
	      };
	    } else {
	      this.disabledyyDateZy = (current: Date): boolean => {
	        return differenceInCalendarDays(current, new Date()) < 0;
	      };
	    }
	    let end = this.getLgNumber(getMinutes(this.yyTimeZy), this.inspectAndPatientTransportConfig.timeMod);
	    this.yyTimeZy = setMinutes(this.yyTimeZy, end);
	  }
	  this.clickYYZyFlag = false;
	}
	yyTimeChange(e) {
	  if (this.yyTime) {
	    let now = new Date();
	    // 禁用日期(其他)
	    if (getHours(this.yyTime) < getHours(now)) {
	      this.disabledyyDate = (current: Date): boolean => {
	        return differenceInCalendarDays(current, new Date()) < 1;
	      };
	    } else {
	      this.disabledyyDate = (current: Date): boolean => {
	        return differenceInCalendarDays(current, new Date()) < 0;
	      };
	    }
	    let end = this.getLgNumber(getMinutes(this.yyTime), this.inspectAndPatientTransportConfig.timeMod);
	    this.yyTime = setMinutes(this.yyTime, end);
	  }
	  this.clickYYFlag = false;
	}
	// 需要预约建单-事件
	yyInspectChange(e) {
	  if (this.currentTasktype.associationType.value === "other") {
	    //其他临床服务
	    this.yyTime = null;
	    this.yyDate = new Date();
	    console.log(this.isYyInspect);
	  } else if (this.currentTasktype.associationType.value === "patientTransport") {
	    //患者其他服务
	    this.yyTimeZy = null;
	    this.yyDateZy = new Date();
	  }else if (this.currentTasktype.associationType.value === "inspect") {
	    //陪检
	    let obj = this.filterLinkCheckLis.find((item) => {
	      return (parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime() - new Date().getTime() > 0);
	    });
	    if (obj) {
	      this.showDateTime();
	    } else {
	      this.yyTimeZy = null;
	      this.yyDateZy = new Date();
	      console.log(this.isYyInspect);
	    }
	  }
	}
	//回显时间日期
	showDateTime() {
	  //当前时间要大于生效时间
	  let isYyInspect = this.filterLinkCheckLis.every((item) => {
	    return (parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime() - new Date().getTime() > 0);
	  });
	  //如果勾选需要预约检查
	  if (isYyInspect) {
	    //筛选离当前时间最近的
	    let timeList = this.filterLinkCheckLis
	      .map((item) => parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime())
	      .sort();
	    this.yyTimeZy = new Date(timeList[0] - 0); //回显预约时间,需要减去生效时间
	    this.yyDateZy = new Date(timeList[0] - 0); //回显预约日期,需要减去生效时间
	    this.yyDateChange(this.yyTimeZy);
	  } else {
	    this.yyTimeZy = null;
	    this.yyDateZy = null;
	  }
	}
	// 患者送检检查项目-选择检查项目
	linkCheckLisTrue = false; //是否有已选择(患者)
	filterLinkCheckLis = []; //有预约时间并且选中的
	isInspects = false; //勾选检车的时候是否多个检查多个检查科室
	linkCheckLisChange(e) {
	  let flag = false; //检查是否紧急
	  let arr = []; //选中的索引
	  // 是否检查生成工单允许多个科室，1是，0否
	  if (this.currentTasktype.isMoreDept === 0) {
	    let arr = e.map((item) => item.execDeptId);
	    arr = Array.from(new Set(arr));
	    this.isInspects = arr.length > 1;
	  }
	  this.linkCheckLis.forEach((item, index) => {
	    if (e.length) {
	      //有选中的检查
	      e.forEach((v) => {
	        //检查是否有紧急度
	        if (v.priority == 1) {
	          flag = true;
	        }
	        //选中的检查设置checked
	        if (v.value == item.value) {
	          arr.push(index);
	        }
	      });
	    } else {
	      item.checked = false;
	    }
	  });
	  this.linkCheckLis.forEach((item, index) => {
	    item.checked = arr.includes(index);
	  });
	  console.log(e, this.linkCheckLis);
	  this.clickYYFlag = false;
	  // 有预约时间并且选中的
	  this.filterLinkCheckLis = this.linkCheckLis.filter(
	    (item) => Boolean(item.yyTime) && item.checked
	  );
	  //有预约时间并且选中的检查数组不为空
	  if (this.filterLinkCheckLis.length) {
	    //当前时间要大于生效时间
	    this.isYyInspect = this.filterLinkCheckLis.every((item) => {
	      return (parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime() - new Date().getTime() > 0);
	    });
	    //不加急状态下，回显时间
	    this.showDateTime();
	  } else {
	    //有预约时间并且选中的检查数组为空
	    this.isYyInspect = false;
	    this.yyTimeZy = null;
	    this.yyDateZy = null;
	  }
	  this.linkCheckLisTrue = e.length > 0;
	}
	// 转运类型选中类型（单选）触发
	yyDateZy = null; //预约日期-患者其他服务
	yyDate = null; //预约日期-其他临床服务
	yyTimeZy = null; //预约时间-患者其他服务
	yyTime = null; //预约时间-其他临床服务
	inspectAndPatientTransportConfig:any = {timeMod: 30};
	isYyInspect = false; //需要预约检查
	clickYYZyFlag = false; //是否点击预约建单-患者其他服务
	clickYYFlag = false; //是否点击预约建单-其他临床服务
	currentTasktype = null; //当前选中的任务类型对象
	isTaskTypeInspect:boolean = false;//是否是患者陪检
	linkCheckLis:any[] = [];//检查列表
	tabIndex;
	isStartFixedType:boolean = false;
	isEndFixedType:boolean = false;
	//获取携带设备
	goodsNow; //携带的物品列表
	getAllGoods() {
	  this.mainService.getDictionary("list", "goods").subscribe((data) => {
	    let goodsNow = data || [];
	    this.goodsNow = [];
	    goodsNow.forEach((e) => {
	      this.goodsNow.push({
	        label: e.name,
	        value: e.id,
	        checked: false,
	      });
	    });
	  });
	}

	//获取陪检方式
	workOrderInspectScoreList:any[] = [];
	workOrderInspectScore:any;
	getWorkOrderInspectScore() {
	  let postData = { idx: 0, sum: 9999, workOrderInspectScore: { hosId: this.currentHospital.id } };
	  this.mainService
	    .getFetchDataList("simple/data", "workOrderInspectScore", postData)
	    .subscribe((result) => {
	      if (result.status == 200) {
	        this.workOrderInspectScoreList = result.list || [];
	      } else {
	        this.msg.error("请求数据失败");
	      }
	    });
	}

	psValue:any;
	taskType:any;
	radioChangeQt(value) {
	  //任务类型id
	  if (value === "" || value === null) {
	    return;
	  }
		let index = this.tabIndex;
		// let item = this.workTypesArrange[1].value.find(v => v.id == value);
		// console.log(788787,item)
		// this.taskType = item.associationTypeValue?item.associationTypeValue:null
		this.psValue = value
	  this.startDeptQt = null;
	  this.endDeptQt = null;
	  // 返回值的status是201 则是默认发起科室，把申请科室作为值
	  // 返回值的status是202 则是固定科室范围，会返回科室列表
	  // 返回值的status是203 则是固定科室，会返回单个科室
	  // 返回值的status是204 则让前端自己调用科室搜索接口
	  // 返回值的status是205 则是固定科室类型，会返回科室列表
	  this.mainService.getdeptList(value).subscribe((data:any) => {
	    this.deptQtList = data;
			if(data.startStatus==202 || data.startStatus==204 || data.startStatus==205){
				this.isStartFixedType = true
			}else{
				this.isStartFixedType = false
			}
			if(data.endStatus==202 || data.endStatus==204 || data.endStatus==205){
				this.isEndFixedType = true
			}else{
				this.isEndFixedType = false
			}
	    // 预约start
	    this.currentTasktype = data.taskType;
	    this.isYyInspect = false;
	    this.clickYYFlag = false;
	    this.yyDate = new Date();
	    this.yyTime = null;
	    // 预约end
	    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.currentHospital.id, "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.currentHospital.id, "end", "");
	    }
	  });
	}

	//新建工单->确定提交
	isGoLoading = false;
	goType:any;

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

	// 取消
	newOrderCancel(): void {
	  this.newOrderShow = false;
	  this.newOrderShowOpen = false;
	  // this.currentTabIndex = "";
	  this.fixedTab = "";
	  this.fixedMenuShangla();
		this.goType = null;
	  this.radioValueQt = null;
	  this.startDeptQt = null;
	  this.endDeptQt = null;
	  this.radioValueZy = null;
	  this.radioValueZyPre = null;
	  this.startDeptZy = null;
	  this.endDeptZy = null;
	  this.patientZy = null;
	  this.goodsNow = [];
	  this.workOrderInspectScore = undefined;
	  this.patientList = [];
	  this.workOrderRemark = "";
	  this.workOrderRemarkZy = "";
	  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;
		this.eventData = null
		this.tool.triggerEndEvent({
			message:'关单',
		})
	}

	// 撤回
	// 打开撤回模态框
	openRecallModal(id) {
	  this.coopId = id;
	  this.recallOrderShow = true;
	}
	// 确认撤回
	btnLoading:any;
	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);
	    }
	  });
	}
	// 撤回并删除
	recDelLoading:boolean = false;
	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);
	    }
	  });
	}
	// 关闭撤回模态框
	batchClickType1:boolean = false;
	recallOrderShow:boolean = false;

	closeRecallOrderModal() {
	  this.recallOrderShow = false;
	  this.batchClickType1 = false;
	}

	// 删除
	// 打开模态框
	coopId; //当前操作id
	coopType;
	delOrderShow:boolean = false
	openDelModal(id, type) {
	  this.coopId = id;
	  this.coopType = type;
	  this.delOrderShow = true;
	}

	// 关闭模态框
	closeDelOrderModal() {
	  this.delOrderShow = false;
	}
	// 新建工单
	// 提交选择转入科室的模态框
	dataStatus:any;
	limitTimeModal: boolean = false; //模态框
	limitTimeInfo:string = '';
	limitTimeItem: any = {};
	hideLimitTimeModal() {
	  this.limitTimeModal = false;
	}

	// 建单判断时间-护士端建单通用方法
	isShowConfirm:boolean = true;
	isShowConfirmInfo:string = '';
	newOrderTimeFun(order, fun1, fun2){
	  fun2.call(this)
	}

	repeatModal: boolean = false; //删除模态框
	repeatMsg = "";
	loadingRepeat = false;
	repeatPostData;
	sourceType;
	showRepeatModal(postData, sourceType, go) {
	  this.repeatModal = true;
	  this.repeatPostData = postData;
	  this.sourceType = sourceType;
		// if(this.goType=='&go&'){
		// 	this.showRepetitionModal("建单", true, "", "closeGo");
		// }
	}
	hideRepeatModal() {
	  this.repeatModal = false;
	  this.btnLoading = false;
		this.confirmType = false;
		if(this.goType=='&go&'){
			console.log('fou222222')
			this.showNewOrder("&go&");
			// this.showRepetitionModal("建单", true, "", "closeGo");
		}
	}

	confirmType:boolean = false;
	currentDept:any;

	confirmRepeat() {
		this.confirmType = true;
	  this.loadingRepeat = true;
	  this.repeatPostData.tipsCreateOder = 1;
		let url = null;
		if(this.isYyInspect){
			url = this.mainService.postCustom("api", "appointmentOrder", this.repeatPostData)
		}else{
			url = this.mainService.buildOrder(this.repeatPostData)
		}
	 url.subscribe((data) => {
	    this.loadingRepeat = false;
	    this.repeatModal = false;
			if(this.currentDept.typeValue == 'recovery'){
			  this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.repeatPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
			    this.confirmRepeatFun(data);
			  });
			}else{
			  this.confirmRepeatFun(data);
			}

	  });
	}
	confirmRepeatFun(data){
		console.log(10087,this.sourceType)
	  if (this.sourceType === "specimen") {
	    // 标本建单
			if (data.status == 200){
				this.showRepetitionModal("创建", true, "");
			}else if(data.status == 100043){
				this.showRepetitionModal("创建", true, data.msg);
			}else{
				this.showRepetitionModal("创建", false, data.msg);
			}
	  //   if (data.status == 200 && (this.taskType == "other" || this.taskType == "ordinary")) {
	  //     this.showRepetitionModal("创建", true, "", this.taskType);
	  //   } else if (data.status == 200 && this.taskType == "bb") {
	  //     this.showRepetitionModal("创建", true, "", "bb");
	  //   } else if (this.taskType == "bb" && data.status == 100043) {
	  //     this.showRepetitionModal("创建", true, data.msg);
	  //   } else if (data.status == 100043){
	  //     this.showRepetitionModal("创建", true, data.msg);
	  //   } else {
			// 	this.showRepetitionModal("创建", false, data.msg);
			// }
	  } else if (this.sourceType === "other" || this.sourceType === "ordinary") {
			// 其他建单
			if (data.status == 200){
				this.showRepetitionModal("创建", true, "");
			}else if(data.status == 100043){
				this.showRepetitionModal("创建", true, data.msg);
			}else{
				this.showRepetitionModal("创建", false, data.msg);
			}
	    // if (data.status == 200 && (this.taskType == "other" || this.taskType == "ordinary")) {
	    //   this.showRepetitionModal("创建", true, "", this.taskType);
	    // } else if (data.status == 200 && this.taskType == "bb") {
	    //   this.showRepetitionModal("创建", true, "", "bb");
	    // } else if (this.taskType == "bb" && data.status == 100043) {
	    //   this.showRepetitionModal("创建", true, data.msg);
	    // } else if (data.status == 100043){
	    //   this.showRepetitionModal("创建", true, data.msg);
	    // } else {
	    //   this.showRepetitionModal("创建", false, data.msg);
	    // }
	  } else if (this.sourceType === "transport") {
	    // 转运
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else if (this.sourceType === "accompany1") {
	    // 陪检
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else if (this.sourceType === "accompany2") {
	    // 陪检
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else if (this.sourceType === "accompany3") {
	    // 陪检
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else if (this.sourceType === "accompany4") {
	    // 陪检
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else if (this.sourceType === "accompany5") {
	    // 陪检
	    if (data.status == 200) {
	      this.showRepetitionModal("创建", true, "");
	    } else if (data.status == 100042) {
	      this.showRepetitionModal("创建", false, data.msg);
	    } else {
	      this.showRepetitionModal("创建", false, data.msg);
	    }
	  } else {
			if (data.status == 200) {
			  this.showRepetitionModal("创建", true, "");
			} else if (data.status == 100042) {
			  this.showRepetitionModal("创建", false, data.msg);
			} else if (data.status == 100043) {
			  this.showRepetitionModal("创建", true, data.msg);
			} else {
			  this.showRepetitionModal("创建", false, data.msg);
			}
		}
	}

	// 隐藏选择转入科室的模态框
	deptFlagHand(e) {
	  this.deptFlag = false;
	}
	// 打开模态框,服务台右侧转入院记录建单
	createOrderObj; //当前操作id
	createLoading = false;
	deptFlag = false;
	patientLogBuild(obj) {
	  this.createOrderObj = obj;
	  this.deptFlag = true;
	}

	// 初始化展示形式
	controlView:any = {}; //展示形式
	hurseInfoHiding:any;
	audioNotDispatched:any;
	orderInfoTime:any;
	workerInfoTime:any;
	txtLabelCol:any;
	patientCareCol:any;
	typeId:any;
	checkTab:any;
	workerRefreshTime:any;
	orderRefreshTime:any;

	initControlView() {
	  let postData = {
	    controlView: {},
	    idx: 0,
	    sum: 1,
	  };
	  this.mainService
	    .coopTypeConfig("fetchDataList", "controlView", postData)
	    .subscribe((data) => {
	      this.controlView = data.list[0] ? data.list[0] : {
	        hurseInfoHiding: 1,
	        orderInfoTime: 60,
	        workerInfoTime: 60,
	        unsendOrderVoice: true,
	        orderType: 'priority',
	      };

	      this.patientCareCol = 7;
	      this.hurseInfoHiding = this.controlView.hurseInfoHiding ? 1 : 0;
	      this.txtLabelCol = 1;
	      this.orderRefreshTime = this.orderInfoTime = this.controlView.orderInfoTime;
	      this.workerRefreshTime = this.workerInfoTime = this.controlView.workerInfoTime;
	      this.audioNotDispatched = this.controlView.unsendOrderVoice !== false;
	      this.orderType = this.controlView.orderType || 'priority';

	      // this.getOrderList(1);
	      // this.getOrderList(2);
	      // this.getOrderList(3);
	    });
	}

	// 保存展现形式
	saveLoading:boolean = false
	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: {
	      workerNum: wn,
	      labelNum: that.txtLabelCol,
	      workerInfoTime: that.workerInfoTime,
	      orderInfoTime: that.orderInfoTime,
	      unsendOrderVoice: that.audioNotDispatched,
	      hurseInfoHiding: that.hurseInfoHiding === 1,
	      orderType: this.orderType,
	    },
	  };
	  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.msg.success('排序成功');
	        this.initControlView();
	      } else {
	        that.msg.error(data.msg || '排序失败');
	      }
	    });
	}

	// 确认
	jdFlagId;
	limitTimeLoading:boolean = false;
	confirmLimitTime() {
	  console.log(this.limitTimeItem);
	  this.limitTimeModal = false;
	  this.jdFlagId = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;
	  this.limitTimeItem.fun2.call(this);
	}

	closeModel(e) {
		console.log(99999,e)
	  if (e === "close") {
			this.goType = null;
	    this.newOrderShowOpen = false; //此时可出现新的弹窗
	  } else if (e === "closeGo") {
			console.log(1111)
	    this.showNewOrder("&go&");
	  }else if(this.dataStatus==1000033 && this.goType=='&go&'){
			console.log(2222)
			this.showNewOrder("&go&");
		}
	}

	// 重复建单提示框
	promptModalShow:boolean = false;
	back:any;
	promptInfo:any;
	ifSuccess:any;
	promptContent:any;

	showRepetitionModal(con, success, promptInfo?, back?){
		this.promptModalShow = false;
		this.promptContent = con;
		this.ifSuccess = success;
		this.promptInfo = promptInfo;
		this.back = back || "";
		setTimeout(() => {
			if(this.confirmType || this.goType=='&go&'){
				this.showPromptModalRefresh();
				this.promptModalShow = true;
			}
		}, 100);
	}

	// 展示信息提示框（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.showPromptModalRefresh();
	    this.promptModalShow = true;
	  }, 100);
	}

	showPromptModalRefresh(){
		// this.goType = null;
		// this.confirmType = false;
	  // this.getUnassignedBuilding2();
	  // this.resetList();
	  // this.getOrderList(1);
	  // this.getOrderList(2);
	  // this.getOrderList(3);
	  // this.getVisitList();
	  // this.getMessageList();
	  // if (this.currentRTab === 0) {
	  //   this.getWorkOrders(this.applyDept);
	  // } else if (this.currentRTab === 1) {
	  //   this.getPatientLog(this.applyDept);
	  // } else if (this.currentRTab === 2) {
	  //   this.getItsmOrders(this.incidentModel.department);
	  // } else if (this.currentRTab === 3) {
	  //   this.getDictionaryList();
	  // }
		// this.newOrderShow = false;
		// this.newOrderShowOpen = false;
		this.eventData = null
		this.tool.triggerEndEvent({
			message:'关单',
		})
	  this.fixedTab = "";
	  this.fixedMenuShangla();
	}

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

	// 上拉
	fixedMenuShangla() {
	  this.showLastItems = false;
	  this.fixedTab = "";
	}

	// 格式化时分秒
	// （时间小于一分钟则显示秒，时间大于一分钟则显示分钟数，如超出一小时则显示小时和分钟。）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(nodeId) {
	  let fixedMenu = document.getElementById(nodeId);
	  if (!fixedMenu) return;
	  fixedMenu.onmousedown = function (e) {
	    fixedMenu.classList.remove('maskFull');
	    let y = e.clientY - fixedMenu.offsetTop;
	    document.onmousemove = function (ev) {
	      fixedMenu.classList.add('maskFull');
	      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.classList.remove('maskFull');
	      document.onmousemove = null;
	      document.onmouseup = null;
	    };
	  };
	}

	// 处理人+协同人
	transferSynergetic(incidentData){
	  let str = incidentData.groupORHandlerUser || "";
	  if(incidentData.synergetic && incidentData.synergetic.length){
	      str += '，' + incidentData.synergetic.map(v => v.name).join('，');
	  }
	  return str;
	}

	// 菜单拖拽-自由
	moveMenuAll(nodeId) {
	  let fixedMenu = document.getElementById(nodeId);
	  if (!fixedMenu) return;
	  fixedMenu.onmousedown = function (e) {
	    fixedMenu.classList.remove('maskFull');
	    let x = e.clientX - fixedMenu.offsetLeft;
	    let y = e.clientY - fixedMenu.offsetTop;
	    document.onmousemove = function (ev) {
	      fixedMenu.classList.add('maskFull');
	      var _y = ev.clientY - y > 0 ? ev.clientY - y : 0;
	      var h = window.innerHeight;
	      if (_y > h - fixedMenu.clientHeight) {
	        _y = h - fixedMenu.clientHeight;
	      }
	      fixedMenu.style.top = _y + "px";

	      var _x = ev.clientX - x > 0 ? ev.clientX - x : 0;
	      var w = window.innerWidth;
	      if (_x > w - fixedMenu.clientWidth) {
	        _x = w - fixedMenu.clientWidth;
	      }
	      fixedMenu.style.right = w - _x - fixedMenu.clientWidth + "px";
	    };
	    document.onmouseup = function () {
	      fixedMenu.classList.remove('maskFull');
	      document.onmousemove = null;
	      document.onmouseup = null;
	    };
	  };
	}

	// 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 + "_" + item.associationTypeValue;
	      });
	    }
	  });
	}
	//服务台建单任务类型回车,0_1,0是关联类型，1是任务类型
	changeTaskBuild(e) {
	  let arr = e.split("_");
	  if(arr[2] === 'other' || arr[2] === 'specimen' || arr[2] === 'ordinary'){
	    this.currentTabIndex = '物品配送';
	  }else if(arr[2] === 'patientTransport'){
	    this.currentTabIndex = '患者转运';
	  }
	  if (this.currentTabIndex == "患者转运") {
	    //患者其他服务业务
	    this.radioValueZy = +arr[1];
	  } else if (this.currentTabIndex == "物品配送") {
	    //其他临床服务
	    this.radioValueQt = +arr[1];
	  }
	}

	// 服务台建单输入住院号,查到有且仅有一个患者，则自动选中【患者转运】，自动带出【申请科室】，自动带出【患者信息】
	changeResidenceNo(e){
	  console.log(e);
	  this.changeCommonInpSubject.next(['patient', e]);
	}

	// 运维、配送工单切换
	filterOrderList(type, state){
	  // if(!this.itsmData.mdv2Switch && this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  // if(this.itsmData.mdv2Switch && !this.hsmsData.hsmsSwitch){
	  //   return;
	  // }
	  this.flagList[`${type}Flag${state}`] = !this.flagList[`${type}Flag${state}`];
	  // this.getOrderList(state, state === 1);
	}

	// 排序
	orderType: string = 'priority'; //排序方式 priority:优先级，time:时间
	orderList(){
	  this.orderType = this.orderType === 'priority' ? 'time' : 'priority';
	  this.saveControlView();
	}

	// 优先级颜色
	priorityColor(priorityId) {
	  // 极低|低
	  if(priorityId == 1 || priorityId == 2){
	    return '';
	  } else if(priorityId == 3){
	    return 'yellow';
	  } else if(priorityId == 4 || priorityId == 5){
	    return 'red';
	  }
	}

	// 延期记录
	transferHandlerLog = function (currentLog) {
	  if(!currentLog){
	      return '';
	  }
	  currentLog = cloneDeep(currentLog);
	  if(currentLog.extra1DTO && currentLog.extra2 && currentLog.startTime){
	      if(currentLog.extra2==0.5){
	        currentLog.extra2 = 4;
	        return currentLog.extra1DTO.name+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "MM月dd日")+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "HH时mm分前完成");
	      }else{
	        return currentLog.extra1DTO.name+"<br>"+ format(addDays(currentLog.startTime, +currentLog.extra2), "MM月dd日前完成");
	      }
	  }else{
	      return '';
	  }
	}

	// 生成工单
	buildType;
	editOrder;
	generateOrder(data){
	  this.editOrder = cloneDeep(data);
	  let incidentModel = cloneDeep(data);
	  let incidentMsg:any = {};
	  console.log('data:', data)
	  // incidentModel.department && (this.applicationDeptList = [cloneDeep(incidentModel.department)]);
	  incidentModel.department && (incidentMsg.deptManyPhone = incidentModel.department.manyPhone);
	  incidentModel.department && (incidentMsg.deptName = incidentModel.department.dept);
	  incidentModel.department && (incidentModel.department = incidentModel.department.id);
	  incidentModel.requester && (this.applicationRequesterList = [cloneDeep(incidentModel.requester)]);
	  incidentModel.requester && (incidentMsg.requesterPhone = incidentModel.requester.phone);
	  incidentModel.requester && (incidentMsg.requesterName = incidentModel.requester.name);
	  incidentModel.requester && (incidentModel.requester = incidentModel.requester.id);
	  if(incidentModel.repairIncidentType){
	    incidentModel.repairIncidentType = incidentModel.repairIncidentType.value
	    this.changeRepairIncidentType(incidentModel.repairIncidentType);
	  }
	  incidentModel.source && (incidentModel.source = incidentModel.source.id);
	  incidentModel.area && (incidentModel.area = incidentModel.area.id);
	  incidentModel.place && (incidentModel.place = incidentModel.place.id);
	  incidentModel.category && (this.applicationCategoryList = [cloneDeep(incidentModel.category)]);
	  incidentModel.category && (incidentModel.category = incidentModel.category.id);
	  this.incidentModel = incidentModel;
	  this.incidentMsg = incidentMsg;
	  this.incidentModel.category && this.changeApplyCategory(this.incidentModel.category, true);
	  console.log('this.applicationDeptList:', this.applicationDeptList)
	  console.log('incidentModel:', incidentModel)
	  this.showNewOrder('', '', true, '报修转事件');

	  // 查询报修图片
	  this.getRepairImgs(data.id);
	}

	// 继续建单
	storageSj(data){
	  this.editOrder = cloneDeep(data);
	  let incidentModel = cloneDeep(data);
	  let incidentMsg:any = {};
	  console.log('data:', data)
	  // incidentModel.department && (this.applicationDeptList = [cloneDeep(incidentModel.department)]);
	  incidentModel.department && (incidentMsg.deptManyPhone = incidentModel.department.manyPhone);
	  incidentModel.department && (incidentMsg.deptName = incidentModel.department.dept);
	  incidentModel.department && (incidentModel.department = incidentModel.department.id);
	  incidentModel.requester && (this.applicationRequesterList = [cloneDeep(incidentModel.requester)]);
	  incidentModel.requester && (incidentMsg.requesterPhone = incidentModel.requester.phone);
	  incidentModel.requester && (incidentMsg.requesterName = incidentModel.requester.name);
	  incidentModel.requester && (incidentModel.requester = incidentModel.requester.id);
	  if(incidentModel.repairIncidentType){
	    incidentModel.repairIncidentType = incidentModel.repairIncidentType.value
	    this.changeRepairIncidentType(incidentModel.repairIncidentType);
	  }
	  incidentModel.source && (incidentModel.source = incidentModel.source.id);
	  incidentModel.area && (incidentModel.area = incidentModel.area.id);
	  incidentModel.place && (incidentModel.place = incidentModel.place.id);
	  incidentModel.category && (this.applicationCategoryList = [cloneDeep(incidentModel.category)]);
	  incidentModel.category && (incidentModel.category = incidentModel.category.id);
	  this.incidentModel = incidentModel;
	  this.incidentMsg = incidentMsg;
	  console.log('this.applicationDeptList:', this.applicationDeptList)
	  console.log('incidentModel:', incidentModel)
	  this.showNewOrder('', '', true, '继续建单');

	  // 查询报修图片
	  this.getRepairImgs(data.id);
	}

	// 获取报修图片
	repairImgs:any[] = [];//报修图片
	getRepairImgs(incidentId) {
	  this.mainService
	    .getPreviewImage('wechatRequesterIncident', incidentId)
	    .subscribe((res:any) => {
	      res.data = res.data || [];
	      res.data.forEach(v => {
	        v.previewUrl = location.origin + "/file" + v.relativeFilePath;
	        v.thumbFilePath = location.origin + "/file" + v.thumbFilePath;
	      })
	      this.repairImgs = res.data;
	    });
	}

	// 预览图片
	imgs = [];
	isPreview = false;
	initialViewIndex:number = 0;
	previewImageHandler(data = [], index = 0) {
	  this.initialViewIndex = index;
	  console.log(index)
	  this.isPreview = false;
	  data = data || [];
	  this.imgs = data.map((v) => location.origin + '/file' + v.relativeFilePath);
	  setTimeout(() => {
	    this.isPreview = true;
	  }, 0)
	}

	// 不受理-弹窗
	rejectModalShow = false; //弹窗开关
	rejectFn(data) {
	  this.coopData = data;
	  this.rejectModalShow = true;
	}
	// 关闭弹窗
	closeRejectModelOrder(e) {
	  this.rejectModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmRejectModelOrder(rejectRemark){
	  this.maskFlag = this.msg.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;

	  let postData = {
	    incident: {
	      ...this.coopData,
	      rejectRemark,
	    },
	  }

	  console.log(postData);
	  // return;
	  this.mainService
	  .flowPost("incident/task/reject", postData)
	  .subscribe((result) => {
	    this.msg.remove(this.maskFlag);
	    this.maskFlag = false;

	    if (result.state == 200) {
	      this.rejectModalShow = false;
	      this.showPromptModal("不受理", true, "", "");
	    } else {
	      this.msg.error(result.msg || '不受理失败');
	    }
	  });
	}

	/* 新增报修 end */
	addOrder(){
		this.currentDept = this.tool.getCurrentUserDept();
		//防抖
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchApplicationDepartment(v[0], v[1]);
		});
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  if(v[0] === 'requester'){
		    this.searchApplicationRequester(v[1]);
		  }else if(v[0] === 'category'){
		    this.searchApplicationCategory(v[1]);
		  }else if(v[0] === 'group'){
		    this.searchApplicationGroup(v[1]);
		  }else if(v[0] === 'user'){
		    this.searchApplicationUser(v[1]);
		  }else if(v[0] === 'patient'){
		    this.getPatientByResidenceNo(v[1]);
		  }
		});
		
		this.changeAssetInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.getAssetData(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.initLogin();
		this.getSysConfig();
		this.initOrderScope();

		this.initControlView();
		this.moveMenu("fixedMenu");
		this.moveMenu("fixedMenuLeft");
		this.moveMenuAll("fixedMenuAll");
	}

	// 获取系统配置
	initConfig:any;
	config:any;
	hospitalModel:any; //院区模式 1:单院区 -1：多院区
	applicantMustFillIn:any; //申请人是否必填 1是，0否
	deptRepair:boolean = false; //科内报修
	publicRepair:boolean = false; ; //公共报修
	cmdbRepair:boolean = false; ; //是否支持资产报修
	getSysConfig() {
		const postData = { idx: 0, sum: 99 };
		this.mainService
			.getFetchDataList("simple/data", "systemConfiguration", postData)
			.subscribe((result) => {
				if (result.status == 200) {
					if (result.list && Array.isArray(result.list)) {
						this.initConfig = JSON.parse(JSON.stringify(result.list));
						this.config = result.list.map((item) => {
							return [item.keyconfig, item.valueconfig, item.id, item.label];
						});
						this.config.forEach((c) => {
							switch (c[0]) {
								case "deptRepair":
									if(c[1]=='1'){
										this.deptRepair = true
									}else{
										this.deptRepair = false
									}
									break;
								case "publicRepair":
									if(c[1]=='1'){
										this.publicRepair = true
									}else{
										this.publicRepair = false
									}
									break;
								case "hospitalModel":
									this.hospitalModel = c[1]
									break;
								case "applicantMustFillIn":
									this.applicantMustFillIn = c[1]
									break;
								case "cmdbRepair":
									if(c[1]=='1'){
										this.cmdbRepair = true
									}else{
										this.cmdbRepair = false
									}
									break;	
							}
						});
						if(this.eventData){
							this.incidentModel.repairIncidentType = 'public'
						}else{
							if(this.publicRepair && !this.deptRepair){
								this.incidentModel.repairIncidentType = 'public'
								this.isRelatedDepartment = false
							}
							if(!this.publicRepair && this.deptRepair){
								this.incidentModel.repairIncidentType = 'dept'
							}
						}
						if(this.hospitalModel==1){
							if(this.tool.getCurrentHospital().parent){
								this.incidentModel.hosId = this.tool.getCurrentHospital().parent.id
							}else{
								this.incidentModel.hosId = this.tool.getCurrentHospital().id
							}
							this.searchApplicationBuilding()
						}
						
						if(this.cmdbRepair && this.hospitalModel==1){
							this.getAssetData()
						}
					}
				}
			});
	 }
	
	changeAsset(e){
		this.changeAssetInpSubject.next(e);
	}
	
  // 获取资产列表
	assetData:any = [];
	getAssetData(name?){
		// if(!this.incidentModel.hosId){
		// 	return
		// }
		let data = {
		  idx: 0,
		  sum: 20,
		  asset: {
		    downHosId: this.hospitalModel!=1 ? this.incidentModel.hosId : this.currentHospital.id,
		    name: name
		  },
		};
		
		this.mainService
		  .getFetchDataList("simple/data", "asset", data)
		  .subscribe((data) => {
		    if (data.status == 200) {
		      this.assetData = data.list;
		    }
		  });
	}
	
	// 新增报修
	speedinessAdd(): void {
		this.addOrder();
		if(this.currentTabIndex === '故障报修'){
			this.incidentModel.department = null;
			this.rightTitle_tab = [
				{ id: 2, name: '近期维修' },
				{ id: 3, name: '知识库' },
			]
			this.rightTitleHandler(this.rightTitle_tab[0].id);
		}
	}


  // 调度台
  toFuwutai(): void {
    this.router.navigateByUrl("dispatchingDesk");
  }

  // 护士建单
  toHuShi(): void {
    this.router.navigateByUrl("nurse");
  }
  // 药房端
  toPharmacy(): void {
    this.router.navigateByUrl("pharmacy");
  }
  // 药房端2
  toPharmacy2(): void {
    this.router.navigateByUrl("pharmacy2");
  }
  // 标本视图
  toSpecimenView2(): void {
    this.router.navigateByUrl("specimenView2");
  }
	// 标本间
	toSpecimenRoomView(): void {
	  this.router.navigateByUrl("specimenRoomView");
	}
	// 病理科
	toPathology(): void {
	  this.router.navigateByUrl("pathology");
	}
	// 门诊病理采样端
	toSampling(): void {
	  this.router.navigateByUrl("pathologySample");
	}
	// 病理交接本
	toCommunicationBook(): void {
	  this.router.navigateByUrl("pathologyCommunicationBook");
	}
  // 全局业务查看
  toDisinfectionSupply(): void {
    this.router.navigateByUrl("disinfectionSupply");
  }
  // 故障实时播报
  toRealtimeBroadcast(): void {
    this.router.navigateByUrl("realtimeBroadcast");
  }
  // 陪检闭环视图
  toInspectClosedLoopView(): void {
    this.router.navigateByUrl("inspectClosedLoopView");
  }
  // 配置中心
  toConfigurationCenter(): void {
    this.iShowMenuModal = true;
    // this.router.navigateByUrl("configurationCenter");
  }
	// web报修-个人报修
	toWebRepairs(): void {
	  this.router.navigateByUrl("webRepairs");
	}
  // 统计
  toNewStatistics(): void {
    let menus = JSON.parse(localStorage.getItem("menu"));
    let firstMenu = menus.find((item) => item.type == "newStatistics");
    this.router.navigateByUrl(`newStatistics/${firstMenu.link}/${firstMenu.childrens[0].link}`);
  }
  // 大屏端或视图端
  screenType;
  hosFlag = false;
  toBigScreen(type): void {
    this.screenType = type;
    this.submitFormHand(this.currentHospital.id);
  }
  submitFormHand(id) {
    if (this.screenType === "largeScreen") {
      window.open(`${http.bigScreenHost}/#/${this.queryType}?hosId=${this.hospital ? this.hospital.id : ''}&dutyId=${this.duty ? this.duty.id : ''}`);
    } else if (this.screenType === "largeScreen2") {
      window.open(http.bigScreenHost2 + "/#/" + id);
    } else if (this.screenType === "largeScreen3") {
      window.open(`${http.bigScreenHost3}/#/${this.queryType}?hosId=${this.hospital ? this.hospital.id : ''}&dutyId=${this.duty ? this.duty.id : ''}`);
    } else if (this.screenType === "specimenView") {
      window.open(http.specimenViewHost + "/#/" + id);
    }
  }
  //获取系统设置中的科室类型
  getTypeByDept(id) {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "busiViewDeptId" },
    };
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          let remember = JSON.parse(localStorage.getItem("remember"));
          window.open(
            http.specimenViewHost +
              "/#/" +
              id +
              "/" +
              encodeURIComponent(remember.username) +
              "/" +
              encodeURIComponent(remember.password) +
              "/" +
              result.list[0].valueconfig
          );
        }
      });
  }
  hosFlagHand(flag) {
    if (!flag) {
      this.hosFlag = false;
    }
  }


  // 选择菜单-知道了
  iShowMenuModal:boolean = false;
  cancelMenuModal(flag) {
    this.iShowMenuModal = false;
  }

  // 下拉
  showDropdown:boolean = false;
  showDropdown1:boolean = false;
	showFastDropdown:boolean = false;

  // 选择院区
  selectHospital(){
    this.hosFlag1 = true
  }

  // 退出
  logOut(): void {
    // 假退出
    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("index");

    // 假退出
    this.mainService.logOut().subscribe((data) => {
      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("index");
      }
    });

  }

  // 连接websocket
  getWebsocket() {
    this.webs
      .connectWs(http.mainWs, { userCount: this.userInfo.user.account })
      .subscribe((data) => {
        console.log(data);
        if (data && data.content) {
          this.createBasicNotification(data);
        }
      });
  }
  @ViewChild("msgTemplate1", { static: false }) msgTemplate1: TemplateRef<any>; //消息通知模板
  // 消息提醒
  createBasicNotification(msgs): void {
    this.notification.template(this.msgTemplate1, {
      nzDuration: 0,
      nzData: msgs,
    });
  }

  //打开修改密码弹窗
  pwdAfterOpen(){
    this.passwordVisible = false;
    this.pwdIsOkLoading = false;
    this.enoughRegFlag = true; //弱
    this.mediumRegFlag = false; //中
    this.strongRegFlag = false; //强
    this.upModalData = {
      userid: "",
      pwdOld: "",
      newPwd: "",
      newPwd2: "",
    };
  }

  // 修改密码
  passwordVisible = false;
  password?: string;

  isPwdVisible = false;
  pwdIsOkLoading = false;
  upModalData = {
    userid: "",
    pwdOld: "",
    newPwd: "",
    newPwd2: "",
  };
  upPwd(): void {
    if(this.upModalData.pwdOld.trim() === ''){
      this.msg.error('请填写原始密码！', {
        nzDuration: 5000,
      });
      return;
    }
    if(!this.strongRegFlag){
      this.msg.error('新密码不符合要求！', {
        nzDuration: 5000,
      });
      return;
    }
    if(this.upModalData.newPwd !== this.upModalData.newPwd2){
      this.msg.error('新密码与确认新密码不一致！', {
        nzDuration: 5000,
      });
      return;
    }

    this.pwdIsOkLoading = true;
    let userid = JSON.parse(localStorage.getItem("user")).user.id;
    this.upModalData.userid = userid;
    this.mainService.upPwd(this.upModalData).subscribe((data) => {
      if (data.status == 200) {
        this.isPwdVisible = false;
        this.pwdIsOkLoading = false;
        this.msg.success("修改成功！", {
          nzDuration: 5000,
        });
      } else {
        this.pwdIsOkLoading = false;
        this.msg.error(data.error, {
          nzDuration: 5000,
        });
      }
    });
  }
  showUpPwd(): void {
    this.isPwdVisible = true;
  }

  pwdHandleOk(): void {
    this.upPwd();
  }

  pwdHandleCancel(): void {
    this.isPwdVisible = false;
  }

  delModal = false;
  tipsMsg1 = "是否确定离开该界面，如果未点击生效，数据可能会遗失？";
  navInfo = {};
  // 隐藏模态框
  hideDelModal() {
    this.delModal = false;
  }
  // 模态框确认
  confirmDel() {
    this.delModal = false;
    if (this.navInfo["title"] == "首页") {
      this.router.navigateByUrl("/main/home");
      this.toMenu("首页");
    } else {
      this.router.navigateByUrl("/main/" + this.navInfo["item"].link);
      this.toMenu(
        this.navInfo["title"],
        this.navInfo["item"],
        this.navInfo["data"]
      );
    }
  }
  //前往菜单连接（拦截版）
  totoMenu(title, item?, data?) {
    let url = location.href.split("#")[1];
    if (url.includes("/main/quickCombination")) {
      //拦截
      this.delModal = true;
      this.navInfo = {
        title,
        item,
        data,
      };
    } else {
      //正常情况
      if (title == "首页") {
        this.router.navigateByUrl("/main/home");
        this.toMenu("首页");
      } else {
        this.router.navigateByUrl("/main/" + item.link);
        this.toMenu(title, item, data);
      }
    }
  }
  // 切换院区
  hosFlag1 = false;
  submitFormHand1(id) {
    if(this.currentHospital.id == id){
      return;
    }
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .changeHospital({ currentHosId: +id, loginType: "PC" })
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          localStorage.setItem("user", JSON.stringify(result.user));
          location.reload(true);
        } else {
          this.msg.create("error", "切换院区失败");
        }
      });
  }
  hosFlagHand1(flag) {
    if (!flag) {
      this.hosFlag1 = false;
    }
  }

	// 查询范围
  queryRangeFlag = false;
  queryRangeClick(type){
    this.screenType = type;
    this.queryRangeFlag = true;
  }
  submitQueryRange({queryType, hospital, duty, parent}) {
    console.log('queryType:', queryType)
    console.log('hospital:', hospital)
    console.log('duty:', duty)
    console.log('parent:', parent)
    this.queryType = queryType;
    this.hospital = hospital;
    this.duty = duty;
		this.parent = parent;
    this.queryRangeFlag = false;

    this.toBigScreen(this.screenType);
  }
  cancelQueryRange() {
    this.queryRangeFlag = false;
  }

	// 全院查询-1|院区查询-2|责任部门查询-3|部门垂直查询-4
  hospital;
  duty;
  queryType;//查询范围
	parent:any = 0;
  // 初始化院区、部门显示
  initHospitalAndDuty(hospitalOrDuty){
    let type = 'hospital';//默认是院区
    if(hospitalOrDuty.type){
      // 当前是责任部门
      type = 'duty';
    }

    if(type === 'duty'){
      // 当前的所属责任部门
      this.hospital = hospitalOrDuty.parent;
      this.duty = hospitalOrDuty;
    }else{
      // 当前的所属院区
      this.hospital = hospitalOrDuty;
      this.duty = undefined;
    }

    // 查询范围单选框
    if(this.hospital){
      if(this.duty){
        if(this.duty.parentDeptId){
          this.queryType = 3;
        }else{
          this.queryType = 4;
        }
      }else{
        this.queryType = 2;
      }
    }else{
      this.queryType = 1;
    }

		console.log('this.hospital:', this.hospital)
    console.log('this.duty:', this.duty)
    console.log('this.queryType:', this.queryType)
    console.log('this.parent:', this.parent)
  }
}
