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

import http from "../../../assets/js/http";
import { MainService } from "../../services/main.service";
import { WebsocketNurseService } from "../../services/websocket-nurse.service";

import { NzMessageService, UploadFile } from "ng-zorro-antd";
import { NzNotificationService } from "ng-zorro-antd/notification";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime, filter } from "rxjs/operators";
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
import {
  format,
  getMinutes,
  setMinutes,
  addDays,
  differenceInCalendarDays,
  getHours,
  startOfDay,
  endOfDay,
  parse,
	subHours,
	startOfMinute,
	addMinutes
} from "date-fns";
import { SourceId } from "src/app/type/types";
import cloneDeep from 'lodash-es/cloneDeep'
// 日期禁用
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-hushijiandan",
  templateUrl: "./hushijiandan.component.html",
  styleUrls: ["./hushijiandan.component.less"],
})
export class HushijiandanComponent implements OnInit {
  @ViewChild('printBtn', { static: false }) printBtn: ElementRef<HTMLElement>;
  @ViewChild("remarksEle", { static: false }) remarksEle: ElementRef;
  @ViewChild("remarksEle1", { static: false }) remarksEle1: ElementRef;
  @ViewChild("remarksEle2", { static: false }) remarksEle2: ElementRef;
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef4", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef4: OverlayScrollbarsComponent;
  // @ViewChild("osComponentRef5", {
  //   read: OverlayScrollbarsComponent,
  //   static: false,
  // })
  // osComponentRef5: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef6", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef6: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef7", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef7: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef8", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef8: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef9", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef9: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef10", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef10: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef11", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef11: OverlayScrollbarsComponent;

  othersListOptions: any;
  sortableTimer = null;
  searchAccountSubject = new Subject(); //查工号防抖
  searchTabInpSubject = new Subject(); //左侧查患者信息和检查信息防抖
  otherSearchChangeSubject = new Subject(); //其他建单搜索防抖
  inspectSubject = new Subject();
	changeAssetInpSubject = new Subject();
	changeCommonInpSubject = new Subject();
  isYyInspect = false; //需要预约检查
  inspectAndPatientTransportConfig:any = {timeMod: 30};
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    public router: Router,
    private route: ActivatedRoute,
    private mainService: MainService,
    private notification: NzNotificationService,
    private webs: WebsocketNurseService,
    public tool: ToolService,
		public http: HttpClient

  ) {
    this.othersListOptions = {
      onUpdate: (event: any) => {
        // 触发一次排序
        clearTimeout(this.sortableTimer);
        this.sortableTimer = setTimeout(() => {
          let postData = {
            orders: [],
            tabId: this.checkedTableType == 'other' ? undefined : this.checkedTableType,
          };
          postData.orders = this.othersList[this.checkedTableType].map((item, i) => {
            return {
              id: item.id,
              orders: i,
            };
          });
          this.mainService
            .coopConfig("setOrders", postData)
            .subscribe((result) => {});
        }, 500);
      },
    };
  }
  // 下拉
  showDropdown:boolean = false;
  // 关闭倒计时
  closeTime = 3;
  closeTimeFlag;
  timerCloseTime = null;
  changeShow = true;
  currentHospital; //当前院区
  currentDept; //当前科室
  logTimer = null; //综合日志定时器
  logTime = 0; //综合日志自动刷新秒数
  logTimeConst = 60; //综合日志自动刷新秒数
  orderListTimer = null; //工单列表定时器
  orderListTime = 0; //工单列表自动刷新秒数
  orderListTimeConst = 60; //工单列表自动刷新秒数
  deptDisplay; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
	pathologyModal:boolean = false; //病理申请单
	pathologyDetailModal:boolean = false; //病理详情
  // 初始化权限按钮
  coopBtns: any = {};
	surgeryDataId: any; //手术id
	patientDataId: any; //病人id
	smartShow:boolean = false; //智能客服弹框
	userId:any;
	
  ngOnInit() {
    this.getCoopBtns();
    this.currentHospital = this.tool.getCurrentHospital();
		this.userId = this.tool.getCurrentUserId();
    this.tool.getDeptDisplay().subscribe((result) => {
      if (result.status == 200) {
        this.deptDisplay = result.list[0].valueconfig;
      }
    });
    this.getItsmIncident();
    this.getPagePermissionConfigList();
    this.getInspectAndPatientTransportConfigTasktype();
    this.getUpdateTipsForNurses();
    this.getRefreshNurseWorkOrderTime();
    this.getCloseTimeFlag();
		this.getCmdbRepairFlag();
    this.currentDept = this.tool.getCurrentUserDept();
    console.log(this.currentDept, this.tabSearchCont);
    this.currentDept.typeValue == 'surgery' && !this.tabSearchCont && this.getSurgeryConfig();
    this.getSpecimenButton();
    //防抖
    this.getAccountList();
    this.searchAccountSubject.pipe(debounceTime(500)).subscribe((v:any) => {
      this.getAccountList(v);
    });
    this.searchTabInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getPatient(v);
    });
    this.otherSearchChangeSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getDeptTaskType(v);
    });
    this.inspectSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.refreshInspectList();
    });
		this.changeAssetInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.getAssetData(v);
		});
		this.changeCommonInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchApplicationCategory(v);
		});
    this.getTodayNum();
    this.initLogin();
    this.getDeptTaskType();

    this.getAdvice();
    this.getOrderSelectList();
    this.getCheckStatusLis();
    this.refreshSpecimenWorkOrderMsg();
    this.initRole();
    this.getWebsocket();
		this.getTaskTypesId();
    // 综合日志倒计时 start
    this.logTime = this.logTimeConst;
    clearInterval(this.logTimer);
    this.logTimer = setInterval(() => {
      this.logTime--;
      if (this.logTime === 0) {
        this.logTime = this.logTimeConst;
        if (this.smallTabId == 1) {
          this.listDeptOrderRecord();
        } else if (this.smallTabId == 2) {
          this.getQuickBxlb();
        }
        this.getTodayNum(); //当日工单数量
      }
    }, 1000);
    // 综合日志倒计时 end

  }
  ngOnDestroy() {
    clearInterval(this.moveId);
    clearInterval(this.moveId1);
    clearInterval(this.msgTimerId);
    clearInterval(this.logTimer);
    clearInterval(this.orderListTimer);
    this.webs.closeWs(true);
  }
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息
  loginUserDeptId: number = JSON.parse(localStorage.getItem("user")).user.dept
    .id; //登录人所属科室
  appointmentBuildFlag = "0"; //是否开启护士端预约建单-患者陪检
  appointmentZyBuildFlag = "0"; //是否开启护士端预约建单-患者其他
  leadTime = 0; //护士端预约建单生效时长
  followFlag = "0"; //是否开启护士端终点关注
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  back: string; //操作结果后回调标识
  promptModalShow: boolean; //操作提示框是否展示
  hsPromptModalShow: boolean = false; //护士端科室切换提示框是否展示

  deptTaskTypeRules: any = {}; //当前登录科室任务类型信息规则

  orderSelectList: any = []; //工单列表筛选选项
  orderSelected = "-1"; //工单列表下拉框选中
  orderStateSelected = "1"; //工单列表工单状态下拉框选中

  tabSearchCont: string = ""; //左侧tab搜索框内容
  pLoading: boolean = true; //患者信息loading
  patientList: any = []; //左侧tab患者信息list
  infoPageIdx: number = 1; //左侧tab页码
  infoLength: number = 5; //左侧tab信息总数

  specimenWorkOrderMsg: any = {}; //急标普标数量&信息
  jpDrugsWKOMsg: any = {}; //药品静配提示信息
  surgeryWKOMsg: any = {}; //手术提示信息
	detailId:any = null; //病理申请单详情id

  getCoopBtns(){
    let menu: any = JSON.parse(localStorage.getItem("menu")) || []; //菜单
    let coopBtns:any = {};
    let nurseMenu = menu.find(v => v.link === 'nurse');
    let nurseMenuChildren = nurseMenu.childrens || [];
    nurseMenuChildren.forEach((e) => {
      switch (e.link) {
        case "suggestionBox":
          coopBtns.suggestionBox = true; //意见箱
          break;
        case "surgery":
          coopBtns.surgery = true; //手术排程信息
          break;
        case "outpatientHelpAppointment":
          coopBtns.outpatientHelpAppointment = true; //门诊帮扶预约
          break;
        case "inquiryOfHistoricalSpecimens":
          coopBtns.inquiryOfHistoricalSpecimens = true; //历史标本查询
          break;
        case "historicalMedicineListInquiry":
          coopBtns.historicalMedicineListInquiry = true; //历史药单查询
          break;
        case "repairList":
          coopBtns.repairList = true; //报修列表
          break;
        case "buildOrdersForOtherTasks":
          coopBtns.buildOrdersForOtherTasks = true; //其他任务建单
          break;
      }
    });
    this.coopBtns = coopBtns;
    console.log(this.coopBtns);
  }

	// 关闭客服弹框
	smartClose(e){
		this.smartShow = false;
	}

	// 打开客服弹框
	smartOpen(e?){
		this.smartShow = true;
	}

	// 预览图片
	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)
	}

	// 图片相关
	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;
	repairImgs:any[] = [];//报修图片
	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('wechatRequesterIncident', 0);

	// 图片上传
	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();
	}

	// 获取任务类型（病理标本）
	taskTypeData:any;
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='pathology')
			this.getPathologySys();
		});
	}

	// 获取标本配置
	autoCreate:any;
	pathologyFrozenSpecime:any;
	getPathologySys(){
		let postData = {
			  idx: 0,
			  sum: 10,
			  taskTypeConfig: {
					hosId:this.currentHospital.id,
					taskType:this.taskTypeData.id
			  }
		}

		this.mainService
		  .getFetchDataList("simple/data", "taskTypeConfig", postData)
		  .subscribe((result) => {
		    if (result.status == 200) {
          if(Array.isArray(result.list) && result.list[0]){
            this.autoCreate = result.list[0].autoCreate;
					  this.pathologyFrozenSpecime = result.list[0].pathologyFrozenSpecimenNum;
          }
		    }
		  });
	}

	// 新增申请单自选类型
	applicationType:any;
	isPathologyVisible:any = false;
	addPathologyType(type){
		this.applicationType = type
		if(type ==1 && this.pathologyFrozenSpecime == 1){
			this.submitPathlogyForm()
		}else{
			if(this.viewData.length>0){
				this.isPathologyVisible = true
			}else{
				this.submitPathlogyForm()
			}
		}
	}

	// 取消新增申请单自选类型
	handlePathologyCancel(){
		this.applicationType = null
		this.isPathologyVisible = false
	}

	// 确定新增申请单自选类型
	handlePathologyOk(){
		this.submitPathlogyForm()
	}

	// 新增申请单自选类型
	submitPathlogyForm(){
		if(this.openType=='btn'){
			this.surgeryDataId = this.surgeryWKOMsg.id
			this.patientDataId = this.surgeryWKOMsg.patientDTO.id
		}else{
			this.surgeryDataId = this.scheduleItem.id
			this.patientDataId = this.scheduleItem.patientDTO.id
		}
		let data = {
			idx: 0,
			sum: 9999,
			surgeryId: this.surgeryDataId || "",
			patientId: this.patientDataId || "",
			hosId: this.currentHospital.id || "" ,
			operationType: 'pathologyForm',
			pathologyFormType: this.applicationType
		};
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((data) => {
			this.detailId = data.data.id
			this.isPathologyVisible = false
			this.multiDialog = false
			this.pathologyModal = true
		});
	}

	// 手术排程-病理申请单
	openType:any;
	scheduleItem:any;
	pathologyAddItem(e,item){
		this.openType = 'schedule'
		this.scheduleItem = item
		// this.surgeryDataId = item.id
		// this.patientDataId = item.patientDTO.id
		let data = {
			idx: 0,
			sum: 9999,
			pathologyForm: {
				surgeryId: item.id || "",
				patientId: item.patientDTO.id || "",
				surgeryDeptId:this.loginUser.dept.id,
				// hosId: this.currentHospital.id || "" ,
				operationType: 'pathologyForm',
				order:'createTime desc',
			},
		};
		this.isSpinning = true
		this.mainService
			.getFetchDataList("data", "pathologyForm", data)
			.subscribe((data) => {
				this.isSpinning = false
				this.viewData = data.list
				for(let i of this.viewData){
					if(i.pathologyInspectDTOS){
						i.arr = []
						for(let x of i.pathologyInspectDTOS){
							i.arr.push(x.inspectProject.name)
						}
					}
				}
				this.multiDialog = true
			});
	}

	// 病理申请单
	multiDialog:any = false;
	isSpinning:any = false;
	viewData:any = [];
	pathologyAdd(e){
		this.openType = 'btn'
		this.surgeryDataId = this.surgeryWKOMsg.id
		this.patientDataId = this.surgeryWKOMsg.patientDTO.id
		let data = {
			idx: 0,
			sum: 9999,
			pathologyForm: {
				surgeryId: this.surgeryWKOMsg.id || "",
				patientId: this.surgeryWKOMsg.patientDTO.id || "",
				surgeryDeptId:this.loginUser.dept.id,
				// hosId: this.currentHospital.id || "" ,
				operationType: 'pathologyForm',
				order:'createTime desc'
			},
		};
		this.isSpinning = true
		this.mainService
		.getFetchDataList("data", "pathologyForm", data)
		.subscribe((data) => {
			this.isSpinning = false
			this.viewData = data.list
			for(let i of this.viewData){
				if(i.pathologyInspectDTOS){
					i.arr = []
					for(let x of i.pathologyInspectDTOS){
						i.arr.push(x.inspectProject.name)
					}
				}
			}
			this.multiDialog = true
		});
	}

	// 获取病理申请单最新数据
	getPathologyData(){
		if(this.openType=='btn'){
			this.surgeryDataId = this.surgeryWKOMsg.id
			this.patientDataId = this.surgeryWKOMsg.patientDTO.id
		}else{
			this.surgeryDataId = this.scheduleItem.id
			this.patientDataId = this.scheduleItem.patientDTO.id
		}
		let data = {
			idx: 0,
			sum: 9999,
			pathologyForm: {
				surgeryId: this.surgeryDataId || "",
				patientId: this.patientDataId || "",
				hosId: this.currentHospital.id || "" ,
				surgeryDeptId:this.loginUser.dept.id,
				operationType: 'pathologyForm',
				order:'createTime desc'
			},
		};
		this.isSpinning = true
		this.mainService
		.getFetchDataList("data", "pathologyForm", data)
		.subscribe((data) => {
			this.isSpinning = false
			this.viewData = data.list
			for(let i of this.viewData){
				if(i.pathologyInspectDTOS){
					i.arr = []
					for(let x of i.pathologyInspectDTOS){
						i.arr.push(x.inspectProject.name)
					}
				}
			}
		})
	}

	// 申请单号点击
	itemClick(item){
		this.detailId = item.id
		this.multiDialog = false
		setTimeout(_=>{
			if(!item.status){
				this.pathologyModal = true
				return
			}
			if(item.status && (item.status.value==1 || item.status.value==2 ||
				item.status.value==3 || item.status.value==4)){
				this.pathologyModal = true
			}else{
				this.pathologyDetailModal = true
			}
		},200)
	}

	// 申请单作废
	cancellationLoading:any = false;
	cancellationModal:any = false;
	cancellation(data){
		this.coopId = data.id
		this.cancellationModal = true
	}

	// 确定作废
	confirmCancellation(){
		this.cancellationLoading = true;
		this.mainService
		.coopTypeConfig('rmvData', 'pathologyForm', [this.coopId])
		.subscribe((data) => {
			this.cancellationLoading = false;
			this.cancelCancellation();
			if (data["status"] == 200) {
				this.showPromptModal("作废", true, "", "application");
			} else {
				this.showPromptModal("作废", false, data["msg"]);
			}
		});
	}

	// 取消作废
	cancelCancellation(){
		this.cancellationModal = false
	}

	hideModal(){
		this.multiDialog = false
	}

	pathologyDetailCancel(){
		this.pathologyDetailModal = false
	}

	pathologyCancel(){
		this.pathologyModal = false
	}
  // 切换综合日志和一键报修
  smallTabs = [];
  smallTabId = 2; //默认显示一键报修
  changeSmallTab(id) {
    this.smallTabId = id;
    if (id == 1) {
      this.listDeptOrderRecord();
    } else if (id == 2) {
      this.getQuickBxlb();
    }
  }
  // 获取当日建单总数
  todayNum = ""; //当日建单总数
  getTodayNum() {
    this.mainService
      .getFetchDataList("nurse", "workOrder", {
        idx: 0,
        sum: 1,
        workOrder: {
          createDept: this.loginUser.dept.id,
          startTime1: format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss"),
          endTime1: format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss"),
        },
      })
      .subscribe((data) => {
        if (data.status == 200) {
          this.todayNum = data.totalNum || 0;
        }
      });
  }

  // 获取报修区域（所属院区）
  // areas: any = []; //区域（所属院区）列表
  // getArea() {
  //   this.areas = [];
  //   this.mainService
  //     .fetchListBx("area", { idx: 0, sum: 1000 })
  //     .subscribe((result: any) => {
  //       if (result.status == 200) {
  //         this.areas = result.list;
  //         if (this.areas.length) {
  //           this.bxForm.controls.hospital.setValue(this.areas[0].id);
  //         } else {
  //           this.bxForm.controls.hospital.setValue(null);
  //         }
  //       }
  //     });
  // }
  //根据区域(所属院区)获取地点(楼栋)
  places: any = []; //地点（楼栋）列表
  getPlace(buildingId) {
    this.places = [];
    this.mainService
      .fetchListBx("place", {
        idx: 0,
        sum: 1000,
        place: { area: { id: buildingId } },
      })
      .subscribe((result: any) => {
        if (result.status == 200) {
          this.places = result.list;
          if (this.places.length) {
            this.bxForm.controls.building.setValue(this.places[0].id);
          } else {
            this.bxForm.controls.building.setValue(null);
          }
        }
      });
  }

  btnLoading: boolean = false; //确认按钮loading状态
  workOrderRemark = ""; //备注
  workOrderRemark1 = ""; //备注
  workOrderRemark2 = ""; //备注
  workOrderRemarkTips = ""; //备注提示
  workOrderRemarkTips1 = ""; //备注提示
  workOrderRemarkTips2 = ""; //备注提示
  customRemarks = []; //备注快速输入
  customRemarks1 = []; //备注快速输入
  customRemarks2 = []; //备注快速输入
  // 添加备注
  addRemarks(item) {
    this.remarksEle.nativeElement.focus();
    this.workOrderRemark += item;
  }
  // 添加备注
  addRemarks1(item) {
    this.remarksEle1.nativeElement.focus();
    this.workOrderRemark1 += item;
  }
  // 添加备注
  addRemarks2(item) {
    this.remarksEle2.nativeElement.focus();
    this.workOrderRemark2 += item;
  }
  // 立即执行
  coopItem: any = {};
  execModal: boolean = false;
  // 打开立即执行模态框
  openExecModal(item) {
    this.coopItem = item;
    // 是否允许提前执行
    if(item.taskType.executeSwitch == 1){
      this.execModal = true;
    }else{
      this.showPromptModal("操作", false, "相关任务会到点执行，无需立即执行。有问题请联系相关科室！");
    }
  }
  // 确认立即执行
  confirmExec() {
    this.btnLoading = true;
    this.mainService.executeNow(this.coopItem.id, {userId: this.userId}).subscribe((result: any) => {
      this.closeExecModal();
      if (result.status == 200) {
        this.showPromptModal("立即执行", true, "");
        this.getOrderList();
      } else {
        this.showPromptModal("立即执行", false, result.msg);
      }
    });
  }
  // 关闭立即执行模态框
  closeExecModal() {
    this.execModal = false;
  }
  // 快捷配置背景色
  backColorComputed(icon){
    if(icon === 'transport-biaobenxinxi'){
      return 'specimen';
    }else if(icon === 'transport-shuyeguanli'){
      return 'blood';
    }else if(icon === 'transport-yaopinshuju'){
      return 'drugbag';
    }else if(icon === 'transport-baoxiu'){
      return 'incident';
    }else if(icon === 'transport-peihuguanli'){
      return 'inspect';
    }else if(icon === 'transport-dabao'){
      return 'specimenPackage';
    }else{
      return '';
    }
  }
  // 获取快捷配置列表
  pagePermissionConfigList: any[] = []; //表格数据
  getPagePermissionConfigList() {
    let data = {
			idx: 0,
			sum: 99999,
			pagePermissionConfig: {
        hosId: this.currentHospital.id,
        active: 1,
        taskTypeDeptId: this.loginUser.dept.id,
      },
		};
		this.mainService
			.getFetchDataList("simple/data", "pagePermissionConfig", data)
			.subscribe((data) => {
				let pagePermissionConfigList = data.list || [];
        pagePermissionConfigList.forEach(v => {
          if(v.urgentIds){
            let urgentIds = v.urgentIds.split(',');
            v.urgentFlag = urgentIds.some(v => v == 1);
            v.ordinaryFlag = urgentIds.some(v => v == 2);
          }
        })
        this.pagePermissionConfigList = pagePermissionConfigList;
			});
  }
  // 获取系统配置
  isShowBx = false;// 护士端是否显示报修
  isAssign = false;// 是否护士指定人员
  getItsmIncident() {
    let postData = { idx: 0, sum: 100, hospitalConfig: { hosId: this.currentHospital.id } };
    this.mainService.getFetchDataList("simple/data", "hospitalConfig", postData).subscribe((result) => {
        if (result.status == 200) {
          this.isShowBx = result.list.find(v => v.key == 'hos_itsmIncident').value == 1;
          this.isAssign = result.list.find(v => v.key == 'nurseSendOrder').value == 1;
          if (this.isShowBx && this.coopBtns.repairList && !this.checkedTableType) {
            // 初始化默认显示第一个
            console.log(this.tabPermission)
            // if(this.tabPermission.length){
            //   this.checkedTableType = (this.tabPermission[0] && this.tabPermission[0].system) ? 'other' : this.tabPermission[0].id;
            // }else if(this.coopBtns.suggestionBox){
            //   this.checkedTableType = 'advice';
            //   this.checkTable(this.checkedTableType);
            // }else if(this.coopBtns.surgery){
            //   this.checkedTableType = 'surgery';
            //   this.checkTable(this.checkedTableType);
            // }else if(this.coopBtns.outpatientHelpAppointment){
            //   this.checkedTableType = 'outpatientHelpAppointment';
            //   this.checkTable(this.checkedTableType);
            // }else if(this.coopBtns.inquiryOfHistoricalSpecimens){
            //   this.checkedTableType = 'historySpecimen';
            //   this.checkTable(this.checkedTableType);
            // }else if(this.coopBtns.historicalMedicineListInquiry){
            //   this.checkedTableType = 'historyDrugsbag';
            //   this.checkTable(this.checkedTableType);
            // }else if(this.coopBtns.repairList && this.isShowBx){
            //   this.checkedTableType = 'bxlb';
            //   this.checkTable(this.checkedTableType);
            // }
            this.smallTabs = [
              { id: 1, name: "综合日志" },
              { id: 2, name: "一键报修" },
            ];
            this.smallTabId = 2;
            this.getQuickBxlb();
            this.getBxlb(this.bxlbPageIndex, true);
          } else {
            this.smallTabs = [{ id: 1, name: "综合日志" }];
            this.smallTabId = 1;
            this.listDeptOrderRecord();
          }
        }
      });
  }
  // 派单,flag 0是待抢单指派，1是待到达指派
  allotWorker(id, stateId, flag?) {
    if (flag == 1) {
      this.router.navigateByUrl("nurse/allotWorker/" + id + "/" + stateId + "/1/" + this.currentHospital.id);
    } else {
      this.router.navigateByUrl("nurse/allotWorker/" + id + "/" + stateId + "/0/" + this.currentHospital.id);
    }
  }
  //获取检查页面任务类型
  getInspectAndPatientTransportConfigTasktype() {
    let postData = {
      idx: 0,
      sum: 10,
      taskType: {
        simpleQuery: true,
        hosId: {
          id: this.currentHospital.id
        },
        associationType: {
          key:"association_types",
          value: 'inspect'
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskType", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          let tasktype:any = result.list[0] || {};
          this.getInspectAndPatientTransportConfig(tasktype);
        }
      });
  }
  // 获取检查页面信息配置
  getInspectAndPatientTransportConfig(tasktype) {
    let postData = {
      idx: 0,
      sum: 10,
      taskTypeConfig: {
        taskTypeDTO: {
          hosId: {
            id: this.currentHospital.id
          },
          associationType: tasktype.associationType
        }
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "taskTypeConfig", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          let inspectAndPatientTransportConfig = result.list[0] || {};
          this.inspectAndPatientTransportConfig = {...this.inspectAndPatientTransportConfig, ...inspectAndPatientTransportConfig};
					
          // 是否显示排队信息
          if(this.inspectAndPatientTransportConfig.queuingInformation == 1){
            this.getQueuingInformation();
          }

          this.initForm();
        }
      });
  }
  // 获取排队信息
  queuingInformationList:any[] = [];
  getQueuingInformation() {
    this.mainService
      .coopWorkerOrder("queuingInformation", {})
      .subscribe((result) => {
        if(result.status == 200){
          this.queuingInformationList = result.datalist || [];
        }
      });
  }
  // 获取护士端更新提示
  updateTipsForNurses = "";
  getUpdateTipsForNurses() {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "updateTipsForNurses" },
    };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.updateTipsForNurses = result.list[0].valueconfig;
        }
      });
  }
  // 获取护士工单列表刷新速度
  getRefreshNurseWorkOrderTime() {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "refreshNurseWorkOrderTime" },
    };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.orderListTimeConst = result.list[0].valueconfig;
          // 工单列表倒计时 start
          this.orderListTime = this.orderListTimeConst;
          clearInterval(this.orderListTimer);
          this.orderListTimer = setInterval(() => {
            this.orderListTime--;
            if (this.orderListTime === 0) {
              this.orderListTime = this.orderListTimeConst;
              this.getOrderList();
            }
          }, 1000);
          // 工单列表倒计时 end
        }
      });
  }
  // 获取标本按钮
  specimenButton = "";
  getSpecimenButton() {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "specimenButton" },
    };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.specimenButton = result.list[0].valueconfig;
        }
      });
  }
  // 获取护士端弹窗的配置
  // (1)	当用户设置为正数时，用户必须查看此窗体指定秒数。
  // (2)	当用户设置为负数时，用户可点击知道了也可倒计时自动关闭。
  // (3)	如果用户填写0则为无自动关闭和强制查看时间。
  getCloseTimeFlag() {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "nurseDeptSwitchTip" },
    };
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.closeTimeFlag = result.list[0].valueconfig - 0;
          this.changeKs();
        }
      });
  }
	// 获取资产报修是否开启
	cmdbRepair:Boolean = false;
	getCmdbRepairFlag() {
	  let postData = {
	    idx: 0,
	    sum: 1,
	    systemConfiguration: { keyconfig: "cmdbRepair" },
	  };
	  this.mainService
	    .getFetchDataList("simple/data", "systemConfiguration", postData)
	    .subscribe((result) => {
	      if (result.status == 200) {
					if(result.list[0].valueconfig==1){
						this.cmdbRepair = true
						this.getAssetData();
					}else{
						this.cmdbRepair = false
					}
	      }
	    });
	}

	changeCommonInp(e) {
		return
	  this.changeCommonInpSubject.next(e);
	}
	changeApplyCategory(e){
	  console.log(111, e)
		if(e){
		  // 根据故障现象带出故障描述
		  if(this.validateBxForm.value.description){
				this.validateBxForm.controls.description.setValue(this.validateBxForm.value.description +';'+this.applicationCategoryList.find(v => v.id == e).mutiCategory)
		  }else{
				this.validateBxForm.controls.description.setValue(this.applicationCategoryList.find(v => v.id == e).mutiCategory)
		  }
		}
	}
	// 故障现象列表
	applicationCategoryList:any[] = [];
	searchApplicationCategory(keyWord?) {
		let item = this.assetData.find(i=> i.id == this.validateBxForm.value.assetId)
		if(!item.assetProductDTO.incidentCategoryIds){
			return
		}
		let postData = {
			incidentCategoryIds: item.assetProductDTO.incidentCategoryIds,
	   //  category: {
	   //    category: keyWord,
	   //    selectType: 'mutlQuery',
				// hierarchy: 3,//只差有三级的故障现象列表
	   //  },
	  };
	  console.log(postData);
	  this.isLoading = true;
	  this.mainService
	    .incidentPost("listIncidentCategory", postData)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.applicationCategoryList = data.data;
	      }
	    });
	}

	changeAsset(e){
		this.changeAssetInpSubject.next(e);
	}
	// 选择资产
	changeAssetData(e){
		this.validateBxForm.controls.category.setValue(null)
		this.searchApplicationCategory();
	}

	// 获取资产列表
	assetData:any = [];
	getAssetData(name?){
		let data = {
		  idx: 0,
		  sum: 20,
		  asset: {
		    downHosId: this.currentHospital.id,
		    name: name
		  },
		};

		this.mainService
		  .getFetchDataList("simple/data", "asset", data)
		  .subscribe((data) => {
		    if (data.status == 200) {
		      this.assetData = data.list;
		    }
		  });
	}

  //获取综合日志
  rLoading = false;
  listDeptOrderRecords: any = [];
  listDeptOrderRecord() {
    this.rLoading = true;
    this.mainService
      .listMsgByMain("listDeptOrderRecord", { deptId: this.loginUserDeptId })
      .subscribe((result) => {
        this.rLoading = false;
        if (result["status"] == 200) {
          this.listDeptOrderRecords = result["data"].slice(0, 15);
        }
      });
  }
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 查看药单历史记录
  historyDPromptModalShow = false; //药单历史记录弹窗开关
  drugsBagId = ""; //查看历史记录携带
  viewDrugsbagHistory(data) {
    this.drugsBagId = data.id;
    this.historyDPromptModalShow = true;
  }
  // 关闭药单历史记录弹窗
  closeModelHistoryDrugsbag(e) {
    this.historyDPromptModalShow = JSON.parse(e).show;
  }
  // 查看报修信息
  detailBx(data){
    this.router.navigateByUrl("nurse/detailBx/" + data.id);
  }

  // 查看报修信息弹窗
  bxPromptModalShow = false; //弹窗开关
  bData = ""; //查看详情携带所有数据
  viewBx(data) {
    this.bData = data;
    this.bxPromptModalShow = true;
  }
  // 关闭报修信息弹窗
  closeModelBx(e) {
    this.bxPromptModalShow = JSON.parse(e).show;
  }
  // 护士端患者信息列表，鼠标移入姓名展示最近一条检查信息
  recentInfo = "";
  recentInfoTimer = null;
  recentInfoNum = 0;
  isRemand = true; //自动送回
  yyTime = null; //预约时间-患者列表
  yyTimeZy = null; //预约时间-患者列表-患者其他服务
  yyDate = null; //预约日期-陪检
  yyDateZy = null; //预约日期-转运
  getRecentInfo(patientCode) {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    this.recentInfo = "";
    clearTimeout(this.recentInfoTimer);
    this.recentInfoTimer = setTimeout(() => {
      this.recentInfoNum++;
      this.mainService
        .listMsgByMain("workOrder/findInspectRecently", { patientCode })
        .subscribe((result) => {
          this.recentInfoNum--;
          if (result["status"] == 200 && this.recentInfoNum === 0) {
            this.recentInfo = result["data"]["info"];
          } else {
            this.recentInfo = "";
          }
        });
    }, 500);
  }
  // 获取患者陪检任务类型（只有一个）的信息
  getTaskTypeByInspection() {
    const list = {
      idx: 0,
      sum: 1,
      taskType: {
        patientInspectQuery: true,
        hosIds: this.currentHospital.id + "",
        associationType: {
          id: 260,
        },
      },
    };
    return this.mainService.getFetchDataList("configuration", "taskType", list);
  }
  //修改预约建单时间的日期
  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 [];
        }
      };
    }
  }
  // 关闭其他建单保存结果
  closeModel(e) {
    console.log(e);
    if (e === "other" || e === "ordinary") {
      this.osComponentRef2.osInstance().scroll({ x: 0, y: this.positionY });
      this.getOrderList();
    } else if (e === "bb") {
      this.getOrderList();
      this.getSpecimenWorkOrderMsg();
    } else if (e === "application"){
			this.getPathologyData()
		}
  }

  // 其他建单
  selectOtherId; //选中的id
  otherSearch = ""; //搜索的关键词
  oLoading = false;
  nLoading = false;
  positionY = 0; //记录其他建单Y轴滚动距离
  otherClick(item) {
    this.osComponentRef2 && (this.positionY = this.osComponentRef2.osInstance().scroll().position.y); //内容滚动的距离
    this.selectOtherId = item.id;
    this.newShortcutOrder(item, "other");
    this.account = null;
    this.userAccount = null;
  }
  selectIncidentId; //选中的id
  incidentClick(item) {
    this.positionY = this.osComponentRef10.osInstance().scroll().position.y; //内容滚动的距离
    this.selectIncidentId = item.id;
    this.bxForm.controls.content.setValue(item.mutiCategory);
  }
  //搜索
  otherNum = 0;
  otherSearchChange() {
    this.otherSearchChangeSubject.next(this.otherSearch);
  }
  // 切换科室
  changeKs() {
    this.hsPromptModalShow = true;
    // (1)	当用户设置为正数时，用户必须查看此窗体指定秒数。
    // (2)	当用户设置为负数时，用户可点击知道了也可倒计时自动关闭。
    // (3)	如果用户填写0则为无自动关闭和强制查看时间。
    if (this.closeTimeFlag === 0) {
      return;
    }
    this.closeTime = Math.abs(this.closeTimeFlag);
    clearInterval(this.timerCloseTime);
    this.timerCloseTime = setInterval(() => {
      this.closeTime = Math.max(--this.closeTime, 0);
      if (this.closeTime === 0) {
        if (this.closeTimeFlag <= 0) {
          this.hsPromptModalShow = false;
        }
        clearInterval(this.timerCloseTime);
      }
    }, 1000);
  }
  // 判断登录是否已失效
  initLogin() {
    let that = this;
    if (!localStorage.getItem("user")) {
      that.message.error("您的登录已失效，请重新登录！", {
        nzDuration: 3000,
      });
      setTimeout(() => {
        that.router.navigateByUrl("login");
      }, 2000);
      return;
    }
  }

  // 连接websocket
  getWebsocket() {
    let that = this;
    this.webs
      .connectWs(http.nurseWs, { userCount: that.loginUser.account })
      .subscribe((data) => {
        if (data && data.content) {
          that.createBasicNotification(data);
        }
      });
  }

  // 每隔一分钟刷新标本信息
  msgTimerId: any;
  refreshSpecimenWorkOrderMsg() {
    this.msgTimerId = setInterval(() => {
      this.getSpecimenWorkOrderMsg();
      this.getPatientInspectCountMsg();
      this.getSpePackageCountMsg();
    }, 60000);
  }

  // 工单列表筛选
  getOrderSelectList() {
    let that = this;
    that.mainService
      .getDictionary("list", "association_types")
      .subscribe((data) => {
        that.orderSelectList = data || [];
      });
  }

  // 急标普标数量
  getSpecimenWorkOrderMsg() {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    let that = this;

    that.mainService
      .postCustom("nurse", "getSpecimenWorkOrderMsg", {
        deptId: JSON.parse(localStorage.getItem("user")).user.dept.id,
      })
      .subscribe((data) => {
        that.specimenWorkOrderMsg = data;
      });
  }

  // 护士端-批量陪检图标下两个数字
  patientInspectCountMsg: any = {};
  getPatientInspectCountMsg() {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    let that = this;

    that.mainService
      .getPatientInspectCount({
        deptId: JSON.parse(localStorage.getItem("user")).user.dept.id,
      })
      .subscribe((data) => {
        that.patientInspectCountMsg = data;
      });
  }

  // 护士端-标本打包图标下两个数字
  specimenPackageCountMsg: any = {};
  getSpePackageCountMsg() {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    let that = this;

    that.mainService
      .getSpePackageCount({
        deptId: JSON.parse(localStorage.getItem("user")).user.dept.id,
      })
      .subscribe((data) => {
        that.specimenPackageCountMsg = data;
      });
  }

  // 手术提示信息
  surgeryLoading = false;
	now:any = new Date();
  getSurgeryWKOMsg() {
    if(this.currentDept.typeValue != 'surgery'){
      return;
    }
    let postData = {
      idx: 0,
      sum: 1,
      surgery: {
        applyDateStart: format(subHours(new Date(),12), "yyyy-MM-dd HH:mm:ss"),
        applyDateEnd: format(endOfDay(new Date()), "yyyy-MM-dd")+' '+'23:59:59',
        // hosId: this.currentHospital.id,
        surgeryDept: this.loginUserDeptId,
        state: {
          key: 'surgery_trans_state',
          value: 8
        }
      }
    }
    this.surgeryLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "surgery", postData)
      .subscribe((data) => {
        data.list = Array.isArray(data.list) ? data.list : [];
        this.surgeryLoading = false;
        this.surgeryWKOMsg = data.list[0] || {};
      });
  }

  // 获取手术配置信息
  surgeryField = null; //手术关联业务
  surgeryConfigs:any = {};
  // 送回苏醒室的运输过程终点科室信息
  surgeryCarryingCourse:any = null;
  surgeryCarryingCourseDepts: any[] = [];
  getSurgeryConfig() {
    this.mainService
      .getDictionary("list", "ordinary_field")
      .subscribe((data) => {
        this.surgeryField = data.find(v => v.value == 'surgery');
        if(this.surgeryField){
          let postData = {
            idx: 0,
            sum: 10,
            taskTypeConfig: {
              hosId: this.currentHospital.id,
              ordinaryField: this.surgeryField
            }
          };
          this.mainService
            .getFetchDataList("simple/data", "taskTypeConfig", postData)
            .subscribe((result) => {
              if (result.status == 200) {
                this.surgeryConfigs = result.list[0] || {};
                // 送回苏醒室开关开启 并且 有对应的任务类型
                if(this.surgeryConfigs.remandRecovery == 1 && this.surgeryConfigs.recoveryType){
                  this.surgeryCarryingCourse = this.surgeryConfigs.recoveryType.carryingCourses ? this.surgeryConfigs.recoveryType.carryingCourses.find(v => v.nodeId ? v.nodeId.value == 'finish' : false) : null;

                  // 运输过程终点科室配置是固定科室或者固定科室范围-苏醒室
                  if(this.surgeryCarryingCourse && (this.surgeryCarryingCourse.departmentStrategy.value == 2 || this.surgeryCarryingCourse.departmentStrategy.value == 3)){
                    this.surgeryCarryingCourseDepts = this.surgeryCarryingCourse.departmentDTOS || [];
                  }
                }
              }
            });
        }
      });
  }

  // 药品静配提示信息
  drugJpLoading = false;
  getJpDrugsWKOMsg() {
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      return;
    }
    let that = this;
    this.drugJpLoading = true;
    that.mainService
      .postCustom("nurse", "getJpDrugsWKOMsg", {})
      .subscribe((data) => {
        this.drugJpLoading = false;
        that.jpDrugsWKOMsg = data.data ? data.data : {};
        console.log(that.jpDrugsWKOMsg);
        if (
          that.jpDrugsWKOMsg.drugsInfoList &&
          that.jpDrugsWKOMsg.drugsInfoList.length
        ) {
          that.startSwiper(that.jpDrugsWKOMsg.drugsInfoList.length);
        }
        if (
          that.jpDrugsWKOMsg.jpInfoList &&
          that.jpDrugsWKOMsg.jpInfoList.length
        ) {
          that.startSwiper1(that.jpDrugsWKOMsg.jpInfoList.length);
        }
      });
  }

  // swiper 轮播图
  swiperTop: number = 0;
  moveId: any;
  index: number = 0;
  startSwiper(length) {
    let that = this;
    clearInterval(that.moveId);
    setInterval(() => {
      that.index++;
      clearInterval(that.moveId);
      that.moveId = setInterval(() => {
        if (that.swiperTop > -44 * that.index) {
          that.swiperTop--;
        }
        if (that.swiperTop <= length * -44) {
          that.swiperTop = 0;
          that.index = 0;
          clearInterval(that.moveId);
        }
      }, 20);
    }, 2000);
  }

  swiperTop1: number = 0;
  moveId1: any;
  index1: number = 0;
  startSwiper1(length) {
    let that = this;
    clearInterval(that.moveId1);
    setInterval(() => {
      that.index1++;
      clearInterval(that.moveId1);
      that.moveId1 = setInterval(() => {
        if (that.swiperTop1 > -44 * that.index1) {
          that.swiperTop1--;
        }
        if (that.swiperTop1 <= length * -44) {
          that.swiperTop1 = 0;
          that.index1 = 0;
          clearInterval(that.moveId1);
        }
      }, 20);
    }, 2000);
  }
  // 关注患者
  follow(data) {
    this.showCommonModal(
      data,
      data.focusPatient === 0
        ? "您将设置患者【" +
            data.patientName +
            "】为重点关注，后期此患者的相关检查将会自动建单通知支助中心"
        : "您将取消设置患者【" +
            data.patientName +
            "】为重点关注，后期此患者的相关检查将不会自动建单通知支助中心"
    );
  }
  // 通用提示模态框
  commonModal: boolean = false; //模态框
  loading4 = false;
  tipsMsg1: string; //提示框信息
  coop: any; //当前操作列
  showCommonModal(data: any, tipsMsg1: string) {
    this.commonModal = true;
    this.coop = data;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏模态框
  hideCommonModal() {
    this.commonModal = false;
  }
  // 确认
  confirmCommon() {
    this.commonModal = false;
    let postData = {
      patient: {
        id: this.coop.id,
        focusPatient: this.coop.focusPatient === 0 ? 1 : 0,
      },
    };
    this.loading4 = true;
    this.mainService.listMsgByMain("updData/patient", postData).subscribe(
      (result) => {
        this.loading4 = false;
        if (result["status"] == 200) {
          this.showPromptModal(
            result["data"].focusPatient === 0 ? "取消关注" : "关注",
            true,
            ""
          );
          this.getPatient(this.tabSearchCont);
        } else {
          this.showPromptModal(
            result["data"].focusPatient === 0 ? "取消关注" : "关注",
            false,
            ""
          );
        }
      },
      (err) => {
        this.loading4 = false;
        this.showPromptModal("操作", false, "");
      }
    );
  }
  // 初始化新增form表单
  initBxForm(content) {
    this.validateBxForm = this.fb.group({
      description: [content || null, [Validators.required]],
      building: [null, [Validators.required]],
      floor: [null, [Validators.required]],
      officeAddress: [null, [Validators.required]],
      contacts: [this.loginUser.name, [Validators.required]],
      contactsInformation: [this.loginUser.phone, [Validators.required]],
			assetId: [null, []],
			// category: [null, []],
    });
		if(this.cmdbRepair){
			this.validateBxForm.addControl(
				'assetId',
				new FormControl(null, [])
			);
			// this.validateBxForm.addControl(
			// 	'category',
			// 	new FormControl(null, [])
			// );
		}else{
			this.validateBxForm.removeControl('assetId');
			// this.validateBxForm.removeControl('category');
		}
    this.getDeptById(this.currentDept.id);
  }
  // 根据科室ID获取详情
  deptDto:any = {};
  getDeptById(id){
    this.mainService
      .getFetchDataList("simple/data", "department", {
        idx: 0,
        sum: 1,
        department: {
          id,
        }
      })
      .subscribe((data:any) => {
        let list = data.list || [];
        this.deptDto = list.length > 0 ? list[0] : {};
        console.log(this.deptDto);
        this.changeHosp();
        // 回显楼栋
        if(this.deptDto.building){
          this.validateBxForm.controls.building.setValue(this.deptDto.building.id);
        }

        // 回显楼层
        if(this.deptDto.floor){
          this.validateBxForm.controls.floor.setValue(this.deptDto.floor.id);
        }
      });
  }
  // 切换院区选项
  buildings: any = []; //楼栋
  changeHosp() {
    this.validateBxForm.controls.building.setValue(null);
    this.buildings = [];
    let data = {
      idx: 0,
      sum: 9999,
      building: {
        hosId: this.deptDto.hospital.id,
      }
    };
    this.mainService
      .getFetchDataList("simple/data", "building", data)
      .subscribe((data:any) => {
        this.buildings = data.list || [];
        this.floors = [];
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
      });
  }

  // 切换楼栋信息
  floors: Array<any> = []; //楼层
  floorLoading: boolean = false;
  changeBuilding(buildingId) {
    if(!buildingId){
      return;
    }
    this.validateBxForm.controls.floor.setValue(null);
    this.validateBxForm.controls.officeAddress.setValue(null);
    this.floors = [];

    let data = {
      idx: 0,
      sum: 9999,
      floor: {
        buildId: buildingId,
      }
    };
    this.floorLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "floor", data)
      .subscribe((data:any) => {
        this.floorLoading = false;
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.floors = data.list || [];
      });
  }
  // 是否确定报修模态框
  bxModal: boolean = false; //模态框
  loading6 = false;
  coopBx: any; //当前操作列
  validateBxForm: FormGroup; //新增/编辑表单
  showBxModal(data?) {
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.bxModal = true;
    this.coopBx = data || {};
		this.fileList = [];
    this.initBxForm(this.coopBx.content);
  }
  // 隐藏模态框
  hideBxModal() {
    this.bxModal = false;
		this.fileList = [];
  }
  // 确认
  confirmBx() {
    for (const i in this.validateBxForm.controls) {
      this.validateBxForm.controls[i].markAsDirty();
      this.validateBxForm.controls[i].updateValueAndValidity();
    }
    if (this.validateBxForm.invalid){
      this.message.error('请填写必填字段！');
      return;
    };
    if (!this.deptDto.id){
      this.message.error('数据异常，无法建单！');
      return;
    };
    this.showReqModal();
  }

  // 报修
  // type, 1是，0否
  async confirmBxNext(type){
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    if(type == 1){
      this.btnLoading = true;
      let loginUser:any = cloneDeep(this.loginUser);
			// loginUser.upType = "changeDept";
      if(this.deptDto.hospital){
        loginUser.hospital = { id: this.deptDto.hospital.id };
      }
      if(this.deptDto){
        loginUser.dept = {id: this.deptDto.id};
      }
      if(this.validateBxForm.value.contacts){
        loginUser.name = this.validateBxForm.value.contacts;
      }
      // if(this.validateBxForm.value.floor){
      //   loginUser.place = {id: this.validateBxForm.value.floor, area: { id: this.validateBxForm.value.building }};
      // }
      // if(this.validateBxForm.value.officeAddress){
      //   loginUser.houseNumber = this.validateBxForm.value.officeAddress;
      // }
      if(this.validateBxForm.value.contactsInformation){
        loginUser.phone = this.validateBxForm.value.contactsInformation;
      }
      let result:any = await this.mainService.coopData("updData", "user", { user: loginUser }).toPromise();
      console.log(result);
      if(result.status != 200){
        this.hideReqModal();
        this.btnLoading = false;
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.message.error(result.msg);
        return;
      }
    }else{
      this.cancenlLoading = true;
    }
    this.mainService.getDictionary("list", "incident_source").subscribe((source:any) => {
      let incidentSourceList = source || [];
      let pc = incidentSourceList.find(v => v.value === 'pc');
      this.mainService.getDictionary("list", "repair_incident_type").subscribe((result) => {
        let repairIncidentTypeList = result || [];
        let repairIncidentType = repairIncidentTypeList.find(v => v.value === 'dept');
        if (repairIncidentType) {
          let postData: any = {
            incident: {
              repairIncidentType,
              place: this.validateBxForm.value.floor ? { id: this.validateBxForm.value.floor } : undefined,
              department: { id: this.deptDto.id},
              description: this.validateBxForm.value.description,
              houseNumber: this.validateBxForm.value.officeAddress,
              contacts: this.validateBxForm.value.contacts,
              contactsInformation: this.validateBxForm.value.contactsInformation,
              hosId: this.deptDto.hospital.id,
              source: pc,
              fromWx: true,
              requester: this.loginUser,
              acceptUser: this.loginUser,
              deleteFlag: 0,
							assetId: this.validateBxForm.value.assetId || undefined,
							// category: this.validateBxForm.value.category ? { id: this.validateBxForm.value.category } : undefined,
            },
          };
          // if (this.coopBx.category) {
          //   postData.incident.category = this.coopBx.categoryDTO;
          // }
          this.mainService.flowPost("incident/task/request", postData).subscribe((res) => {
            this.btnLoading = false;
            this.cancenlLoading = false;
            this.message.remove(this.maskFlag);
            this.maskFlag = false;
            this.bxModal = false;
            this.hideReqModal();
            if ((res as any).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, res.data.id);
								})
							}
              this.showPromptModal("提交", true, "");
              this.checkTable("bxlb");
            } else {
              this.showPromptModal("提交", false, (res as any).msg);
            }
          });
        } else {
          this.btnLoading = false;
          this.showPromptModal("提交", false, "缺少【科室内报修】数据字典");
        }
      });
    })
  }

  // 获取星级
  degrees = [];
  getDegrees() {
    this.iLoading = true;
    this.mainService.getDictionary("list", "incident_degree").subscribe((data: any) => {
      this.iLoading = false;
      this.degrees = data || [];
    });
  }
  iLoading = false;
  // 获取当前登录人科室任务类型信息
  othersList: any = []; // 其他一键建单列表
  bbMsg: any = {}; //标本一键建单
  patientMsgList: any = []; // 患者转运，患者陪检一键建单
  tabFlag = true; //页面初始化获取一次患者陪检的任务类型信息
  allowUrgentFlag = false; //检查列表的患者陪检类型是否允许加急
  tabPermission:any = []; //tab自定义
  tabPermissionTpl:any = []; //tab自定义模板
  getDeptTaskType(search?, clear?) {
    let that = this;
    this.otherNum++;
    this.oLoading = true;
    let postData = {
      deptId: that.loginUserDeptId,
    };
    if (search !== undefined) {
      postData["taskName"] = search;
      postData["tabId"] = this.checkedTableType == 'other' ? undefined : this.checkedTableType;
    }
    that.mainService
      .postCustom("nurse", "getDeptTaskType", postData)
      .subscribe((data) => {
        this.otherNum--;
        if (this.otherNum === 0) {
          this.oLoading = false;
        }
        if (search === undefined) {
          that.deptTaskTypeRules = data.data;
          that.getOrderList();
          if(that.deptTaskTypeRules.openPatientTransport){
            // 手术权限
            that.getSurgeryWKOMsg();
          }
          if (
            that.deptTaskTypeRules.openInspection ||
            that.deptTaskTypeRules.openPatientTransport
          ) {
            this.getPatientInspectCountMsg();
            // 陪检权限或转科权限
            if (this.tabFlag) {
              this.tabFlag = false;
              this.getTaskTypeByInspection().subscribe((result) => {
                console.log(result);
                if (result.list && result.list.length > 0) {
                  this.appointmentBuildFlag =
                    result.list[0].appointmentSwitch + ""; //是否开启护士端预约建单
                  // this.leadTime = result.list[0].appointmentTime; //生效时长
                  this.leadTime = 0; //生效时长
                  this.followFlag = result.list[0].focusSwitch + ""; //是否开启护士端重点关注
                  this.allowUrgentFlag =
                    result.list[0].allowUrgent == 1 ? true : false; //是否允许加急（检查列表）
                } else {
                  this.appointmentBuildFlag = "0"; //是否开启护士端预约建单
                  this.leadTime = 0; //生效时长
                  this.followFlag = "0"; //是否开启护士端重点关注
                  this.allowUrgentFlag = false; //是否允许加急（检查列表）
                }
                this.pLoading = true;
                that.getPatient();
              });
            } else {
              that.getPatient();
            }
          }
          if (that.deptTaskTypeRules.openSpecimen) {
            // 标本权限
            that.getSpecimenWorkOrderMsg();
          }
          if (
            that.deptTaskTypeRules.openStaticDistribution ||
            that.deptTaskTypeRules.openDrugsBag
          ) {
            // 药品静配权限
            that.getJpDrugsWKOMsg();
          }

          that.getSpePackageCountMsg();
        }

        if(data.data.tabPermission && Array.isArray(data.data.tabPermission.data)){
          if (search !== undefined) {
            let tabPermission = [];
            tabPermission = this.tabPermissionTpl.map(v => {
              let obj = data.data.tabPermission.data.find(vv => vv.id == v.id);
              if(obj){
                return obj;
              }else{
                return v;
              }
            })
            this.tabPermission = tabPermission.sort((a,b) => a.orders - b.orders);
          }else{
            this.tabPermission = data.data.tabPermission.data.sort((a,b) => a.orders - b.orders);
            this.tabPermissionTpl = data.data.tabPermission.data.sort((a,b) => a.orders - b.orders).map(v => ({...v, taskTypeList: []}));
          }
        }else{
          this.tabPermission = this.tabPermissionTpl.length ? cloneDeep(this.tabPermissionTpl) : [];
        }
        if(!this.coopBtns.buildOrdersForOtherTasks){
          this.tabPermission = this.tabPermission.filter(v => !v.system);
        }
        // 初始化默认显示第一个
        if(search === undefined && !this.checkedTableType){
          console.log(this.tabPermission)
          if(this.tabPermission.length){
            this.checkedTableType = (this.tabPermission[0] && this.tabPermission[0].system) ? 'other' : this.tabPermission[0].id;
          }else if(this.coopBtns.suggestionBox){
            this.checkedTableType = 'advice';
            this.checkTable(this.checkedTableType);
          }else if(this.coopBtns.surgery){
            this.checkedTableType = 'surgery';
            this.checkTable(this.checkedTableType);
          }else if(this.coopBtns.outpatientHelpAppointment){
            this.checkedTableType = 'outpatientHelpAppointment';
            this.checkTable(this.checkedTableType);
          }else if(this.coopBtns.inquiryOfHistoricalSpecimens){
            this.checkedTableType = 'historySpecimen';
            this.checkTable(this.checkedTableType);
          }else if(this.coopBtns.historicalMedicineListInquiry){
            this.checkedTableType = 'historyDrugsbag';
            this.checkTable(this.checkedTableType);
          }else if(this.coopBtns.repairList && this.isShowBx){
            this.checkedTableType = 'bxlb';
            this.checkTable(this.checkedTableType);
          }
        }else{
          console.log('this.checkedTableType', this.checkedTableType);
          this.checkTable(this.checkedTableType);
        }
        this.othersList = {};
        this.tabPermission.forEach(v => {
          if(v.system){
            that.othersList['other'] = [];
          }else{
            that.othersList[v.id] = v.taskTypeList || [];
          }
        })

        if (data.data.allTaskTypes) {
          that.patientMsgList = [];

          data.data.allTaskTypes.forEach((e) => {
            if (e.associationType.value == "other") {
              if(that.othersList['other']){
                that.othersList['other'].push(e);
              }else{
                that.othersList['other'] = [e];
              }
            } else if (e.associationType.value == "specimen") {
              that.bbMsg = e;
            } else if (
              e.associationType.value == "patientTransport" ||
              e.associationType.value == "inspect"
            ) {
              that.patientMsgList.push(e);
            }
          });
          // if (clear === "clear") {
          //   this.otherSearch = "";
          //   this.workOrderRemark = "";
          //   this.customRemarks = [];
          //   this.historyCustomRemarks = [];
          //   let obj = that.othersList.find(
          //     (item) => item.id == this.selectOtherId
          //   );
          //   obj && this.otherClick(obj);
          // }
          console.log(this.selectOtherId);
          if (!this.selectOtherId) {
            if (that.othersList[that.checkedTableType] && that.othersList[that.checkedTableType].length) {
              this.selectOtherId = that.othersList[that.checkedTableType][0].id;
              let obj = that.othersList[that.checkedTableType].find(
                (item) => item.id == this.selectOtherId
              );
              obj && this.otherClick(obj);
            } else {
              this.selectOtherId = null;
            }
          }
        }
      });
  }
  // 工号输入搜索
  searchAccount(e) {
    this.searchAccountSubject.next(e);
  }

  // 根据工号获取用户
  account = null;
  accountList = [];
  isLoading:boolean = false;
  getAccountList(key = ''): void {
    let postData = {
      idx: 0,
      sum: 10,
      user: {
        account: key,
        hospital: {
          id: this.currentHospital.id
        }
      }
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.accountList = data.list || [];
      });
  }

  // 目标科室输入搜索
  searchDept(type, msg, e) {
		this.getDeptList(type, msg, e)
  }
  // 获取科室
  getDeptList(type, msg, key?): void {
    // 返回值的status是201 则是默认发起科室
    // 返回值的status是202 则是固定科室范围
    // 返回值的status是203 则是固定科室
    // 返回值的status是204 则是自主填写
    // 返回值的status是205 则是固定科室类型
		key = key.toUpperCase()
		console.log('hahhah =======', key)
    if (
      (type == "start" && msg.start.start.departmentStrategy == 202) ||
      (type == "target" && msg.end.end.departmentStrategy == 202)
    ) {
			let data = [];
			let postData = null
			if(this.patientModal){
				postData = this.patientQuery
			}else{
				postData = {
				  taskTypeId: this.msgId
				};
			}
			if(type == "start"){
				this.mainService
				.postCustom("nurse", "workOrder/buildTrip", postData)
				.subscribe((result) => {
					let arr = result.start.start.list;
					arr.forEach(i=>{
            if(i.inputcode){
                i.inputcode = i.inputcode.toUpperCase()
              if(this.deptDisplay == 2){
                i.deptalias = i.deptalias + '('+i.inputcode+')'
              }else{
                i.dept = i.dept + '('+i.inputcode+')'
              }
            }
					})

					if(key!=''){
						if(this.deptDisplay ==2){
							data = arr.filter(i=>i.deptalias.indexOf(key) !=-1)
						}else{
							data = arr.filter(i=>i.dept.indexOf(key) !=-1)
						}
						msg.start.start.list = data
					}else{
						msg.start.start.list = arr
					}
				});
			}else{
				this.mainService
				.postCustom("nurse", "workOrder/buildTrip", postData)
				.subscribe((result) => {
					let arr = result.end.end.list;
					arr.forEach(i=>{
            if(i.inputcode){
              i.inputcode = i.inputcode.toUpperCase()
              if(this.deptDisplay == 2){
                i.deptalias = i.deptalias + '('+i.inputcode+')'
              }else{
                i.dept = i.dept + '('+i.inputcode+')'
              }
            }
					})

					if(key!=''){
						if(this.deptDisplay ==2){
							data = arr.filter(i=>i.deptalias.indexOf(key) !=-1)
						}else{
							data = arr.filter(i=>i.dept.indexOf(key) !=-1)
						}
						msg.end.end.list = data
					}else{
						msg.end.end.list = arr
					}
				});
			}
      return; //固定科室范围禁用搜索
    }
    let postData: any = {
      idx: 0,
      sum: 20,
      department: {
        searchType: 1,
        cascadeHosId: this.currentHospital.id
      },
    };
    if (key) {
      postData.department["keyWord"] = key;
    }
    if (type == "start" && msg.start.start.departmentStrategy == 205) {
      postData.department["type"] = { id: msg.start.start.startTypeId };
    } else if (type == "target" && msg.end.end.departmentStrategy == 205) {
      postData.department["type"] = { id: msg.end.end.endTypeId };
    }
    if (type == "start") {
      postData.department["ids"] = msg.start.deptIds || "";
    } else if (type == "target") {
      postData.department["ids"] = msg.end.deptIds || "";
    }
    postData.department.nurseSign = 1;
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((data) => {
        if (type == "target") {
					data.list.forEach(i=>{
            if(i.inputcode){
              i.inputcode = i.inputcode.toUpperCase()
              if(this.deptDisplay == 2){
                i.deptalias = i.deptalias + '('+i.inputcode+')'
              }else{
                i.dept = i.dept + '('+i.inputcode+')'
              }
            }
					})
          msg.end.end.list = data.list;
        } else if (type == "start") {
					data.list.forEach(i=>{
            if(i.inputcode){
              i.inputcode = i.inputcode.toUpperCase()
              if(this.deptDisplay == 2){
                i.deptalias = i.deptalias + '('+i.inputcode+')'
              }else{
                i.dept = i.dept + '('+i.inputcode+')'
              }
            }
					})
          msg.start.start.list = data.list;
        }
      });
  }

  // 切换左侧tab
  changeInfo() {
    if (
      !this.deptTaskTypeRules.openInspection &&
      !this.deptTaskTypeRules.openPatientTransport
    ) {
      return;
    }
    this.infoPageIdx = 1;
    this.getPatient();
  }

  // 获取患者信息
  snum = 0;
  getPatient(e?) {
    if ((this.currentDept.typeValue == "outpatientDept" || this.currentDept.typeValue == "checkRoom" || this.currentDept.typeValue == "outpatientService") && !this.tabSearchCont) {
      this.pLoading = false;
      this.patientList = [];
      this.infoLength = 0;
      return; //护士端如果登录后如果科室类型为“门诊科室”、“检验科室”、“门诊服务点”，默认不显示患者信息
    }
    this.pLoading = true;
    let postData = {
      idx: this.infoPageIdx - 1,
      sum: 10,
    };
    if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
      // 手术安排信息-手术室类型
      postData["surgery"] = {
        searchKey: e ? e : this.tabSearchCont,
        applyDateStart: format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss"),
        applyDateEnd: format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss"),
        hosId: this.currentHospital.id,
        surgeryDept: this.loginUserDeptId,
        state: {
          key: 'surgery_trans_state',
          value: 3
        }
      };
    }else if(this.currentDept.typeValue == 'recovery'){
      // 患者信息-复苏室类型
      postData["patient"] = {
        keyWord: e ? e : this.tabSearchCont,
      };
      // 查询父级科室患者
      postData["patient"]["parentIdOnly"] = true;
      postData["patient"]["recoveryDept"] = this.loginUserDeptId;
      postData["patient"]["recoveryDeptDTO"] = {keyWord: '1'};
    }else if(this.currentDept.typeValue == "checkRoom2"){
      // 患者信息
      postData["patient"] = {
        keyWord: e ? e : this.tabSearchCont,
      };
      // 查询父级科室患者
      postData["patient"]["parentIdOnly"] = true;
      if (this.tabSearchCont) {
        delete postData["patient"]["department"]; //搜索范围为全院在院患者
        delete postData["patient"]["checkTempDept"];
      } else {
        postData["patient"]["checkTempDept"] = { id: this.loginUserDeptId };
      }
    }else{
      // 患者信息
      postData["patient"] = {
        keyWord: e ? e : this.tabSearchCont,
      };
      // 查询父级科室患者
      postData["patient"]["parentIdOnly"] = true;
      if (
        this.currentDept.typeValue == "checkRoom2" ||
        this.currentDept.typeValue == "outpatientDept" ||
        this.currentDept.typeValue == "checkRoom" ||
        (this.currentDept.typeValue == 'surgery' && this.tabSearchCont)
      ) {
        delete postData["patient"]["department"]; //搜索范围为全院在院患者
      } else {
        postData["patient"]["department"] = { id: this.loginUserDeptId };
      }
    }

    this.snum++;
    this.mainService
      .getFetchDataList((this.currentDept.typeValue == 'surgery' && !this.tabSearchCont) ? "simple/data" : 'nurse', (this.currentDept.typeValue == 'surgery' && !this.tabSearchCont) ? "surgery" : 'patient', postData)
      .subscribe((data) => {
        this.snum--;
        if (data.list.length > 0) {
          data.list.forEach((item) => {
            if(this.currentDept.typeValue == 'surgery' && !this.tabSearchCont){
              if (item.patientDTO && item.patientDTO.focusPatient === undefined) {
                item.patientDTO.focusPatient = 0;
              }
            }else{
              if (item.focusPatient === undefined) {
                item.focusPatient = 0;
              }
            }
          });
        }
        this.patientList = data.list || [];
        if (this.snum === 0) {
          this.pLoading = false;
        }
        this.infoLength = data.totalNum || 0;
      });
  }

  // tab输入搜索节流阀
  searchTabInp(e) {
    if (
      !this.deptTaskTypeRules.openInspection &&
      !this.deptTaskTypeRules.openPatientTransport
    ) {
      return;
    }
    this.searchTabInpSubject.next(e);
  }
  // 下一日(陪检)
  nextDay() {
    this.yyDate = addDays(this.yyDate, 1);
    this.yyDateChange(this.yyDate);
  }
  // 下一日(转运)
  nextDayZy() {
    this.yyDateZy = addDays(this.yyDateZy, 1);
    this.yyDateChange(this.yyDateZy);
  }
  // 禁用日期(陪检)
  disabledyyDate = (current: Date): boolean => {
    return differenceInCalendarDays(current, new Date()) < 0;
  };
  // 禁用日期(转运)
  disabledyyDateZy = (current: Date): boolean => {
    return differenceInCalendarDays(current, new Date()) < 0;
  };

  // 一键建单确认弹框
  confirmSub: boolean = false;
  confirmPostData: any = {}; //确认提交数据
  confirmYuyue: boolean = false; //确认预约
  confirmInfo: string = "";
  btnLoading3 = false;
  confirm() {
    if (this.confirmYuyue) {
      this.confirmPostData.workOrder.yyTime =
        format(parse(this.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()), "yyyy-MM-dd HH:mm") + ":00";
    }
    if (!this.confirmYuyue) {
      this.confirmPostData.workOrder.platform = 2;
    } else {
      delete this.confirmPostData.workOrder.platform;
    }
    //是否需要医护陪同检查
    if (this.patientMsg.careLevel && this.currentTasktype.isAccompany == 1) {
      //特级护理或一级护理
      if (
        this.patientMsg.careLevel.value === "0" ||
        this.patientMsg.careLevel.value === "1"
      ) {
        this.btnLoading = false;
        this.btnLoading1 = false;
        this.accompany(this.confirmPostData, this.confirmYuyue, "patient-yy");
        return;
      }
    }
    if (this.patientMsg.illnessState && this.currentTasktype.isAccompany == 1) {
      //病危或病重
      if (
        this.patientMsg.illnessState.value === "2" ||
        this.patientMsg.illnessState.value === "3"
      ) {
        this.btnLoading = false;
        this.btnLoading1 = false;
        this.accompany(this.confirmPostData, this.confirmYuyue, "patient-yy");
        return;
      }
    }
    this.btnLoading3 = true;
    this.confirmPostData.workOrder.isAccompany = 0; //是否需要医护陪同检查
    this.newOrderTimeFun(this.confirmPostData.workOrder, () => {
      this.btnLoading3 = false;
      this.cancel();
    }, () => {
      this.mainService
      .postCustom(
        "api",
        this.confirmYuyue ? "appointmentOrder" : "startOrder",
        this.confirmPostData
      )
      .subscribe((data) => {
        this.message.remove(this.jdFlagId);
        this.btnLoading3 = false;
        this.cancel();
        if (data.status == 200) {
          if(this.currentDept.typeValue == 'recovery'){
            this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.confirmPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
              this.showPromptModal("创建", true, "");
              this.goodsLis = [];
              // this.workOrderInspectScore = undefined;
              this.getOrderList();
              this.getDeptTaskType();
              this.getTodayNum();
            });
          }else{
            this.showPromptModal("创建", true, "");
            this.goodsLis = [];
            // this.workOrderInspectScore = undefined;
            this.getOrderList();
            this.getDeptTaskType();
            this.getTodayNum();
          }
        } else if (data.status == 100042) {
          this.showPromptModal("创建", false, data.msg);
          this.getPatient(this.tabSearchCont);
        } else if (data.status == 1000033) {
          //重复建单那策略
          this.repeatMsg = data.msg;
          this.showDelModal(
            this.confirmPostData,
            "accompany5",
            this.confirmYuyue
          );
        } else {
          this.showPromptModal("创建", false, data.msg);
        }
      });
    })
  }
  cancel() {
    this.confirmSub = false;
    // this.confirmPostData = {};
    // this.confirmYuyue = false;
    this.btnLoading = false;
  }

  patientForm: FormGroup; //患者信息一键建单表单
  //患者送检检查项目
  checkTypeLis: any = [];
  // 患者信息一键建单关联检查
  linkCheckLis: any = [];
  isRemarks: boolean = false; //是否开启备注信息
  allowUrgent: any = "0"; //加急
  urgentReason: any = ""; //加急原因

  // 初始化form表单
  initForm() {
    // 初始化患者信息一键建单表单
    this.patientForm = this.fb.group({
      checkedType: [null, [Validators.required]],
      goods: [null],
      inspectScore: this.inspectAndPatientTransportConfig.enableTripType == 1 ? [null, [Validators.required]] : [null],
      workOrderRemark2: [null],
      linkCheck: [null, []],
      targetOffice: [null, [this.targetOfficeValidator]],
      originOffice: [null, [this.originOfficeValidator]],
      allowUrgent: [null], //加急
      urgentReason: [null, [this.urgentReasonValidator]], //加急原因
    });

    // 初始化一键发起建单表单
    this.shortcutForm = this.fb.group({
      targetOffice: [null, [this.targetOfficeShortCutValidator]],
      originOffice: [null, [this.originOfficeShortCutValidator]],
    });
    // 初始化一键发起建单表单
    this.shortcutForm1 = this.fb.group({
      targetOffice: [null, [this.targetOfficeShortCutValidator1]],
      originOffice: [null, [this.originOfficeShortCutValidator1]],
    });
    //新增报修
    this.bxForm = this.fb.group({
      // name: [null, [Validators.required]],
      // phone: [null, [Validators.required]],
      // hospital: [null, [Validators.required]],
      // building: [null, [Validators.required]],
      // address: [null, [Validators.required]],
      content: [null, [Validators.required]],
    });
  }
  //创建自定义校验规则dateValidator，用于复选框组校验时调用。
  // 起点科室校验
  originOfficeValidator = (control: FormControl): { [s: string]: boolean } => {
    if (
      this.patientForm &&
      this.patientForm.value &&
      this.checkedShowMsg.status != 200 &&
      !control.value &&
      (this.checkedShowMsg.status == 100015 ||
        this.checkedShowMsg.status == 100013)
    ) {
      return { required: true };
    }
  };
  // 目标科室校验
  targetOfficeValidator = (control: FormControl): { [s: string]: boolean } => {
    if (
      this.patientForm &&
      this.patientForm.value &&
      this.checkedShowMsg.status != 200 &&
      !control.value &&
      (this.checkedShowMsg.status == 100015 ||
        this.checkedShowMsg.status == 100014)
    ) {
      return { required: true };
    }
  };
  // 加急原因校验
  urgentReasonValidator = (control: FormControl): { [s: string]: boolean } => {
    if (this.allowUrgent == 1) {
      return { required: true };
    }
  };

  surgeryModal: boolean = false; //模态框
  surgeryInfo:string = '';
  surgeryItem: any = {};
  hideSurgeryModal() {
    this.surgeryModal = false;
  }
  // 确认
  confirmSurgery(surgeryItem) {
    console.log(surgeryItem);
    this.btnLoading = true;
    this.mainService
      .listMsgByMain('surgeryMsg', {
        surgeryId: surgeryItem.id,
        code: 'surgery_begin',
      })
      .subscribe((result:any) => {
        this.btnLoading = false;
        this.surgeryModal = false;
        if(result.state == 200){
          this.showPromptModal("操作", true, "");
        }else{
          this.showPromptModal("操作", false, result.msg);
        }
      });
  }

  // 手术安排信息-即将开始
  surgeryBegin(e, item){
    e.stopPropagation();
    let maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    let postData = {
      idx: 0,
      sum: 9999,
      transportMessage: {
        hosId: this.currentHospital.id,
        code: 'surgery_begin',
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "transportMessage", postData)
      .subscribe((result:any) => {
        this.message.remove(maskFlag);
        if (result.status == 200) {
          result.list = result.list || [];
          if(result.list.length){
            let resultObj:any = {};
            result.list.forEach(v => {
              resultObj[v.role] = v;
            })
            item.doctorNameFlag = resultObj.doctor.phoneFlag == 1 || resultObj.doctor.wechatFlag == 1;
            item.docAssistantInfosFlag = resultObj.docAssistant.phoneFlag == 1 || resultObj.docAssistant.wechatFlag == 1;
            item.anesthetistNameFlag = resultObj.anesthetist.phoneFlag == 1 || resultObj.anesthetist.wechatFlag == 1;
            item.patientNameFlag = resultObj.patient.phoneFlag == 1 || resultObj.patient.wechatFlag == 1;

            if(item.docAssistantInfosFlag && item.docAssistantInfos){
              item.docAssistantInfos = item.docAssistantInfos.split('|').map(v => v.split(',')[0]).join(' / ');
            }
            this.surgeryModal = true;
            this.surgeryItem = item;
            this.surgeryInfo = `提示：您即将给以下工作人员发送短信/微信提醒，请确认以下信息`;
          }else{
            this.showPromptModal("【手术即将开始通知】未配置", false, "失败");
          }
        }else{
          this.showPromptModal("接口获取数据", false, "失败");
        }
      });
  }
  // -----------------
  // --------------------------------------------------------start
  otherDataModal: boolean = false; //模态框
  otherDataInfo:string = '';
  otherDataItem: any = {};
  hideOtherDataModal() {
    this.otherDataModal = false;
  }
  // 确认
  confirmOtherData() {
    console.log(this.otherDataItem);
    this.otherBuildOrder(JSON.parse(this.otherDataItem).otherList);
    this.otherDataModal = false;
    this.relationTransModalShow = JSON.parse(this.otherDataItem).show;
  }

  otherDataConfirm(e){
    this.otherDataModal = true;
    this.otherDataItem = e;
    this.otherDataInfo = `您本次送${this.otherBindConfigDto.relationTrans.name}选择了${JSON.parse(this.otherDataItem).otherList.length}本${this.otherBindConfigDto.relationTrans.name}，您确认要建单配送吗？`;
  }
  // --------------------------------------------------------end
  pickUpModal: boolean = false; //模态框
  pickUpInfo:string = '';
  pickUpItem: any = {};
  hidePickUpModal() {
    this.pickUpModal = false;
  }
  // 确认
  confirmPickUp() {
    console.log(this.pickUpItem);
    this.btnLoading = true;
    this.mainService
      .createOrTakeOrder({
        type: 'surgery',
        id: this.pickUpItem.id,
        workOrder: {
          sourceld: 2,
          createDept: this.loginUser.dept.id,
          platform: 2
        }
      })
      .subscribe((result:any) => {
        this.btnLoading = false;
        this.pickUpModal = false;
        if(result.state == 200){
          this.showPromptModal("创建", true, "");
          this.getOrderList();
          this.getDeptTaskType();
          this.getTodayNum();
        }else{
          this.showPromptModal("创建", false, result.msg);
        }
      });
  }

  // 手术安排信息-一键接患者
  pickUpPatient(e, item){
    e.stopPropagation();
    this.pickUpModal = true;
    this.pickUpItem = item;
    this.pickUpInfo = `您本次需要从<span style="color:red;">${item.areaDeptDTO ? (this.deptDisplay == 2 ? item.areaDeptDTO.deptalias : item.areaDeptDTO.dept) : ''}</span>科室接<span style="color:red;">${item.patientDTO ? item.patientDTO.patientName : ''}</span>患者到<span style="color:red;">${item.surgeryDeptDTO ? (this.deptDisplay == 2 ? item.surgeryDeptDTO.deptalias : item.surgeryDeptDTO.dept) : ''}</span>手术间进行手术，您确认接患者吗？`
  }
  sendWardModal: boolean = false; //模态框
  sendWardInfo:string = '';
  sendWardItem: any = {};
  hideSendWardModal() {
    this.sendWardModal = false;
  }
  // 确认
  sLoading1 = false;
  confirmSendWard(data) {
    console.log(this.sendWardItem);
    this.sLoading1 = true;
    this.mainService
      .createRemandOrder({
        type: 'surgery',
        surgeryId: this.sendWardItem.id,
        orderId: this.sendWardItem.gdid,
        configId: this.surgeryConfigs.id,
        remandType: 'clinical',
        remandClean: data.isRemandClean ? 1 : 0,
      })
      .subscribe((result:any) => {
        this.sLoading1 = false;
        this.sendWardModal = false;
        if(result.state == 200){
          this.showPromptModal("创建", true, "");
          this.getOrderList();
          this.getDeptTaskType();
          this.getTodayNum();
        }else{
          this.showPromptModal("创建", false, result.msg);
        }
      });
  }
  // 手术中患者-送回病房
  sendWard(e, item){
    e.stopPropagation();
    this.sendWardModal = true;
    this.sendWardItem = item;
    this.sendWardInfo = `您是否确认将<span style="color:red;">${item.patientDTO ? item.patientDTO.patientName : ''}</span>患者送往<span style="color:red;">${item.areaDeptDTO ? (this.deptDisplay == 2 ? item.areaDeptDTO.deptalias : item.areaDeptDTO.dept) : ''}</span>科室吗？`
  }
  sendAwakeningRoomModal: boolean = false; //模态框
  sendAwakeningRoomInfo:string = '';
  sendAwakeningRoomItem: any = {};
  hideSendAwakeningRoomModal() {
    this.sendAwakeningRoomModal = false;
  }
  // 确认
  sLoading2 = false;
  confirmSendAwakeningRoom(data) {
    console.log(this.sendAwakeningRoomItem);
    console.log(this.surgeryConfigs);
    if(!data.recoveryRoom){
      this.message.info(`<span class="red">${this.surgeryConfigs.recoveryType.taskName}</span>任务类型-运输过程-终点科室-默认科室配置错误！`);
      return;
    }
    this.sLoading2 = true;
    this.mainService
      .createRemandOrder({
        type: 'surgery',
        surgeryId: this.sendAwakeningRoomItem.id,
        orderId: this.sendAwakeningRoomItem.gdid,
        configId: this.surgeryConfigs.id,
        remandType: 'recovery',
        remandClean: data.isRemandClean ? 1 : 0,
        endDept: data.recoveryRoom || undefined,
      })
      .subscribe((result:any) => {
        this.sLoading2 = false;
        this.sendAwakeningRoomModal = false;
        if(result.state == 200){
          this.showPromptModal("创建", true, "");
          this.getOrderList();
          this.getDeptTaskType();
          this.getTodayNum();
        }else{
          this.showPromptModal("创建", false, result.msg);
        }
      });
  }
  // 手术中患者-送回苏醒区
  sendAwakeningRoom(e, item){
    e.stopPropagation();
    this.sendAwakeningRoomModal = true;
    this.sendAwakeningRoomItem = item;
    this.sendAwakeningRoomInfo = `您是否确定将<span style="color:red;">${item.patientDTO ? item.patientDTO.patientName : ''}</span>患者送往<span style="color:red;">${this.surgeryConfigs.recoveryDeptDTO ? (this.deptDisplay == 2 ? this.surgeryConfigs.recoveryDeptDTO.deptalias : this.surgeryConfigs.recoveryDeptDTO.dept) : ''}</span>科室吗？`
  }

  // 手术排程信息-一键建单
  createOrder(e, item){
    e.stopPropagation();
    this.newPatientOrder(item.patientDTO);
  }

  // 患者信息一键建单
  patientModal: boolean = false; //患者信息一键建单模态框
  patientMsg; //患者信息
  // 打开患者信息一键建单模态框
  maskFlag: any = false;
  newPatientOrder(msg) {
    this.yyTime = null;
    this.yyTimeZy = null;
    this.btnLoading = false;
    this.btnLoading1 = false;
    let that = this;
    that.initForm();
    that.checkedShowMsg = {};
    that.patientMsg = msg;
    this.workOrderInspectScore = msg.tripType;
    this.workOrderRemark2 = msg.remark || '';
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    that.mainService
      .postCustom("configuration", "deptTSPTaskType", {})
      .subscribe((data) => {
        that.checkTypeLis = data.data;
        // 默认选中患者陪检,没有患者陪检，则选择第一个患者其他服务的任务类型
        let id;
        for (let i = that.checkTypeLis.length - 1; i >= 0; i--) {
          if (that.checkTypeLis[i].associationType.value == "inspect") {
            id = that.checkTypeLis[i].id;
            break;
          } else if (
            that.checkTypeLis[i].associationType.value == "patientTransport"
          ) {
            id = that.checkTypeLis[i].id;
          }
        }
        that.patientForm.controls.checkedType.setValue(id);
        this.changeCheckedType(true);
      });
  }
  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;
  }
  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;
  }

  // 获取大于x，并且是n的倍数的数字
  getLgNumber(x: number, n:number): number{
    for(let i = x; i < 60; i++){
      if(i % n === 0){
        return i;
      }
    }
    return 0;
  }

  hidePatientOrder() {
    this.patientModal = false;
    this.clickYYFlag = false;
    this.clickYYZyFlag = false;
  }
  // 预约建单
  btnLoading1 = false;
  confirmPatient1(type) {
    this.confirmPatient(type);
  }
  // 患者信息保存
  clickYYFlag = false; //是否点击预约建单-患者陪检
  clickYYZyFlag = false; //是否点击预约建单-患者其他
  confirmPatient(yuyue?) {
    if (yuyue === "patient-yuyue") {
      this.clickYYFlag = true;
    } else {
      this.clickYYFlag = false;
    }
    if (yuyue === "patient-zy-yuyue") {
      this.clickYYZyFlag = true;
    } else {
      this.clickYYZyFlag = false;
    }

    // 选项是患者转运
    let flag = this.checkTypeLis.some((item) => {
      return (
        item.id == this.patientForm.controls.checkedType.value &&
        item.associationType.value == "patientTransport"
      );
    });
    //预约时间-患者陪检不能为空
    console.log(this.yyTime, this.yyTimeZy, flag, yuyue);
    if (
      (!this.yyTime && !flag && yuyue === "patient-yuyue") ||
      (!this.yyTimeZy && flag && yuyue === "patient-zy-yuyue")
    ) {
      return;
    }
    console.log(this.yyDateZy, this.yyTimeZy, this.yyDate, this.yyTime, flag);
    if (flag) {
      //转运
      let yyDateZy = (typeof this.yyDateZy === 'object') ? new Date(this.yyDateZy) : parse(this.yyDateZy, 'yyyy-MM-dd HH:mm:ss', new Date());
      let yyTimeZy = (typeof this.yyTimeZy === 'object') ? new Date(this.yyTimeZy) : parse(this.yyTimeZy, 'yyyy-MM-dd HH:mm:ss', new Date());
      this.yyTimeZy =
        format(yyDateZy, "yyyy-MM-dd") +
        " " +
        format(yyTimeZy, "HH:mm") +
        ":00";
    } else {
      //陪检
      let yyDate = (typeof this.yyDate === 'object') ? new Date(this.yyDate) : parse(this.yyDate, 'yyyy-MM-dd HH:mm:ss', new Date());
      let yyTime = (typeof this.yyTime === 'object') ? new Date(this.yyTime) : parse(this.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date());
      this.yyTime =
        format(yyDate, "yyyy-MM-dd") +
        " " +
        format(yyTime, "HH:mm") +
        ":00";
    }
    var that = this;
    for (const i in that.patientForm.controls) {
      that.patientForm.controls[i].markAsDirty();
      that.patientForm.controls[i].updateValueAndValidity();
    }
    if (that.patientForm.invalid) {
      if(!that.patientForm.value.inspectScore){
        this.message.error("陪检方式必填！");
      }
      return;
    }
    console.log(that.patientForm);
    if (yuyue) {
      this.confirmYuyue = true;
      this.btnLoading1 = true;
    } else {
      this.confirmYuyue = false;
      this.btnLoading = true;
    }

    let postData: any = {
      workOrder: {
        sourceId: SourceId.hushi,
        taskType: { id: that.patientForm.controls.checkedType.value },
        startDept: { id: that.checkedShowMsg.startDept },
        endDepts: [{ id: that.checkedShowMsg.endDept }],
        createDept: that.loginUserDeptId,
        patient: {
          patientCode: that.patientMsg.patientCode,
        },
      },
    };
    if (!flag) {
      postData.workOrder.taskType.isHalfInspect =
        this.currentTasktype.isHalfInspect === 1 ? 1 : 0; //半程陪检
    }
    if (
      (that.checkedShowMsg.status == 100013 ||
        that.checkedShowMsg.status == 100015) &&
      that.patientForm.value.originOffice
    ) {
      postData.workOrder.startDept.id = that.patientForm.value.originOffice;
    }
    if (that.patientForm.value.targetOffice) {
      postData.workOrder["endDepts"] = [
        { id: that.patientForm.value.targetOffice },
      ];
    } else if (flag) {
      postData.workOrder["endDepts"] = [
        { id: that.checkedShowMsg.end.end.list[0].id },
      ];
    }
    let checkedArr = [];
    let yy = false; //是否有预约时间
    if (that.linkCheckLis && that.linkCheckLis.length) {
      that.linkCheckLis.forEach((e) => {
        if (e.checked) {
          checkedArr.push({ id: e.value });
          if (e.yyTime) {
            yy = true;
          }
        }
      });
    }
    // 携带设备
    let goods = "";
    if (that.patientForm.value.goods && that.patientForm.value.goods.length) {
      that.patientForm.value.goods.forEach((e) => {
        if (e.checked) {
          goods += e.value + ",";
        }
      });
      goods = goods.slice(0, goods.length - 1);
    }
    postData.workOrder["goods"] = goods;
    // 陪检方式
    if (that.patientForm.value.inspectScore) {
      postData.workOrder["inspectScore"] = { id: that.patientForm.value.inspectScore };
    }

    // 工单备注
    postData.workOrder["workOrderRemark"] = that.workOrderRemark2 || '';
    if (!yuyue && that.current_allowUrgent && this.allowUrgent == 1) {
      postData.workOrder["urgentDetails"] = {
        checkStatus: { id: 329 },
        urgentReason: that.urgentReason,
      };
    } else {
      delete postData.workOrder["urgentDetails"];
    }
    if (
      yy &&
      that.checkedShowMsg.status == 200 &&
      that.linkCheckLis &&
      checkedArr.length
    ) {
      // 有预约时间
      postData.workOrder["checkList"] = checkedArr;
      that.hidePatientOrder();
      that.confirmSub = true;
      that.confirmPostData = postData;
      that.confirmInfo = "您确认建单吗？";
    } else {
      if (!yy && that.checkedShowMsg.status == 200) {
        postData.workOrder["checkList"] = checkedArr;
        // 添加预约时间
        if (yuyue) {
          postData.workOrder.yyTime =
            format(parse(this.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()), "yyyy-MM-dd HH:mm") + ":00";
        }
      } else {
        delete postData.workOrder["checkList"];
        // 添加预约时间
        if (yuyue) {
          postData.workOrder.yyTime =
            format(parse(this.yyTimeZy, 'yyyy-MM-dd HH:mm:ss', new Date()), "yyyy-MM-dd HH:mm") + ":00";
        }
      }
      if (that.checkedShowMsg.status != 200) {
        postData.workOrder["isRemand"] = this.isRemand ? 1 : 0;
      }
      if (!yuyue) {
        postData.workOrder.platform = 2;
      } else {
        delete postData.workOrder.platform;
      }
      //是否需要医护陪同检查
      if (this.patientMsg.careLevel && this.currentTasktype.isAccompany == 1) {
        //特级护理或一级护理
        if (
          this.patientMsg.careLevel.value === "0" ||
          this.patientMsg.careLevel.value === "1"
        ) {
          this.btnLoading = false;
          this.btnLoading1 = false;
          this.accompany(postData, yuyue, "patient");
          return;
        }
      }
      if (
        this.patientMsg.illnessState &&
        this.currentTasktype.isAccompany == 1
      ) {
        //病危或病重
        if (
          this.patientMsg.illnessState.value === "2" ||
          this.patientMsg.illnessState.value === "3"
        ) {
          this.btnLoading = false;
          this.btnLoading1 = false;
          this.accompany(postData, yuyue, "patient");
          return;
        }
      }
      postData.workOrder.isAccompany = 0; //是否需要医护陪同检查
      this.newOrderTimeFun(postData.workOrder, () => {
        this.hidePatientOrder();
      }, () => {
        this.mainService
          .postCustom("api", yuyue ? "appointmentOrder" : "startOrder", postData)
          .subscribe((data) => {
            this.message.remove(this.jdFlagId);
            this.hidePatientOrder();
            if (data.status == 200) {
              if(this.currentDept.typeValue == 'recovery'){
                this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: postData.workOrder.patient.patientCode}).subscribe((resultData) => {
                  this.showPromptModal("创建", true, "");
                  this.goodsLis = [];
                  // this.workOrderInspectScore = undefined;
                  this.getOrderList();
                  this.getDeptTaskType();
                  this.getTodayNum();
                });
              }else{
                this.showPromptModal("创建", true, "");
                this.goodsLis = [];
                // this.workOrderInspectScore = undefined;
                this.getOrderList();
                this.getDeptTaskType();
                this.getTodayNum();
              }
            } else if (data.status == 100042) {
              this.showPromptModal("创建", false, data.msg);
              this.getPatient(this.tabSearchCont);
            } else if (data.status == 1000033) {
              //重复建单那策略
              this.repeatMsg = data.msg;
              this.showDelModal(postData, "transport", yuyue);
            } else {
              this.showPromptModal("创建", false, data.msg);
            }
          });
      })
    }
  }
  // 是否需要护士医生陪同模态框
  accompanyModal: boolean = false;
  accompanyLoading: boolean = false;
  cancenlLoading: boolean = false;
  accompanyPostData = null;
  accompanyYuyue;
  accompanyType = "";
  accompany(postData, yuyue, type) {
    this.accompanyModal = true;
    this.accompanyPostData = postData;
    this.accompanyYuyue = yuyue;
    this.accompanyType = type;
  }
  confirmAccompany() {
    this.accompanyPostData.workOrder.isAccompany = 1;
    this.accompanyLoading = true;
    if (this.accompanyType == "patient") {
      //患者列表直接建单
      this.newOrderTimeFun(this.accompanyPostData.workOrder, () => {
        this.hidePatientOrder();
        this.accompanyModal = false;
        this.accompanyLoading = false;
      }, () => {
        this.mainService
        .postCustom(
          "api",
          this.accompanyYuyue ? "appointmentOrder" : "startOrder",
          this.accompanyPostData
        )
        .subscribe((data) => {
          this.message.remove(this.jdFlagId);
          this.hidePatientOrder();
          this.accompanyModal = false;
          this.accompanyLoading = false;
          if (data.status == 200) {
            if(this.currentDept.typeValue == 'recovery'){
              this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.accompanyPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
                this.showPromptModal("创建", true, "");
                this.goodsLis = [];
                // this.workOrderInspectScore = undefined;
                this.getOrderList();
                this.getDeptTaskType();
                this.getTodayNum();
              });
            }else{
              this.showPromptModal("创建", true, "");
              this.goodsLis = [];
              // this.workOrderInspectScore = undefined;
              this.getOrderList();
              this.getDeptTaskType();
              this.getTodayNum();
            }
          } else if (data.status == 100042) {
            this.showPromptModal("创建", false, data.msg);
            this.getPatient(this.tabSearchCont);
          } else if (data.status == 1000033) {
            //重复建单那策略
            this.repeatMsg = data.msg;
            this.showDelModal(
              this.accompanyPostData,
              "accompany1",
              this.accompanyYuyue
            );
          } else {
            this.showPromptModal("创建", false, data.msg);
          }
        });
      })
    } else if (this.accompanyType == "patient-yy") {
      //患者列表预约建单
      this.newOrderTimeFun(this.accompanyPostData.workOrder, () => {
        this.btnLoading3 = false;
        this.accompanyModal = false;
        this.accompanyLoading = false;
        this.cancel();
      }, () => {
        this.mainService
        .postCustom(
          "api",
          this.accompanyYuyue ? "appointmentOrder" : "startOrder",
          this.accompanyPostData
        )
        .subscribe((data) => {
          this.message.remove(this.jdFlagId);
          this.btnLoading3 = false;
          this.accompanyModal = false;
          this.accompanyLoading = false;
          this.cancel();
          if (data.status == 200) {
            if(this.currentDept.typeValue == 'recovery'){
              this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.accompanyPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
                this.showPromptModal("创建", true, "");
                this.goodsLis = [];
                // this.workOrderInspectScore = undefined;
                this.getOrderList();
                this.getDeptTaskType();
                this.getTodayNum();
              });
            }else{
              this.showPromptModal("创建", true, "");
              this.goodsLis = [];
              // this.workOrderInspectScore = undefined;
              this.getOrderList();
              this.getDeptTaskType();
              this.getTodayNum();
            }
          } else if (data.status == 100042) {
            this.showPromptModal("创建", false, data.msg);
            this.getPatient(this.tabSearchCont);
          } else if (data.status == 1000033) {
            //重复建单那策略
            this.repeatMsg = data.msg;
            this.showDelModal(
              this.accompanyPostData,
              "accompany2",
              this.accompanyYuyue
            );
          } else {
            this.showPromptModal("创建", false, data.msg);
          }
        });
      })
    }
  }

  hideAccompanyModal(e) {
    console.log(e);
    if (e === "x") {
      //关闭
      this.accompanyModal = false;
      return;
    }
    this.accompanyPostData.workOrder.isAccompany = 0;
    this.cancenlLoading = true;
    if (this.accompanyType == "patient") {
      //患者列表直接建单
      this.newOrderTimeFun(this.accompanyPostData.workOrder, () => {
        this.hidePatientOrder();
        this.accompanyModal = false;
        this.cancenlLoading = false;
      }, () => {
        this.mainService
          .postCustom(
            "api",
            this.accompanyYuyue ? "appointmentOrder" : "startOrder",
            this.accompanyPostData
          )
          .subscribe((data) => {
            this.message.remove(this.jdFlagId);
            this.hidePatientOrder();
            this.accompanyModal = false;
            this.cancenlLoading = false;
            if (data.status == 200) {
              if(this.currentDept.typeValue == 'recovery'){
                this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.accompanyPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
                  this.showPromptModal("创建", true, "");
                  this.goodsLis = [];
                  // this.workOrderInspectScore = undefined;
                  this.getOrderList();
                  this.getDeptTaskType();
                  this.getTodayNum();
                });
              }else{
                this.showPromptModal("创建", true, "");
                this.goodsLis = [];
                // this.workOrderInspectScore = undefined;
                this.getOrderList();
                this.getDeptTaskType();
                this.getTodayNum();
              }
            } else if (data.status == 100042) {
              this.showPromptModal("创建", false, data.msg);
              this.getPatient(this.tabSearchCont);
            } else if (data.status == 1000033) {
              //重复建单那策略
              this.repeatMsg = data.msg;
              this.showDelModal(
                this.accompanyPostData,
                "accompany3",
                this.accompanyYuyue
              );
            } else {
              this.showPromptModal("创建", false, data.msg);
            }
          });
      })
    } else if (this.accompanyType == "patient-yy") {
      //患者列表预约建单
      this.newOrderTimeFun(this.accompanyPostData.workOrder, () => {
        this.btnLoading3 = false;
        this.accompanyModal = false;
        this.cancenlLoading = false;
        this.cancel();
      }, () => {
        this.mainService
          .postCustom(
            "api",
            this.accompanyYuyue ? "appointmentOrder" : "startOrder",
            this.accompanyPostData
          )
          .subscribe((data) => {
            this.message.remove(this.jdFlagId);
            this.btnLoading3 = false;
            this.accompanyModal = false;
            this.cancenlLoading = false;
            this.cancel();
            if (data.status == 200) {
              if(this.currentDept.typeValue == 'recovery'){
                this.mainService.postCustom("api", "clearPatientRecoveryDept", {patientCode: this.accompanyPostData.workOrder.patient.patientCode}).subscribe((resultData) => {
                  this.showPromptModal("创建", true, "");
                  this.goodsLis = [];
                  // this.workOrderInspectScore = undefined;
                  this.getOrderList();
                  this.getDeptTaskType();
                  this.getTodayNum();
                });
              }else{
                this.showPromptModal("创建", true, "");
                this.goodsLis = [];
                // this.workOrderInspectScore = undefined;
                this.getOrderList();
                this.getDeptTaskType();
                this.getTodayNum();
              }
            } else if (data.status == 100042) {
              this.showPromptModal("创建", false, data.msg);
              this.getPatient(this.tabSearchCont);
            } else if (data.status == 1000033) {
              //重复建单那策略
              this.repeatMsg = data.msg;
              this.showDelModal(
                this.accompanyPostData,
                "accompany4",
                this.accompanyYuyue
              );
            } else {
              this.showPromptModal("创建", false, data.msg);
            }
          });
      })
    }
  }

  //获取携带设备
  goodsLis: any = []; //携带设备
  getAllGoods() {
    this.mainService.getDictionary("list", "goods").subscribe((data) => {
      let goodsLis = data || [];
      goodsLis.forEach((e) => {
        this.goodsLis.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.message.error("请求数据失败");
        }
      });
  }

  // 切换患者送检检查项目
  checkedShowMsg: any = {}; //患者送检检查项目对应展示信息
  current_allowUrgent = false; //当前任务类型是否允许加急
  currentTasktype; //当前选中的任务类型对象
  cLoading = false;
  historyCustomRemarks2 = [];
	isStartFixedType:boolean = false;
	isEndFixedType:boolean = false;
	patientQuery:any={};
  changeCheckedType(isInit = false) {
    isInit && (this.inspectToday = new Date());
    this.customRemarks2 = [];
    this.historyCustomRemarks2 = [];
    this.isYyInspect = false;
    this.linkCheckLisTrue = false;
    this.clickYYFlag = false;
    this.clickYYZyFlag = false;
    this.currentTasktype = this.checkTypeLis.find(
      (item) => item.id == this.patientForm.controls.checkedType.value
    );
    // 是否回显注意事项
    if(isInit){
      if(this.currentTasktype.remarksSwitch === 1){
        this.workOrderRemark2 = this.patientMsg.remark || "";
      }else{
        this.workOrderRemark2 = '';
      }
    }
    // 获取患者其他服务，护士端是否预约建单
    let appointmentZyBuildFlag = this.checkTypeLis.filter((item) => item.id == this.patientForm.controls.checkedType.value && item.associationType.value == "patientTransport");
    if (appointmentZyBuildFlag.length) {
      this.appointmentZyBuildFlag =
        appointmentZyBuildFlag[0].appointmentOtherSwitch == 1 ? "1" : "0";
      console.log(this.appointmentZyBuildFlag, "seimin");
      this.yyDateZy = new Date();
      this.yyTimeZy = new Date();
      let end = this.getLgNumber(this.yyTimeZy.getMinutes(), this.inspectAndPatientTransportConfig.timeMod);
      this.yyTimeZy.setMinutes(end);
      if(end === 0){
        this.yyTimeZy.setHours(this.yyTimeZy.getHours() + 1);
      }
    } else {
      this.appointmentBuildFlag =
        this.currentTasktype.appointmentSwitch == 1 ? "1" : "0";
      console.log(this.appointmentBuildFlag, "seimin");
    }
    console.log(this.patientForm.controls.checkedType.value, this.checkTypeLis);
    this.current_allowUrgent =
      this.checkTypeLis.find(
        (item) => item.id == this.patientForm.controls.checkedType.value
      ).allowUrgent == 1
        ? true
        : false;
    // 判断这个任务类型是否允许加急 start
    // 判断这个任务类型是否允许加急 end
    let that = this;
    let isInpect = this.checkTypeLis.some((item) => item.id == this.patientForm.controls.checkedType.value && item.associationType.value == "inspect");
    this.patientQuery = {
      taskTypeId: that.patientForm.controls.checkedType.value,
      patientCode: that.patientMsg.patientCode,
      startTime: isInpect ? format(startOfDay(this.inspectToday), 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: isInpect ? format(endOfDay(this.inspectToday), 'yyyy-MM-dd HH:mm:ss') : undefined,
    };
    this.cLoading = true;
    that.mainService
      .postCustom("nurse", "workOrder/buildTrip", this.patientQuery)
      .subscribe((data) => {
        this.cLoading = false;
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.patientModal = true;
        that.checkedShowMsg = data;
				if(data.end){
					if(data.end.end.departmentStrategy==202 ||
					data.end.end.departmentStrategy==204 ||
					data.end.end.departmentStrategy==205){
						this.isEndFixedType = true
					}else{
						this.isEndFixedType = false
					}
				}
				if(data.start){
					if(data.start.start.departmentStrategy==202 ||
					data.start.start.departmentStrategy==204 ||
					data.start.start.departmentStrategy==205){
						this.isStartFixedType = true
					}else{
						this.isStartFixedType = false
					}
				}
        if (that.checkedShowMsg.status != 200) {
          that.isRemand = data.isRemand == 1 ? true : false;
        }
        that.goodsLis = [];
        // that.workOrderInspectScore = undefined;
        that.allowUrgent = "0"; //加急
        that.urgentReason = ""; //加急原因

        that.getAllGoods();
        that.getWorkOrderInspectScore();
        // 工单备注配置 start
        that.isRemarks = data.remarksSwitch == 1;
        if (data.remarksSwitch == 1) {
          if (data.customRemarks === null || data.customRemarks === "") {
            that.customRemarks2 = [];
          } else {
            that.customRemarks2 = data.customRemarks.split("$");
          }
          that.workOrderRemarkTips2 =
          data.remarksPrompts || "请填写工单备注,不超过100个字符";
          // let user = JSON.parse(localStorage.getItem("user"));
          // that.mainService
          //   .postCustom("nurse", "workOrder/recentRemarks", {
          //     deptId: user.user.dept.id,
          //     taskTypeId: that.patientForm.controls.checkedType.value,
          //   })
          //   .subscribe((result) => {
          //     if (result.state == 200) {
          //       that.historyCustomRemarks2 = result.data;
          //     }
          //   });
        }
        // 工单备注配置 end
        that.linkCheckLis = [];
        if (data.status == 200 && data.data && data.data.length) {
          let arr = [];
          data.data.forEach((e) => {
						if(e.yyTime){
							e.yyEndTime = e.yyTime
							e.newTime = format(new Date(e.yyTime), 'MM-dd HH:mm')
							if(e.endCheckTime){
								e.newTime2 = format(new Date(e.endCheckTime), 'HH:mm')
								e.yyEndTime = e.newTime + '--' + e.newTime2
							}else{
								e.yyEndTime = e.newTime
							}
						}else{
							e.yyEndTime = null
						}

						arr.push({
						  execDeptId: e.execDept.id,
						  yyTime: e.yyTime,
              priority: e.priority,
              manualCreate: e.manualCreate,
              label:
                (e.yyEndTime || "") +
                " " +
                (this.deptDisplay == 2
                  ? e.execDept.deptalias
                  : e.execDept.dept) +
                " 进行 " +
                (e.inspectName?e.inspectName:'' + '-' + e.inspectCode || "检查"),
              value: e["id"],
              checked: false,
              remark: e.remark,
            });
          });
          that.linkCheckLis = arr;
        }
      });
  }
  // 需要预约建单-事件
  yyInspectChange(e) {
    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() >
          this.leadTime * 60 * 1000
        );
      });
      if (obj) {
        this.showDateTime();
      } else {
        this.yyTime = null;
        this.yyDate = new Date();
        console.log(this.isYyInspect);
      }
    } else {
      //转运
      this.yyTimeZy = null;
      this.yyDateZy = new Date();
    }
  }
  //回显时间日期
  showDateTime() {
    //当前时间要大于生效时间
    let isYyInspect = this.filterLinkCheckLis.every((item) => {
      return (
        parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime() - new Date().getTime() >
        this.leadTime * 60 * 1000
      );
    });
    //如果勾选需要预约检查
    if (isYyInspect) {
      //筛选离当前时间最近的
      let timeList = this.filterLinkCheckLis
        .map((item) => parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime())
        .sort();
      this.yyTime = new Date(timeList[0] - this.leadTime * 60 * 1000); //回显预约时间,需要减去生效时间
      this.yyDate = new Date(timeList[0] - this.leadTime * 60 * 1000); //回显预约日期,需要减去生效时间
      this.yyDateChange(this.yyTime);
    } else {
      this.yyTime = null;
      this.yyDate = null;
    }
  }
  // 患者送检检查项目-选择检查项目
  linkCheckLisTrue = false; //是否有已选择(患者)
  isInspectPriority = 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);
    //检查有紧急度,则加急
    if (flag) {
      this.allowUrgent = "1";
      this.urgentReason = "系统根据检查信息，自动进行加急";
    } else {
      this.allowUrgent = "0";
      this.urgentReason = "";
    }
    this.clickYYFlag = false;
    // 有预约时间并且选中的
    this.filterLinkCheckLis = this.linkCheckLis.filter(
      (item) => Boolean(item.yyTime) && item.checked
    );
    //有预约时间并且选中的检查数组不为空,并且预约建单的开关开启
    if (this.filterLinkCheckLis.length && this.appointmentBuildFlag == "1") {
      //当前时间要大于生效时间
      this.isYyInspect = this.filterLinkCheckLis.every((item) => {
        return (
          parse(item.yyTime, 'yyyy-MM-dd HH:mm:ss', new Date()).getTime() - new Date().getTime() >
          this.leadTime * 60 * 1000
        );
      });
      this.allowUrgentChange(this.allowUrgent);
      if (this.allowUrgent == 0) {
        //不加急状态下，回显时间
        this.showDateTime();
      }
    } else {
      //有预约时间并且选中的检查数组为空
      this.isYyInspect = false;
      this.yyTime = null;
      this.yyDate = null;
    }
    this.linkCheckLisTrue = e.length > 0;
    this.isInspectPriority = e.some((item) => item.priority == 1);
  }
  // 是否加急
  allowUrgentChange(e) {
    // this.urgentReasonValidator = (control: FormControl): { [s: string]: boolean } => {
    //   if (e == 1) {
    //     return { required: true };
    //   }
    // };
    if (e == 0) {
      this.patientForm.get("urgentReason")!.clearValidators();
      this.patientForm.get("urgentReason")!.markAsPristine();
    } else {
      this.patientForm.get("urgentReason")!.setValidators(Validators.required);
      this.patientForm.get("urgentReason")!.markAsDirty();
    }
    this.patientForm.get("urgentReason")!.updateValueAndValidity();
    if (this.isYyInspect) {
      this.isYyInspect = e == 0;
      if (!this.isYyInspect) {
        this.yyDate = null;
        this.yyDateZy = null;
        this.yyTime = null;
        this.yyTimeZy = null;
      }
    } else {
      this.yyDate = null;
      this.yyDateZy = null;
      this.yyTime = null;
      this.yyTimeZy = null;
    }
  }
  // 禁用小时
  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;
  }

  // 快捷一键发起建单
  shortcutMsg; //一键发起信息
  buildMsg: any = {}; //一键发起返回信息
  buildType: string = ""; //快捷建单类型
  historyCustomRemarks = []; //历史快捷输入
	msgId:any;
  // 打开一键发起建单模态框
  newShortcutOrder(msg, type) {
    this.workOrderRemark = "";
    this.customRemarks = [];
    this.historyCustomRemarks = [];
    console.log(msg, type);
    this.buildType = type;
    this.shortcutMsg = msg;
    this.initForm();
    this.buildMsg = {};
		this.msgId = msg.id;
    let postData = {
      taskTypeId: msg.id,
    };
    this.nLoading = true;
    this.mainService
      .postCustom("nurse", "workOrder/buildTrip", postData)
      .subscribe((result) => {
				result.start.start.list.forEach(i=>{
          if(i.inputcode){
            i.inputcode = i.inputcode.toUpperCase()
            if(this.deptDisplay ==2){
              i.deptalias = i.deptalias + '('+i.inputcode+')'
            }else{
              i.dept = i.dept + '('+i.inputcode+')'
            }
          }
				})
				result.end.end.list.forEach(i=>{
          if(i.inputcode){
            i.inputcode = i.inputcode.toUpperCase()
            if(this.deptDisplay ==2){
              i.deptalias = i.deptalias + '('+i.inputcode+')'
            }else{
              i.dept = i.dept + '('+i.inputcode+')'
            }
          }
				})
        this.buildMsg = result;
				if(result.end){
					if(result.end.end.departmentStrategy==202 ||
					result.end.end.departmentStrategy==204 ||
					result.end.end.departmentStrategy==205){
						this.isEndFixedType = true
					}else{
						this.isEndFixedType = false
					}
				}
				if(result.start){
					if(result.start.start.departmentStrategy==202 ||
					result.start.start.departmentStrategy==204 ||
					result.start.start.departmentStrategy==205){
						this.isStartFixedType = true
					}else{
						this.isStartFixedType = false
					}
				}
        if (result.remarksSwitch == 1) {
          if (result.customRemarks === null || result.customRemarks === "") {
            this.customRemarks = [];
          } else {
            this.customRemarks = result.customRemarks.split("$");
          }
          this.workOrderRemarkTips =
            result.remarksPrompts || "请填写工单备注,不超过100个字符";
          let user = JSON.parse(localStorage.getItem("user"));
          this.mainService
            .postCustom("nurse", "workOrder/recentRemarks", {
              deptId: user.user.dept.id,
              taskTypeId: msg.id,
            })
            .subscribe((result1) => {
              this.nLoading = false;
              if (result1.state == 200) {
                this.historyCustomRemarks = result1.data;
              }
            });
        } else {
          this.nLoading = false;
        }
      });
  }
  shortcutForm: FormGroup; //一键发起建单表单
  bxForm: FormGroup; //报修表单
  // 一键建单校验
  // 起点科室校验
  originOfficeShortCutValidator = (
    control: FormControl
  ): { [s: string]: boolean } => {
    if (
      this.shortcutForm &&
      this.shortcutForm.value &&
      !control.value &&
      (this.buildMsg.status == 100013 || this.buildMsg.status == 100015)
    ) {
      return { required: true };
    }
  };
  // 目标科室校验
  targetOfficeShortCutValidator = (
    control: FormControl
  ): { [s: string]: boolean } => {
    if (
      this.shortcutForm &&
      this.shortcutForm.value &&
      !control.value &&
      (this.buildMsg.status == 100014 || this.buildMsg.status == 100015)
    ) {
      return { required: true };
    }
  };
  // 修改工号
  userAccount = null;
  changeAccount(e){
    this.userAccount =this.accountList.find(v => v.id == e);
  }

  // 查看关联业务
  otherBindConfigDto:any = {};
  relationTransModalShow = false; //关联业务弹窗开关
  // 关闭关联业务弹窗
  closeModelRelationTrans(e) {
    this.relationTransModalShow = JSON.parse(e).show;
  }
  // 确定关联业务弹窗
  confirmModelRelationTrans(e) {
    if(JSON.parse(e).otherList.length){
      this.otherDataConfirm(e);
    }else{
      this.message.info('请选择病历！');
    }

  }

  // 一键发起建单保存
  loading5 = false;
  async confirmShortcut(shortcutForm?, buildType?) {
    shortcutForm && (this.shortcutForm = shortcutForm);
    var that = this;
    for (const i in that.shortcutForm.controls) {
      that.shortcutForm.controls[i].markAsDirty();
      that.shortcutForm.controls[i].updateValueAndValidity();
    }
    console.log(that.shortcutForm);
    if (that.shortcutForm.invalid) return;
    that.loading5 = true;
    that.buildType = buildType || "other";
    if(this.buildMsg.reserveUserSwitch == 1 && !this.userAccount){
      this.message.info('请选择工号！');
      this.loading5 = false;
      return;
    }

    // 判断改任务类型是否开启关联数据
    let taskTypeDtoPromise = await this.mainService.getFetchDataList('simple/data', 'otherBindConfig', {"idx":0,"sum":10,"otherBindConfig":{"hosId":1}}).toPromise();
    console.log(taskTypeDtoPromise);
    console.log(that.shortcutMsg);
    let otherBindConfigDto = taskTypeDtoPromise.list.find(v => v.taskTypeId == that.shortcutMsg.id);
    if(taskTypeDtoPromise.status == 200 && otherBindConfigDto && otherBindConfigDto.startAlert == 1 && that.shortcutMsg.bindTrans == 1){
      this.otherBindConfigDto = otherBindConfigDto;
      this.relationTransModalShow = true;
      that.loading5 = false;
      return;
    }
    shortcutForm && (this.isShowBuildQuickConfirm = false);
    this.otherBuildOrder(undefined, buildType);
  }
  otherBuildOrder(otherList?,buildType?){
    var that = this;
    // 其他
    let workOrderRemark = '';
    if(otherList){
      workOrderRemark = this.userAccount ? `${this.userAccount.account}-${this.userAccount.name}:${this.workOrderRemark}共${otherList.length}本${this.otherBindConfigDto.relationTrans.name}` : this.workOrderRemark + `共${otherList.length}本${this.otherBindConfigDto.relationTrans.name}`;
    }else{
      workOrderRemark = this.userAccount ? `${this.userAccount.account}-${this.userAccount.name}:${this.workOrderRemark}` : this.workOrderRemark;
    }
    let postData = {
      workOrder: {
        sourceId: SourceId.hushi,
        workOrderRemark,
        taskType: { id: that.shortcutMsg.id },
        createDept: that.loginUserDeptId,
        startDept: { id: that.buildMsg.startDept },
        endDepts: [{ id: that.buildMsg.endDept }],
        otherList: otherList || undefined,
      },
    };
    if (
      (that.buildMsg.status == 100013 || that.buildMsg.status == 100015) &&
      that.shortcutForm.value.originOffice
    ) {
      postData.workOrder.startDept.id = that.shortcutForm.value.originOffice;
    }
    if (that.shortcutForm.value.targetOffice) {
      postData.workOrder["endDepts"] = [
        { id: that.shortcutForm.value.targetOffice },
      ];
    } else {
      postData.workOrder["endDepts"] = [
        { id: that.buildMsg.end.end.list[0].id },
      ];
    }
    console.log(postData);
    this.newOrderTimeFun(postData.workOrder, () => {
      that.loading5 = false;
    }, () => {
      that.mainService
      .postCustom("api", this.shortcutMsg.reserveSwitch == 1 && this.currentDept.typeValue != 'recovery' && this.currentDept.typeValue != 'surgery' ? "reserveOrder" :"startOrder", postData)
      .subscribe((data) => {
        this.message.remove(this.jdFlagId);
        that.loading5 = false;

        if (data.status == 200 && (that.buildType == "other" || that.buildType == "ordinary")) {
          that.showPromptModal("创建", true, "", that.buildType);
          this.getTodayNum();
        } else if (data.status == 200 && that.buildType == "bb") {
          that.showPromptModal("创建", true, "", "bb");
          this.getTodayNum();
        } else if (that.buildType == "bb" && data.status == 100043) {
          that.showPromptModal("创建", true, data.msg);
          this.getTodayNum();
        } else if (data.status == 1000033) {
          //重复建单那策略
          this.repeatMsg = data.msg;
          this.showDelModal(postData, that.buildType);
        } else {
          that.showPromptModal("创建", false, data.msg);
        }

        // 重置
        this.getDeptTaskType();
      });
    })
  }
  // ======================start===============================
  // 快捷一键发起建单
  shortcutModal: boolean = false; //检查信息一键建单模态框
  shortcutMsg1; //一键发起信息
  buildMsg1: any = {}; //一键发起返回信息
  urgentFlag = false;
  bLoading = false; //收取标本的loading
  // 打开一键发起建单模态框,urgent为true的时候是紧急
  historyCustomRemarks1 = [];
  newShortcutOrder1(msg, type, urgent?) {
    this.btnLoading = false;
    this.workOrderRemark1 = "";
    this.customRemarks1 = [];
    this.historyCustomRemarks1 = [];
    console.log(msg, type);
    this.urgentFlag = Boolean(urgent);
    this.buildType = type;
    this.shortcutMsg1 = msg;
    this.initForm();
    this.buildMsg1 = {};
    let postData = {
      taskTypeId: msg.id,
      deptId: JSON.parse(localStorage.getItem("user")).user.dept.id,
    };
    this.bLoading = true;
    this.mainService
      .postCustom("nurse", "workOrder/buildTrip", postData)
      .subscribe((result) => {
        this.shortcutModal = true;
        this.buildMsg1 = result;
        if (result.remarksSwitch == 1) {
          if (result.customRemarks === null || result.customRemarks === "") {
            this.customRemarks1 = [];
          } else {
            this.customRemarks1 = result.customRemarks.split("$");
          }
          this.workOrderRemarkTips1 =
            result.remarksPrompts || "请填写工单备注,不超过100个字符";
          let user = JSON.parse(localStorage.getItem("user"));
          this.mainService
            .postCustom("nurse", "workOrder/recentRemarks", {
              deptId: user.user.dept.id,
              taskTypeId: msg.id,
            })
            .subscribe((result1) => {
              this.bLoading = false;
              if (result1.state == 200) {
                this.historyCustomRemarks1 = result1.data;
              }
            });
        } else {
          this.bLoading = false;
        }
      });
  }
  hideShortcutOrder() {
    this.shortcutModal = false;
  }
  shortcutForm1: FormGroup; //一键发起建单表单
  // 一键建单校验
  // 起点科室校验
  originOfficeShortCutValidator1 = (
    control: FormControl
  ): { [s: string]: boolean } => {
    if (
      this.shortcutForm1 &&
      this.shortcutForm1.value &&
      !control.value &&
      (this.buildMsg1.status == 100013 || this.buildMsg1.status == 100015)
    ) {
      return { required: true };
    }
  };
  // 目标科室校验
  targetOfficeShortCutValidator1 = (
    control: FormControl
  ): { [s: string]: boolean } => {
    if (
      this.shortcutForm1 &&
      this.shortcutForm1.value &&
      !control.value &&
      (this.buildMsg1.status == 100014 || this.buildMsg1.status == 100015)
    ) {
      return { required: true };
    }
  };
  // 建单判断时间-护士端建单通用方法
  isShowConfirm:boolean = true;
  isShowConfirmInfo:string = '';
  newOrderTimeFun(order, fun1, fun2){
    if(this.currentDept.typeValue != 'recovery' && this.currentDept.typeValue != 'surgery'){
      let taskTypeId = order.taskType.id;
      let deptId = order.createDept;
      let maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      this.mainService
      .postCustom("api", "compareWorkTime", {taskTypeId, deptId, yyTime: order.yyTime})
      .subscribe((data) => {
        this.message.remove(maskFlag);
        if(data.state == 200){
          fun2.call(this);
        }else{
          fun1.call(this);
          this.limitTimeModal = true;
          this.limitTimeItem = {taskTypeId, fun1, fun2};
          this.limitTimeInfo = data.data.remark;
          this.isShowConfirm = data.data.limitType == 1;
          if(this.isShowConfirm || data.data.limitNum == 1){
            this.isShowConfirmInfo = '';
          }else{
            this.isShowConfirmInfo = '请在规定时间内下单';
          }
        }
      })
    }else{
      fun2.call(this);
    }
  }
  limitTimeModal: boolean = false; //模态框
  limitTimeInfo:string = '';
  limitTimeItem: any = {};
  hideLimitTimeModal() {
    this.limitTimeModal = false;
  }
  // 确认
  jdFlagId;
  limitTimeLoading:boolean = false;
  confirmLimitTime() {
    console.log(this.limitTimeItem);
    this.limitTimeModal = false;
    this.jdFlagId = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.limitTimeItem.fun2.call(this);
  }
  // 一键发起建单保存
  confirmShortcut1(shortcutForm?) {
    shortcutForm && (this.shortcutForm1 = shortcutForm);
    var that = this;
    for (const i in that.shortcutForm1.controls) {
      that.shortcutForm1.controls[i].markAsDirty();
      that.shortcutForm1.controls[i].updateValueAndValidity();
    }
    console.log(that.shortcutForm1);
    if (that.shortcutForm1.invalid) return;
    shortcutForm && (this.isShowBuildQuickConfirm = false);
    that.btnLoading = true;
    let postData;
    if (that.buildType == "bb") {
      // 标本
      postData = {
        urgent: this.urgentFlag ? 1 : 0,
        workOrder: {
          sourceId: SourceId.hushi,
          workOrderRemark: this.workOrderRemark1,
          taskType: { id: that.shortcutMsg1.id },
          createDept: that.loginUserDeptId,
          startDept: { id: that.loginUserDeptId },
        },
      };
    }
    console.log(postData);
    this.newOrderTimeFun(postData.workOrder, () => {
      this.hideShortcutOrder();
    }, () => {
      that.mainService
        .postCustom("api", "startOrder", postData)
        .subscribe((data) => {
          this.message.remove(this.jdFlagId);
          this.hideShortcutOrder();
          console.log(that.buildType, data.status);
          if (data.status == 200 && that.buildType == "other") {
            that.showPromptModal("创建", true, "", "other");
            this.getTodayNum();
          } else if (data.status == 200 && that.buildType == "bb") {
            that.showPromptModal("创建", true, "", "bb");
            this.getTodayNum();
          } else if (that.buildType == "bb" && data.status == 100043) {
            that.showPromptModal("创建", true, data.msg);
            this.getOrderList();
            this.getSpecimenWorkOrderMsg();
            this.getTodayNum();
          } else if (data.status == 1000033) {
            //重复建单那策略
            this.repeatMsg = data.msg;
            this.showDelModal(postData, "specimen");
          } else {
            that.showPromptModal("创建", false, data.msg);
          }
        });
    });
  }
  repeatModal: boolean = false; //删除模态框
  repeatMsg = "";
  loadingRepeat = false;
  repeatPostData;
  sourceType;
  isYuyue;
  showDelModal(postData, sourceType, yuyue?) {
    this.repeatModal = true;
    this.repeatPostData = postData;
    this.sourceType = sourceType;
    this.isYuyue = yuyue ? yuyue : false;
  }
  hideRepeatModal() {
    this.repeatModal = false;
    this.btnLoading = false;
  }
  confirmRepeat() {
    this.loadingRepeat = true;
    this.repeatPostData.tipsCreateOder = 1;
    this.newOrderTimeFun(this.repeatPostData.workOrder, () => {
      this.loadingRepeat = false;
      this.repeatModal = false;
    }, () => {
      this.mainService
      .postCustom(
        "api",
        this.isYuyue ? "appointmentOrder" : "startOrder",
        this.repeatPostData
      )
      .subscribe((data) => {
        this.message.remove(this.jdFlagId);
        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){
    if (this.sourceType === "specimen") {
      // 标本建单
      if (data.status == 200 && (this.buildType == "other" || this.buildType == "ordinary")) {
        this.showPromptModal("创建", true, "", this.buildType);
        this.getTodayNum();
      } else if (data.status == 200 && this.buildType == "bb") {
        this.showPromptModal("创建", true, "", "bb");
        this.getTodayNum();
      } else if (this.buildType == "bb" && data.status == 100043) {
        this.showPromptModal("创建", true, data.msg);
        this.getOrderList();
        this.getSpecimenWorkOrderMsg();
        this.getTodayNum();
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "other" || this.sourceType === "ordinary") {
      // 其他建单
      if (data.status == 200 && (this.buildType == "other" || this.buildType == "ordinary")) {
        this.showPromptModal("创建", true, "", this.buildType);
        this.getTodayNum();
      } else if (data.status == 200 && this.buildType == "bb") {
        this.showPromptModal("创建", true, "", "bb");
        this.getTodayNum();
      } else if (this.buildType == "bb" && data.status == 100043) {
        this.showPromptModal("创建", true, data.msg);
        this.getTodayNum();
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "transport") {
      // 转运
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "accompany1") {
      // 陪检
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "accompany2") {
      // 陪检
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "accompany3") {
      // 陪检
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "accompany4") {
      // 陪检
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    } else if (this.sourceType === "accompany5") {
      // 陪检
      if (data.status == 200) {
        this.showPromptModal("创建", true, "");
        this.goodsLis = [];
        // this.workOrderInspectScore = undefined;
        this.getOrderList();
        this.getDeptTaskType();
        this.getTodayNum();
      } else if (data.status == 100042) {
        this.showPromptModal("创建", false, data.msg);
        this.getPatient(this.tabSearchCont);
      } else {
        this.showPromptModal("创建", false, data.msg);
      }
    }
  }
  // =======================end=================================

  // 页面中间部分tab切换
  checkedTableType: string = "";
  checkTable(type) {
    if(typeof type === 'object'){
      if(type.system){
        this.checkedTableType = 'other';
      }else{
        this.checkedTableType = type.id;
      }
      this.getDeptTaskType('');
    }else{
      this.checkedTableType = type;
    }
    this.positionY = 0;
    this.selectOtherId = null;
    this.otherSearch = '';
    if (type === "surgery") {
      this.getSurgery(true);
    } else if (type === "outpatientHelpAppointment") {
      this.getOutpatientHelpAppointment(true);
    } else if (type === "historySpecimen") {
      this.getHistorySpecimen(true);
    } else if (type === "historyDrugsbag") {
      this.getHistoryDrugsbag(true);
    } else if (type === "bxlb" && this.isShowBx && this.coopBtns.repairList) {
      this.getBxlb(this.bxlbPageIndex);
      // this.getIncidentState();
      this.getDegrees();
    }
  }
  //提交报修
  bxLoading = false;
  submitBxForm() {
    for (const i in this.bxForm.controls) {
      this.bxForm.controls[i].markAsDirty();
      this.bxForm.controls[i].updateValueAndValidity();
    }
    if (this.bxForm.invalid) return;
    // if(!this.selectIncidentId){
    //   this.message.error("请选择故障现象！");
    //   return;
    // }
    this.bxLoading = true;
    this.mainService.wxbx({}).subscribe((result) => {
      if ((result as any).status == 200) {
        let bxcode = (result as any).data; //生成微信报修号
        let postData = {
          verification: "true",
          incident: {
            branch:this.loginUser.currentHospital.id,
            // contacts: this.loginUser.name,
            deptId:this.loginUser.dept.id,
            // contactsInformation: this.loginUser.phone,
            // address: this.bxForm.controls.address.value,
            // areaId: this.bxForm.controls.hospital.value,
            // contacts: this.bxForm.controls.name.value,
            // contactsInformation: this.bxForm.controls.phone.value,
            description: this.bxForm.controls.content.value,
            categoryId: this.selectIncidentId,
            // placeId: this.bxForm.controls.building.value,
            requester: { account: this.loginUser.account },
            sourceType: "wechatUserIncident",
            fileUrl: "url",
            bxcode,
          },
          loginUser: {
            account: this.loginUser.account,
            id: this.loginUser.id,
          },
        };
        this.mainService.addWxIncident(postData).subscribe((res) => {
          this.bxLoading = false;
          if ((res as any).state == 200) {
            this.showPromptModal("提交", true, "");
            this.checkTable("bxlb");
          } else {
            this.showPromptModal("提交", false, (res as any).msg);
          }
        });
      } else {
        this.bxLoading = false;
        this.showPromptModal("提交", false, "");
      }
    });
  }

  // 意见箱表格数据
  adviceList: any = [];
  advicePageIndex: number = 1; //表格当前页码
  advicePageSize: number = 10; //表格每页展示条数
  adviceListLength: number = 10; //表格总数据量
  adviceSearchInp: string = ""; //意见箱搜索
  adviceLoading = false;
  getAdvice(idx?) {
    if(!this.coopBtns.suggestionBox){
      return;
    }
    if(idx){
      this.advicePageIndex = 1;
    }
    let that = this;
    let postData = {
      advice: {
        content: that.adviceSearchInp || "",
        creatDepartment: {
          id: that.loginUserDeptId,
        },
        createUser: {
          id: that.loginUser.id,
        },
      },
      idx: that.advicePageIndex - 1,
      sum: that.advicePageSize,
    };
    this.adviceLoading = true;
    that.mainService
      .getFetchDataList("adviceCollection", "advice", postData)
      .subscribe((data) => {
        this.adviceLoading = false;
        that.adviceList = data.list || [];
        that.adviceListLength = data.totalNum || 0;
      });
  }

	startDate:any = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	endDate:any = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	scheduleTime: any = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	changeDate(result){
		if(result){
			this.startDate = format(result, 'yyyy-MM-dd') +' '+ '00:00:00';
			this.endDate = format(result, 'yyyy-MM-dd') +' '+'23:59:59';
		}else{
			this.startDate = null
			this.endDate = null
		}
	}

  // 手术排程信息表格数据
  surgeryList: any = [];
  surgeryPageIndex: number = 1; //表格当前页码
  surgeryPageSize: number = 10; //表格每页展示条数
  surgeryListLength: number = 10; //表格总数据量
  surgeryCodeSearchInp: string = ""; //标本编码搜索
  surgeryParentSearchInp: string = ""; //患者信息搜索
  surgeryInfoLoading = false;
  getSurgery(idx?) {
    if (idx) {
      this.surgeryPageIndex = 1;
    }
    let postData:any = {
      surgery: {
				applyDateStart: this.startDate,
				applyDateEnd: this.endDate,
        // hosId: this.currentHospital.id,
      },
      idx: this.surgeryPageIndex - 1,
      sum: this.surgeryPageSize,
    };
    if(this.currentDept.typeValue == 'surgery'){
      postData.surgery.surgeryDept = this.loginUserDeptId;
    }else{
      postData.surgery.areaDept = this.loginUserDeptId;
    }
    this.surgeryInfoLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "surgery", postData)
      .subscribe((data) => {
        this.surgeryInfoLoading = false;
        this.surgeryList = data.list || [];
        this.surgeryListLength = data.totalNum || 0;
      });
  }
  // 门诊帮扶表格数据
  outpatientHelpAppointmentList: any = [];
  outpatientHelpAppointmentPageIndex: number = 1; //表格当前页码
  outpatientHelpAppointmentPageSize: number = 10; //表格每页展示条数
  outpatientHelpAppointmentListLength: number = 10; //表格总数据量
  outpatientHelpAppointmentDateSearchInp = new Date(); //预约时间搜索
  outpatientHelpAppointmentInfoLoading = false;
  getOutpatientHelpAppointment(idx?) {
    if (idx) {
      this.outpatientHelpAppointmentPageIndex = 1;
    }
    let postData:any = {
      patientAppointment: {
        escortTime: this.outpatientHelpAppointmentDateSearchInp ? format(startOfDay(this.outpatientHelpAppointmentDateSearchInp), "yyyy-MM-dd HH:mm:ss") : undefined,
        hosId: this.currentHospital.id,
      },
      idx: this.outpatientHelpAppointmentPageIndex - 1,
      sum: this.outpatientHelpAppointmentPageSize,
    };

    this.outpatientHelpAppointmentInfoLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "patientAppointment", postData)
      .subscribe((data) => {
        this.outpatientHelpAppointmentInfoLoading = false;
        this.outpatientHelpAppointmentList = data.list || [];
        this.outpatientHelpAppointmentListLength = data.totalNum || 0;
      });
  }
  // 历史标本查询表格数据
  historySpecimenList: any = [];
  historySpecimenPageIndex: number = 1; //表格当前页码
  historySpecimenPageSize: number = 10; //表格每页展示条数
  historySpecimenListLength: number = 10; //表格总数据量
  historySpecimenCodeSearchInp: string = ""; //标本编码搜索
  historySpecimenParentSearchInp: string = ""; //患者信息搜索
  hsLoading = false;
  getHistorySpecimen(idx?) {
    if (idx) {
      this.historySpecimenPageIndex = 1;
    }
    let current = JSON.parse(localStorage.getItem("user"));
    let postData = {
      specimen: {
        hosId: this.currentHospital.id,
        sickRoom: {
          id: current.user.dept.id,
        },
        scode:
          this.historySpecimenCodeSearchInp === ""
            ? null
            : this.historySpecimenCodeSearchInp,
        keyWord:
          this.historySpecimenParentSearchInp === ""
            ? null
            : this.historySpecimenParentSearchInp,
      },
      idx: this.historySpecimenPageIndex - 1,
      sum: this.historySpecimenPageSize,
    };
    this.hsLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "specimen", postData)
      .subscribe((data) => {
        this.hsLoading = false;
        this.historySpecimenList = data.list || [];
        this.historySpecimenListLength = data.totalNum || 0;
      });
  }
  // 历史药单查询表格数据
  historyDrugsbagList: any = [];
  historyDrugsbagPageIndex: number = 1; //表格当前页码
  historyDrugsbagPageSize: number = 10; //表格每页展示条数
  historyDrugsbagListLength: number = 10; //表格总数据量
  historyDrugsbagCodeSearchInp: string = ""; //发药单号搜索
  // historyDrugsbagParentSearchInp: string = ""; //患者信息搜索
  hsDLoading = false;
  getHistoryDrugsbag(idx?) {
    if (idx) {
      this.historyDrugsbagPageIndex = 1;
    }
    let current = JSON.parse(localStorage.getItem("user"));
    let postData = {
      drugsBag: {
        target: {
          id: current.user.dept.id,
        },
        packid:
          this.historyDrugsbagCodeSearchInp === ""
            ? ""
            : this.historyDrugsbagCodeSearchInp,
        platform: 2,
      },
      idx: this.historyDrugsbagPageIndex - 1,
      sum: this.historyDrugsbagPageSize,
    };
    this.hsDLoading = true;
    this.mainService
      .getFetchDataList("api", "drugsBag", postData)
      .subscribe((data) => {
        this.hsDLoading = false;
        this.historyDrugsbagList = data.list || [];
        this.historyDrugsbagListLength = data.totalNum || 0;
      });
  }
  // 获取事件状态
  incidentStateId = undefined;
  incidentStateList = [
    {name: '全部', value: 0},
    {name: '待受理', value: 'accept,storage'},
    {name: '处理中', value: 'pending,handler,reassign'},
    {name: '待评价', value: 'close0', hasWxdegree: 0},
    {name: '已关闭', value: 'close1', hasWxdegree: 1},
    {name: '不受理', value: 'reject'},
    {name: '撤销', value: 'cancel'},
  ];
  // getIncidentState() {
  //   let postData = { type: "list", key: "wxincident_state" };
  //   this.iLoading = true;
  //   this.mainService.getDictionaryByITSM(postData).subscribe((data: any) => {
  //     this.iLoading = false;
  //     if (data.status == 200) {
  //       this.incidentStateList = data.data || [];
  //     }
  //   });
  // }
  // 报修列表查询表格数据
  bxlbList: any = [];
  bxlbPageIndex: number = 1; //表格当前页码
  bxlbPageSize: number = 10; //表格每页展示条数
  bxlbListLength: number = 10; //表格总数据量
  bxlbCodeSearchInp: string = ""; //标本编码搜索
  bxlbParentSearchInp: string = ""; //患者信息搜索
  processing: number = 0; //处理中的数量
  bxlbLoading = false;
  repairIncidentTypeList = [];//科室报修或公共报修
  getBxlb(idx, isInitState = false) {
    // 获取事件状态
    this.iLoading = true;
    this.bxlbLoading = true;
    this.mainService.getDictionary('list', 'repair_incident_type').subscribe((data: any) => {
      this.iLoading = false;
      this.repairIncidentTypeList = data || [];
      if(isInitState){
        let valueObj2 = this.incidentStateList.find(v => v.value == 0);
        this.incidentStateId = valueObj2 ? valueObj2.value : undefined;
      }

      // 报修列表查询表格数据
      if (idx) {
        this.bxlbPageIndex = 1;
      }
      let current = JSON.parse(localStorage.getItem("user"));
      this.mainService
        .getFetchDataList("simple/data", "incident", {
          idx: this.bxlbPageIndex - 1,
          sum: this.bxlbPageSize,
          incident: {
            repairIncidentType: { id: this.repairIncidentTypeList.find(v => v.value === 'dept').id },
            statesValues: this.incidentStateId || undefined,
            department: { id: current.user.dept.id },
          }
        })
        .subscribe((data: any) => {
          this.bxlbLoading = false;
          this.bxlbList = data.list || [];
          this.bxlbListLength = data.totalNum || 0;
          this.processing = data.totalNum || 0;
        });
    })
  }

  //快速报修列表
  quickBxlbLoading = false;
  quickBxlbList = [];
  getQuickBxlb() {
    this.quickBxlbLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "incidentCategoryContent", { idx: 0, sum: 10 })
      .subscribe((data: any) => {
        this.quickBxlbLoading = false;
        if (data.status == 200) {
          this.quickBxlbList = data.list || [];
        }
      });
  }

  // 意见箱-查看模态框
  adviceModal: boolean = false;
  adviceDetailInfo: any = {}; //意见详情
  adviceDetail(id) {
    this.adviceModal = true;
    this.mainService
      .getFetchData("adviceCollection", "advice", id)
      .subscribe((data) => {
        this.adviceDetailInfo = data.data;
        console.log(this.adviceDetailInfo);
      });
  }
  hideAdvice() {
    this.adviceModal = false;
  }

  // 意见收集
  adviceSubModal: boolean = false;
  adviceSubContent: string; //填写意见内容
  coopAdviceInfo: any = {}; //当前编辑意见详情
  addAdvice(data?) {
    let that = this;
    that.adviceSubContent = "";
    if (data) {
      that.coopAdviceInfo = data;
      that.adviceSubContent = data.content;
    }
    that.adviceSubModal = true;
  }
  hideSubAdvice() {
    this.adviceSubModal = false;
  }
  // 提交意见内容
  confirmSubAdvice() {
    let that = this;
    if (!that.adviceSubContent) return;
    that.btnLoading = true;
    let postData = {
      advice: {
        creatDepartment: {
          id: that.loginUserDeptId,
        },
        createUser: {
          id: that.loginUser.id,
        },
        content: that.adviceSubContent,
      },
    };
    if (that.coopAdviceInfo.id) {
      postData.advice["id"] = that.coopAdviceInfo.id;
    }

    that.mainService
      .postCustom(
        "adviceCollection",
        that.coopAdviceInfo.id ? "updData/advice" : "addData/advice",
        postData
      )
      .subscribe((data) => {
        if (data.status == 200) {
          that.adviceSubModal = false;
          that.showPromptModal(
            that.coopAdviceInfo.id ? "编辑" : "新增",
            true,
            ""
          );
          that.coopAdviceInfo = {};
          that.adviceSubContent = "";
          that.getAdvice();
        } else {
          that.adviceSubModal = false;
          that.showPromptModal(
            that.coopAdviceInfo.id ? "编辑" : "新增",
            false,
            data.msg
          );
          that.adviceSubContent = "";
        }
      });
  }
  // 查看标本详情
  detailModel: boolean = false;
  loading33: boolean = false;
  detailList: any = [];
  // 选择急查或普查(1是急标，0是普标)
  changeSpeDetail(e, speDetailType: number) {
    e.stopPropagation();
    this.detailModel = true;
    let user = JSON.parse(localStorage.getItem("user"));
    let postData = {
      deptId: user.user.dept.id,
      urgent: speDetailType,
    };
    this.loading33 = true;
    this.mainService
      .postCustom("nurse", "getSpecimenWorkOrderDetails", postData)
      .subscribe((result) => {
        this.loading33 = false;
        if (result.status == 200) {
          this.detailList = result.data || [];
        }
      });
  }

  // 跳转患者陪检闭环视图
  changeInspectClosedLoopView(e, stateValue){
    e.stopPropagation();
    let queryParams = {
      department: { id: this.currentDept.id, dept: this.currentDept.dept },
      stateValue,
    }
    this.router.navigateByUrl(`/inspectClosedLoopView?queryParams=${JSON.stringify(queryParams)}`);
  }

  // 标本打包弹窗
  toSpecimenPackage(e, stateValue){
    e.stopPropagation();
    this.viewSpecimenPackageList(stateValue);
  }
  // 隐藏查看标本详情弹层
  hideSpeDetailModel() {
    this.detailModel = false;
  }
  // 意见删除模态框
  delAdviceModal: boolean = false;
  delAdviceId: number; //删除意见id
  delAdvice(id) {
    this.delAdviceId = id;
    this.delAdviceModal = true;
  }
  confirmDelAdvice() {
    let that = this;
    that.btnLoading = true;
    let postData = [that.delAdviceId];
    that.mainService
      .postCustom("adviceCollection", "rmvData/advice", postData)
      .subscribe((data) => {
        if (data.status == 200) {
          that.delAdviceModal = false;
          that.showPromptModal("删除", true, "");
          if (
            that.adviceList.length == 1 &&
            that.advicePageIndex ==
              Math.ceil(that.adviceListLength / that.advicePageSize)
          ) {
            that.adviceListLength--;
            that.advicePageIndex = Math.ceil(
              that.adviceListLength / that.advicePageSize
            );
          }
          that.getAdvice();
        } else {
          that.delAdviceModal = false;
          that.showPromptModal("删除", false, data.msg);
        }
      });
  }
  hideDelAdviceModal() {
    this.delAdviceModal = false;
  }
  // 追加检查删除模态框
  delInspectModal: boolean = false;
  delInspectId: number; //删除id
  btnLoading4:boolean = false;
  delInspect(id) {
    this.delInspectId = id;
    this.delInspectModal = true;
  }
  confirmDelInspect() {
    this.btnLoading4 = true;
    this.mainService
      .coopData("rmvData", "inspect", [this.delInspectId])
      .subscribe((data) => {
        this.delInspectModal = false;
        this.btnLoading4 = false;
        if (data.status == 200) {
          this.message.success('删除检查成功！')
          this.refreshInspectList();
        } else {
          this.message.error(data.msg || '删除检查失败！')
        }
      });
  }
  hideDelInspectModal() {
    this.delInspectModal = false;
  }
  // 报修撤销模态框
  delBxModal: boolean = false;
  delBxData: any; //删除的data
  delBx(data) {
    this.delBxData = data;
    this.delBxModal = true;
  }
  confirmDelBx() {
    this.btnLoading = true;
    this.mainService
      .flowPost("incident/task/cancel", { incident: this.delBxData })
      .subscribe((result) => {
        if(result.state == 200){
          this.delBxModal = false;
          this.showPromptModal("撤销", true, "");
          this.getBxlb(true);
        }else{
          this.delBxModal = false;
          this.showPromptModal("撤销", false, result.msg);
        }
      });
  }
  hideDelBxModal() {
    this.delBxModal = false;
  }
  // 报修提示框
  reqModal: boolean = false;
  extraData:any = {};
  showReqModal() {
    this.extraData.floor = this.floors.find(v => v.id == this.validateBxForm.value.floor);
    // this.reqModal = true;
    this.confirmBxNext(0);
  }
  confirmReq() {
    this.confirmBxNext(1);
  }
  cancelReq() {
    this.confirmBxNext(0);
  }
  hideReqModal() {
    this.reqModal = false;
  }
  // 工单列表下拉筛选
  selectedType: null;
  changeOrderSel(e) {
    this.selectedType = e;
    this.getOrderList();
  }
  // 工单列表工单状态下拉筛选
  changeOrderState(e) {
    this.getOrderList();
  }
  // 工单列表
  orderList: any = [];
  orderIdx: number = 1;
  orderLength: number = 10;
  OLoading: boolean = true;
  getOrderList() {
    let that = this;
    that.orderList = [];
    that.OLoading = true;
    let postData: any = {
      workOrder: {
        createDept: JSON.parse(localStorage.getItem("user")).user.dept.id,
        platform: 2,
        searchDays: 2,
        taskType: {},
      },
      idx: that.orderIdx - 1,
      sum: 10,
    };
    if (that.selectedType && that.selectedType != -1) {
      postData.workOrder.taskType["associationType"] = {
        id: that.selectedType,
      };
    }
    // 执行中包含状态：待抢单、待接单、待到达、待送达、执行中、定时预约
    if (that.orderStateSelected == "1") {
      //执行中
      delete postData.workOrder.gdState;
      postData.workOrder.nurseState = 1;
    } else if (that.orderStateSelected == "2") {
      //待评价
      delete postData.workOrder.nurseState;
      postData.workOrder.gdState = { id: "73" };
    } else {
      //全部
      delete postData.workOrder.nurseState;
      delete postData.workOrder.gdState;
    }
    that.mainService
      .getFetchDataList("nurse", "workOrder", postData)
      .subscribe((data) => {
        that.orderList = data.list || [];
        //显示三项
        that.orderList.forEach((item) => {
          if (item.record.length > 2) {
            let i = item.record
              .reverse()
              .findIndex((step) => step.record.length > 0);
            item.record.reverse();
            i = item.record.length - 1 - i;
            if (i < 2) {
              item.record = item.record.slice(0, 3);
            } else if (i > item.record.length - 2) {
              item.record = item.record.slice(
                item.record.length - 3,
                item.record.length
              );
            } else {
              item.record = item.record.slice(i - 1, i + 2);
            }
          }
        });
        that.orderLength = data.totalNum || 0;
        that.OLoading = false;
      });
  }

  // 撤销
  coopId: number;
  recallOrderModal: boolean = false;
  // 打开撤销模态框
  openRecallModal(id) {
    this.coopId = id;
    this.recallOrderModal = true;
  }
  // 确认撤销
  confirmRec() {
    let that = this;
    that.btnLoading = true;
    that.mainService.delOrder(that.coopId).subscribe((data) => {
      that.closeRecallOrderModal();
      if (data.status == 200) {
        that.getOrderList();
        that.changeInfo();
        this.getTodayNum();
        that.showPromptModal("撤销", true, "");
      } else {
        that.showPromptModal("撤销", false, data.msg);
      }
    });
  }
  // 关闭撤销模态框
  closeRecallOrderModal() {
    this.recallOrderModal = false;
  }

  // 打印二维码-门诊服务点---------------start
  outpatientServiceMsg = "";
  coopOutpatientServiceItem: any;
  outpatientServiceModal: boolean = false;
  // 打开模态框
  openOutpatientServiceModal(item) {
    this.coopOutpatientServiceItem = item;
    this.outpatientServiceMsg = `提示：打印<strong class='red'>${item.patientName}</strong>患者二维码，可用于身份识别`
    this.outpatientServiceModal = true;
  }
  // 确认
  cardNoDto: any = {};
  confirmOutpatientService() {
    this.btnLoading = true;
    this.mainService.qrcodeCardNo({id: this.coopOutpatientServiceItem.id, fieldName: 'cardNo'}).subscribe((data) => {
      this.closeOutpatientServiceModal();
      this.btnLoading = false;
      if (data.state == 200) {
        data.logo = location.origin + '/file' + data.logo || '';
        this.cardNoDto = data;
        this.getPatient();
        // 打印
        setTimeout(()=>{
          this.printBtn.nativeElement.click();
        }, )
      } else {
        this.showPromptModal("打印", false, data.msg);
      }
    });
  }
  // 关闭模态框
  closeOutpatientServiceModal() {
    this.outpatientServiceModal = false;
  }
  // 打印二维码-门诊服务点---------------end

  // 评价
  appraiseModal: boolean = false;
  starNum: number = 5; //评价星
  appraiseContent: string = ""; //评级
  appraiseId: number;
  showAppraise(id) {
    this.appraiseId = id;
    this.appraiseModal = true;
    this.starNum = 5;
    this.appraiseContent = "";
  }
  // 保存评价
  confirmAppraise() {
    console.log(this.starNum, this.appraiseContent);
    let that = this;
    if (!that.starNum) return;
    that.btnLoading = true;
    let id;
    switch (that.starNum) {
      case 1:
        id = 358;
        break;
      case 2:
        id = 357;
        break;
      case 3:
        id = 356;
        break;
      case 4:
        id = 355;
        break;
      case 5:
        id = 354;
        break;
    }
    let postData = {
      serviceEvaluation: { id: id },
      remark: that.appraiseContent,
    };
    this.mainService
      .postCustom("nurse/workOrder", "evaluate/" + this.appraiseId, postData)
      .subscribe((data) => {
        that.hideAppraise();
        if (data.status == 200) {
          that.getOrderList();
          that.showPromptModal("评价", true, "");
        } else {
          that.showPromptModal("评价", false, data.msg);
        }
      });
  }
  hideAppraise() {
    this.appraiseModal = false;
  }

  // 报修评价
  appraiseModalBx: boolean = false;
  starNumBx: number = 5; //评价星
  appraiseContentBx: string = ""; //评级
  appraiseDataBx: any;
  showAppraiseBx(data) {
    this.appraiseDataBx = data;
    this.appraiseModalBx = true;
    this.starNumBx = 5;
    this.appraiseContentBx = "";
  }
  // 保存评价
  confirmAppraiseBx() {
    console.log(this.starNumBx, this.appraiseContentBx);
    if (!this.starNumBx) return;
    this.btnLoading = true;
    let id = this.degrees.find(v=>v.value == this.starNumBx).id;
    let postData = {
      incident: {
        ...this.appraiseDataBx,
        wxdegree: { id },
        wxdegreeremark: this.appraiseContentBx,
      }
    };
    this.mainService
      .flowPost("incident/task/resolve", postData)
      .subscribe((data:any) => {
        this.hideAppraiseBx();
        if (data.state == 200) {
          this.getBxlb(this.bxlbPageIndex);
          this.showPromptModal("评价", true, "");
        } else {
          this.showPromptModal("评价", false, data.msg);
        }
      });
  }
  hideAppraiseBx() {
    this.appraiseModalBx = false;
  }

  // 审核状态
  checkStatusLis: any = [];
  getCheckStatusLis() {
    let that = this;
    that.mainService.getDictionary("list", "check_status").subscribe((data) => {
      that.checkStatusLis = data;
    });
  }

  // 填写加急原因模态框
  jiajiModal: boolean = false;
  jiajiContent: string; //加急原因
  jiajiId; //加急工单id
  showJiaji(id) {
    this.jiajiId = id;
    this.jiajiModal = true;
    this.jiajiContent = "";
  }
  hideJiaji() {
    this.jiajiModal = false;
  }
  // 保存加急原因
  confirmJiaji() {
    let that = this;
    let checkStatusId;
    if (!that.jiajiContent) return;
    that.btnLoading = true;
    that.checkStatusLis.forEach((e) => {
      if (e.value == 1) {
        checkStatusId = e.id;
      }
    });

    let postData = {
      urgentDetails: {
        workerOrder: that.jiajiId,
        checkStatus: { id: checkStatusId },
        urgentReason: that.jiajiContent,
      },
    };
    that.mainService
      .postCustom("workerOrder", "urge", postData)
      .subscribe((data) => {
        if (data.status == 200) {
          that.showPromptModal("加急", true, "");
          that.getOrderList();
          that.hideJiaji();
        } else {
          that.showPromptModal("加急", false, data.msg);
        }
      });
  }

  // 查看工单详情
  openDetails(data) {
    if (data.taskType.associationType.value == 'specimen' || data.taskType.associationType.value == 'specimenPlan') {
      // 标本类
      this.router.navigateByUrl("nurse/detailSample/" + data.id);
    } else if (data.taskType.associationType.value == 'inspect' || data.taskType.associationType.value == 'patientTransport') {
      // 送患者
      this.router.navigateByUrl("nurse/detailPatients/" + data.id);
    } else if (data.taskType.associationType.value == 'drugsBag' || data.taskType.associationType.value == 'jPBag') {
      // 药品配送/静配
      this.router.navigateByUrl("nurse/detailDrug/" + data.id);
    } else if (data.taskType.associationType.value == 'ordinary') {
      // 万能交接服务
      this.router.navigateByUrl("nurse/detailOrdinary/" + data.id);
    } else {
      // 其他
      this.router.navigateByUrl("nurse/detailOthers/" + data.id);
    }
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?, back?) {
    this.btnLoading = false;
    this.btnLoading1 = false;
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    this.back = back;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
  }

  // 回到系统管理
  toMain() {
    this.router.navigateByUrl("main");
  }
  // 查看工单
  toOrder() {
    this.router.navigateByUrl(`main/orderManagement`);
  }

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

    // 假退出
    that.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");
      }
    });
  }

  // 格式化时分秒
  // （时间小于一分钟则显示秒，时间大于一分钟则显示分钟数，如超出一小时则显示小时和分钟。）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;
  }

  // 计算历史记录耗时
  filterTime(step) {
    let num = 0;
    step.forEach((e) => {
      num += e.difTime;
    });
    return this.formatTime(num / 1000);
  }

  // 截取意见内容(ie内核截取)
  spliceContent(con) {
    if (con.length >= 41 && navigator.userAgent.indexOf("Trident") > -1) {
      return con.slice(0, 41) + "...";
    } else {
      return con;
    }
  }

  @ViewChild("msgTemplate", { static: false }) msgTemplate: TemplateRef<any>; //消息通知模板
  // 消息提醒
  createBasicNotification(msgs): void {
    this.notification.template(this.msgTemplate, {
      nzDuration: 0,
      nzData: msgs,
    });
  }
  isShowNurseCode = false; //是否展开科室二维码
  nurseCodeImg = ""; //图片
  refreshQRCodeTime = 0; //刷新时间间隔
  // 关闭科室二维码
  closeNurseCode() {
    this.isShowNurseCode = false;
    clearInterval(this.timer);
    this.timer = null;
  }
  // 展开科室二维码
  timer = null;
  showNurseCode() {
    this.isShowNurseCode = true;
		this.getConfig()
  }

	// 获取配置
	iskeySwitch:any = false;
	getConfig() {
	  let postData = {
	    idx: 0,
	    sum: 9999,
			hospitalConfig:{
				hosId:this.currentHospital.id,
				model:"all"
			}
	  };
	  this.mainService.getFetchDataList("simple/data", "hospitalConfig", postData).subscribe((result:any) => {
	      if (result.status == 200) {
					for(let i of result.list){
						if(i.key=='digitalSecretKey'){
							if(i.value==1){
								this.iskeySwitch = true
								this.getSecretKey()
							}else{
								this.iskeySwitch = false
								this.mainService.getDeptCode([this.loginUserDeptId]).subscribe((data) => {
								  if (data["status"] == 200) {
								    this.nurseCodeImg = data["data"][0].base64;
								    this.refreshQRCodeTime = data["data"][0].refreshQRCodeTime;
								    clearInterval(this.timer);
								    this.timer = setInterval(() => {
								      this.refreshQRCodeTime = Math.max(--this.refreshQRCodeTime, 0);
								      if (this.refreshQRCodeTime === 0) {
								        clearInterval(this.timer);
								        this.showNurseCode();
								      }
								    }, 1000);
								  }
								});
							}
						}
					}
	      }
	    });
	}

	// 获取动态密钥
	numberKey:any;
	getSecretKey(){
		this.mainService.getSecretKey(this.currentDept.id).subscribe((res:any) => {
      if (res["status"] == 200) {
        this.numberKey = res.data.digitalSecretKey;
				this.nurseCodeImg = res.data.base64;
				this.refreshQRCodeTime = res.data.refreshQRCodeTime;
				clearInterval(this.timer);
				this.timer = setInterval(() => {
				  this.refreshQRCodeTime = Math.max(--this.refreshQRCodeTime, 0);
				  if (this.refreshQRCodeTime === 0) {
				    clearInterval(this.timer);
				    this.showNurseCode();
				  }
				}, 1000);
      }
    });
	}

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

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

  mainRole: boolean = false; //回到系统管理权限
  mainRoleBtnName = "回到系统管理"; //回到系统管理名字
  initRole() {
    let menus = JSON.parse(localStorage.getItem("menu"));
    console.log("菜单数量" + menus.length);
    if (menus.length >= 2) {
      this.mainRole = true;
      return;
    }
  }

  // 切换右侧菜单Tab
  fixedTab: string = "";
  checkFixedTab(type: string) {
    if (type == "toSystem") {
      this.router.navigateByUrl("main");
    }
    if (this.fixedTab == type) {
      this.fixedTab = "";
    } else {
      this.fixedTab = type;
    }
  }
  //子传父接收
  closeModelHs(e) {
    this.hsPromptModalShow = JSON.parse(e).show;
    this.changeShow = JSON.parse(e).changeShow;
  }
  //子传父接收
  clearModelHs(e) {
    if (JSON.parse(e).clear === true) {
      clearInterval(this.timerCloseTime);
    }
    this.changeShow = JSON.parse(e).changeShow;
  }
  // 头部切换科室
  changeKsNow() {
    this.hsPromptModalShow = true;
    clearInterval(this.timerCloseTime);
    this.changeShow = false;
  }
  // 刷新工单列表
  refreshList(e) {
    if (!e.promptContent) {
      return;
    }
    this.getOrderList();
  }
  // 打印二维码-门诊服务点
  printCode(item){
    console.log(item)
  }

  //打开修改密码弹窗
  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.message.error('请填写原始密码！', {
        nzDuration: 5000,
      });
      return;
    }
    if(!this.strongRegFlag){
      this.message.error('新密码不符合要求！', {
        nzDuration: 5000,
      });
      return;
    }
    if(this.upModalData.newPwd !== this.upModalData.newPwd2){
      this.message.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.message.success("修改成功！", {
          nzDuration: 5000,
        });
      } else {
        this.pwdIsOkLoading = false;
        this.message.error(data.error, {
          nzDuration: 5000,
        });
      }
    });
  }
  showUpPwd(): void {
    this.isPwdVisible = true;
  }

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

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

  // 新密码失去焦点
  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);
  }

  // 快捷方式建单
  isShowBuildQuickConfirm:boolean = false;
  buildQuickConfirmData:any = {};
  buildQuick(data){
    if(data.bussType.value === 'service'){
      // 运维报修
      this.showBxModal();
    }else if(data.icon.value === 'specimenPackage'){
      // 标本打包
      this.router.navigateByUrl("/batchSpecimen");
    }else if(data.bussType.value === 'goods'){
      // 物品配送
      this.buildQuickConfirmData = data || {};
      this.isShowBuildQuickConfirm = true;
    }else if(data.bussType.value === 'inspect'){
      // 陪检
      if(this.inspectAndPatientTransportConfig.batchInspectType == 1){
        // 预约陪检
        this.router.navigateByUrl("/batchInspection");
      }else if(this.inspectAndPatientTransportConfig.batchInspectType == 2){
        // 陪检信息配置
        this.router.navigateByUrl("/inspectInfoConfig");
      }
    }
  }
  cancelBuildQuickConfirm(e){
    this.isShowBuildQuickConfirm = false;
  }
  loadingQuick:boolean = false;
  confirmBuildQuickConfirm(options){
    let { taskType, shortcutForm, buildMsg, workOrderRemark, userAccount } = options;
    if(taskType.associationType.value === 'other' || taskType.associationType.value === 'ordinary'){
      // 其他临床服务|万能交接
      this.loadingQuick = this.loading5;
      this.buildType = taskType.associationType.value;
      this.shortcutMsg = taskType;
      this.buildMsg = buildMsg;
      this.workOrderRemark = workOrderRemark;
      this.userAccount = userAccount;
      this.confirmShortcut(shortcutForm, taskType.associationType.value);
    }else if(taskType.associationType.value === 'specimen'){
      // 标本配送
      this.loadingQuick = this.btnLoading;
      this.buildType = "bb";
      this.shortcutMsg1 = taskType;
      this.workOrderRemark1 = workOrderRemark;
      this.confirmShortcut1(shortcutForm);
    }
  }

  // 详细地址获取焦点
  isShowAddressList:boolean = false;
  focusAddress(){
    this.isShowAddressList = true;
    this.getAddressList();
  }

  // 点击其他位置
  clickExtra(e){
    if(document.documentElement.contains(document.querySelector('.addressList')) && e.target !== document.querySelector('.addressFocus')){
      this.isShowAddressList = false;
    }
    if(document.documentElement.contains(document.querySelector('.noteList')) && e.target !== document.querySelector('.noteFocus')){
      this.isShowNoteList = false;
    }
  }

  // 选择地址
  selectAddress(name){
    this.validateBxForm.controls.officeAddress.setValue(name)
    this.isShowAddressList = false;
  }

  // 获取科室地点列表
  addressList:any[] = [];
  addressLoading:boolean = false;
  getAddressList() {
    let postData = {
      idx: 0,
      sum: 99999,
      qrCode: {
        deptId: this.loginUserDeptId,
      }
    };
    this.addressLoading = true;
    this.mainService.getFetchDataList("simple/data", "qrCode", postData).subscribe(result=>{
      this.addressLoading = false;
      if(result.status == 200){
        this.addressList = result.list || [];
      }else{
        this.addressList = [];
      }
    });
  }

  // 注意事项获取焦点
  isShowNoteList:boolean = false;
  focusNote(){
    this.isShowNoteList = true;
    this.getNoteList();
  }

  // 选择注意事项
  selectNote(name){
    this.workOrderRemark2 = name;
    this.isShowNoteList = false;
  }

  // 获取注意事项列表
  noteList:any[] = [];
  noteLoading:boolean = false;
  getNoteList() {
    this.noteLoading = true;
    this.mainService.getDictionary('list', 'inspect_notes',).subscribe(result=>{
      this.noteLoading = false;
      this.noteList = result || [];
    });
  }

  // 关联的检查-上一日，下一日，今天
  inspectToday:Date = new Date();
  // 上一日
  previousDayNew(){
    this.inspectToday = addDays(this.inspectToday, -1);
    this.inspectSubject.next();
  }

  // 今天
  todayNew(){
    this.inspectToday = new Date();
    this.inspectSubject.next();
  }

  // 下一日
  nextDayNew(){
    this.inspectToday = addDays(this.inspectToday, 1);
    this.inspectSubject.next();
  }

  refreshInspectList(){
    let postData = {
      taskTypeId: this.patientForm.controls.checkedType.value,
      patientCode: this.patientMsg.patientCode,
      startTime: format(startOfDay(this.inspectToday), 'yyyy-MM-dd HH:mm:ss'),
      endTime: format(endOfDay(this.inspectToday), 'yyyy-MM-dd HH:mm:ss'),
    };
    this.linkCheckLis = [];
    this.mainService
      .postCustom("nurse", "workOrder/buildTrip", postData)
      .subscribe((data) => {
        // 工单备注配置 end
        if (data.status == 200 && data.data && data.data.length) {
          let arr = [];
          data.data.forEach((e) => {
						if(e.yyTime){
							e.newTime = format(new Date(e.yyTime), 'MM-dd HH:mm')
							if(e.endCheckTime){
								e.newTime2 = format(new Date(e.endCheckTime), 'HH:mm')
								e.yyEndTime = e.newTime + '--' + e.newTime2
							}else{
								e.yyEndTime = e.newTime
							}
						}else{
							e.yyEndTime = null
						}

            arr.push({
              execDeptId: e.execDept.id,
              yyTime: e.yyTime,
              priority: e.priority,
              manualCreate: e.manualCreate,
              label:
                (e.yyEndTime|| "") +
                " " +
                (this.deptDisplay == 2
                  ? e.execDept.deptalias
                  : e.execDept.dept) +
                " 进行 " +
                (e.inspectName?e.inspectName:'' + '-' + e.inspectCode || "检查"),
              value: e["id"],
              checked: false,
              remark: e.remark,
            });
          });
          this.linkCheckLis = arr;
        }
      });
  }

  // 查看标本打包
  specimenPackageStateValue;
  isShowSpecimenPackageList = false; //业务数据弹窗开关
  viewSpecimenPackageList(stateValue) {
    this.specimenPackageStateValue = stateValue;
    this.isShowSpecimenPackageList = true;
  }
  // 关闭标本打包弹窗
  closeSpecimenPackageList(e) {
    this.isShowSpecimenPackageList = JSON.parse(e).show;
  }

  // 追加检查
  isShowAddInspect = false; //弹窗开关
  addInspect(){
    this.isShowAddInspect = true;
  }
  // 关闭弹窗
  closeAddInspectModel(e) {
    this.isShowAddInspect = JSON.parse(e).show;
  }
  // 确定弹窗
  confirmAddInspectModel(e) {
    console.log(e);
    let obj = JSON.parse(e);
    this.isShowAddInspect = obj.show;
		let user = JSON.parse(localStorage.getItem("user"));
    if(obj.type == 2){
      // 手动添加
      let postData:any = {
        inspectList: obj.list.map(v => ({
          patientCode: this.patientMsg.patientCode,
          patientName: this.patientMsg.patientName,
          barCode: this.patientMsg.barCode,
          inspectCheckType: { id: v.id },
          applyDeptId: user.user.dept.id,
          bedNum: this.patientMsg.bedNum,
          hosId: this.patientMsg.hosId,
        })) || undefined,
      };
      this.maskFlag = this.message.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      this.mainService
        .simplePost("addData", "inspect", postData)
        .subscribe((data:any) => {
          this.message.remove(this.maskFlag);
          this.maskFlag = false;
          if (data.status == 200) {
            this.message.success('追加检查成功！')
            this.refreshInspectList();
          } else {
            this.message.error(data.msg || '追加检查失败！')
          }
        });
    }else{
			let postData:any = {
			  inspectList: [{
			    patientCode: this.patientMsg.patientCode,
			    patientName: this.patientMsg.patientName,
			    barCode: this.patientMsg.barCode,
			    inspectCheckType: { id: obj.inspectData.id },
			    applyDeptId: user.user.dept.id,
			    execDeptId: obj.inspectData.execDeptId,
			    bedNum: this.patientMsg.bedNum,
			    hosId: this.patientMsg.hosId,
			    yyTime: format(new Date(obj.inspectData.date), 'yyyy-MM-dd ') + format(startOfMinute(new Date(obj.inspectData.time)), 'HH:mm:ss'),
					endCheckTime: obj.inspectData.endCheckTime
				}] || undefined,
			};
			this.maskFlag = this.message.loading("正在加载中..", {
			  nzDuration: 0,
			}).messageId;
			this.mainService
			  .simplePost("addData", "inspect", postData)
			  .subscribe((data:any) => {
			    this.message.remove(this.maskFlag);
			    this.maskFlag = false;
			    if (data.status == 200) {
			      this.message.success('追加检查成功！')
			      this.refreshInspectList();
			    } else {
			      this.message.error(data.msg || '追加检查失败！')
			    }
			  });
		}
  }
}
