import { Component, OnInit, ViewChild, OnDestroy } from "@angular/core";
import { MainService } from "../../services/main.service";
import { ActivatedRoute, Router } from "@angular/router";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { startOfDay, format, endOfDay } from "date-fns";
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from "ng-zorro-antd";
import { debounceTime } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';

import {
  FormBuilder,
  Validators,
  FormGroup,
  FormControl,
} from "@angular/forms";

@Component({
  selector: "app-pathologyScan",
  templateUrl: "./pathologyScan.component.html",
  styleUrls: ["./pathologyScan.component.less"],
})
export class PathologyScanComponent implements OnInit, OnDestroy {
  @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;
  constructor(
	private mainService: MainService,
	public router: Router,
	private route: ActivatedRoute,
	public tool: ToolService,
	private fb: FormBuilder,
	private message: NzMessageService,
	private sanitizer: DomSanitizer,

	) {}
  // 今日药单量
  todayTotal: undefined;
  // 今日已完成
  todayComplete: undefined;
  //手术间数据
  printPharmacyList = []; //数据列表
  printPharmacyIdx = 0; //页码
  printPharmacyTotal = 0; //总数
  printPharmacyFlag = false; //是否查看更多
  printPharmacySearchKey = ""; //搜索的内容
  printPharmacyLoad = false; //按钮的loading
  // 标本间列表
  waitPharmacyList = [];
  waitPharmacyIdx = 0;
  waitPharmacyTotal = 0;
  waitPharmacyFlag = false;
  waitPharmacySearchKey = "";
  waitPharmacyLoad = false;
  // 今日离科列表
  pharmacyList = [];
  pharmacyIdx = 0;
  pharmacyTotal = 0;
  pharmacyFlag = false;
  pharmacySearchKey = "";
  pharmacyLoad = false;
  // 配送中列表
  distributionList = [];
  distributionIdx = 0;
  distributionTotal = 0;
  distributionFlag = false;
  distributionSearchKey = "";
  distributionLoad = false;
  // 已完成列表
  completedList = [];
  completedIdx = 0;
  completedTotal = 0;
  completedFlag = false;
  completedSearchKey = "";
  completedLoad = false;

	barCode:any; //条码搜索
  // other
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息

  logTimer = null; //定时器
  logTime = 0; //自动刷新秒数
  logTimeConst = 60; //自动刷新秒数

  time = new Date().getTime(); // 时间戳
  timer = null; // 时间定时器
	relevanceModal:boolean = false //关联标本和手术室
	validateForm: FormGroup; //关联标本和手术室表单
	validateVerificationForm: FormGroup; //核验标本
	validateConnectForm: FormGroup; //核验标本
	specimenData:any = []; //标本间数据
	operationData:any = []; //手术间数据
	fixationModal:boolean = false //标本接收固定
	verificationMoadl:boolean = false //标本核验
	specimenCode:any; //标本条码
	listOneData:any=[];
	listOneLength:any;
	pageOneIndex:any = 1;
	pageSize:any = 10;
	listTwoData:any=[];
	listTwoLength:any;
	pageTwoIndex:any = 1;
	listThreeData:any=[];
	listThreeLength:any;
	pageThreeIndex:any = 1;
	loading1:boolean = false;
	loading2:boolean = false;
	loading3:boolean = false;
	loading4:boolean = false;
	loading5:boolean = false;
	fixativeData:any = []; //固体液类型
	hosId:any;
	userId:any;
	detailsData:any;
	isSpinning:boolean = false; //全屏加载状态
	codeData:any = []; //标本条码数据
	btnInfoLoading :boolean = false; //标本加固加载
	activeIndex:any = 0; //tabs选择状态
	changeInpSubject = new Subject(); //防抖
	changeInpSubjectUser = new Subject(); //防抖
	changeInpSubjectDepartment = new Subject(); //防抖
	intraoperativeRapidity:any = null; //术中快速
	deliveryUser:any //配送人
	acceptTime:any; //接收时间
	userData:any = []; //配送人数据
	isLoading:boolean = false;
	listDetailMoadl:boolean = false; //详情弹框
	department:any = []; //科室数据
	hospital:any = []; //院区数据
	distributionName:any;
	businessType:any = null;
	multiModal:boolean = false;
	specimenMultiCode:any = null;
	codeMultiData:any=[];
	errorMultiMsg:any = null;
	connectModal:boolean = false; //标本交接弹框
	receptionModal:boolean = false; //标本接收弹框
	deptId:any = null;
	detailMoadl:boolean = false;
	scanCodeData:any = null;
	batchNo:any = null;
	dataType:any = null;
	muArr:any = [];
	packId:any = null;
	userInfo:any = null;
	placeholder:any = null;
	placeholderType:any = null;
  ngOnDestroy() {
    clearTimeout(this.timer);
    clearTimeout(this.logTimer);
  }

  ngOnInit() {
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchSpecimenData(v[0])
		});
		// this.changeInpSubjectDepartment.pipe(debounceTime(500)).subscribe((v) => {
		//   this.getDepartmentData(v[0])
		// });
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId()
		this.deptId = this.tool.getCurrentUserDept().id
		this.userInfo = this.tool.getCurrentUserInfo()
		this.batchNo = this.route.snapshot.queryParams.batchNo
		this.businessType = this.route.snapshot.queryParams.businessType
		this.placeholderType = this.route.snapshot.queryParams.placeholder
		this.packId = this.route.snapshot.queryParams.packId //打包配送查看标本
		if(this.placeholderType==1){
			this.placeholder = '可扫描物理标本条码'
		}else{
			this.placeholder = '可扫描物理标本条码及包码'
		}
		let scanData = localStorage.getItem("scanCodeData")
		//dataType类型：receive：病理科接收标本，pack:病理科打包标本
		//pathologyPack: 病理包扫码
		this.dataType = localStorage.getItem("dataType")
		if(this.packId && this.businessType=='packagLook'){
			this.getJsData(5)
			return
		}
		if(scanData){
			let data = JSON.parse(localStorage.getItem("scanCodeData"))
			this.scanCodeData = data.data[0]
			// 包的状态为配送中展示配送接收弹框
			if(this.dataType=='pathologyPack'){
				this.getJsData(4)
			}
			if(this.scanCodeData.pathologySpecimenDTOList &&
			this.scanCodeData.pathologySpecimenDTOList.length>1){
				this.muArr = []
				for(let i of this.scanCodeData.pathologySpecimenDTOList){
					if(i.isScan==1){
						this.muArr.push(i)
					}
				}
				this.getJsData(3)
			}else if(this.scanCodeData.pathologySpecimenDTOList &&
			this.scanCodeData.pathologySpecimenDTOList.length==1){
				this.getJsData(1)
			}
		}else{
			if(this.placeholderType==1){
				if(this.businessType=='connect'){
					this.dataType = 'receive'
				}else if(this.businessType=='packaging'){
					this.dataType = 'pack'
				}
			}
			this.getJsData(1)
		}

  }

	// 分页
	noType:any='none';
	pageChange(){
		if(this.dataType=='pathologyPack'){
			this.noType='show'
			this.getJsData(4)
		}else if(this.packId && this.businessType=='packagLook'){
			this.getJsData(5)
		}else{
			this.getJsData(1)
		}
	}

  // 当前时间日期
  runTime() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.time = Date.now();
      this.runTime();
    }, 500);
  }

	// 交接
	connect(){
		this.fixationModal = true
		this.businessType = 'connect'
		setTimeout(_=>{
			document.getElementById('specimen').focus();
		},200)
	}

	// 打包
	packaging(){
		this.fixationModal = true
		this.businessType = 'packaging'
		setTimeout(_=>{
			document.getElementById('specimen').focus();
		},200)
	}

	// 配送
	distributionModal:boolean = false
	distribution(e,data){
		this.validateForm = this.fb.group({
		  jobNumber: [null, [Validators.required]],
			gurop: [null, [Validators.required]],
			department:[null, [Validators.required]],
		});
		this.distributionName = null
		this.handoverUserId = null
		this.distributionModal = true
	}

	// 确定配送
	submitDistributionForm(){
		this.btnLoading = true
		this.btnLoading = false
		this.hideDistributionModal()
	}

	// 取消配送
	hideDistributionModal(){
		this.distributionModal = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	changeHospitalInp(e){
		// this.changeInpSubjectHospital.next([e]);
	}

	changeDepartmentInp(e){
		// this.isDeptLoading = true
		// this.changeInpSubjectDepartment.next([e]);
	}

	// 补打
	printModal:boolean = false;
	parintLoading:boolean = false;
	reprint(e,data){
		this.printModal = true
	}

	// 取消补打
	hidePrintModal(){
		this.printModal = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	// 确定补打
	confirmPrintDel(){
		this.parintLoading = true
		this.parintLoading = false
		this.hidePrintModal()
		// if (res.status == 200) {
		// 	this.showPromptModal("操作", true, "");
		// } else {
		// 	this.showPromptModal("操作", false, res.msg);
		// }

	}

	// 接收时间
	startDate:any;
	endDate:any;
	changeDate(result){
		this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
		this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	}

	// 获取批次号
	generateBatchNumber(){

	}

	// 获取标本接收数据
	pageReceptionIndex:any = 1;
	listReceptionLength:any = 0;
	otherData:any=null;
	getJsData(type){
		let data = {
		  idx: this.pageReceptionIndex-1,
		  sum: this.pageSize,
		  pathologyForm: {
		    batchNo:this.batchNo,
				packId:null
		  },
		};
		if(type==4){
			data.pathologyForm.packId = this.scanCodeData.id
			delete data.pathologyForm.batchNo
		}else if(type==5){
			data.pathologyForm.packId = this.packId
			delete data.pathologyForm.batchNo
		}else{
			delete data.pathologyForm.packId
		}
		this.tableLoading = true;
		this.mainService
		  .getFetchDataList("data", "pathologyForm", data)
		  .subscribe((res) => {
				this.tableLoading = false;
				if(type==1 || type==4 || type==5){
					this.fixationModal = true
					this.codeData = res.list;
					if(type==1){
						setTimeout(_=>{
							document.getElementById('specimen').focus();
						},200)
					}else if(type==4 && this.noType=='none'){
						this.connectAccomplish()
					}
				}else if(type==3){
					this.codeMultiData = this.scanCodeData.pathologySpecimenDTOList
					this.fixationModal = true
					this.multiModal = true
					setTimeout(_=>{
						document.getElementById('multiSpecimen').focus();
					},200)
				}
				this.otherData = res.otherData;
				this.listReceptionLength = res.totalNum;
		  });
	}

	// 配送中包交接完成
	connectAccomplish(){
		this.validateConnectForm = this.fb.group({
		  receptionNumber: [this.userInfo.account, [Validators.required]],
			dispatchingNumber: [this.scanCodeData.deliveryUserDTO.account, [Validators.required]]
		});
		this.dispatchingName = this.scanCodeData.deliveryUserDTO.name;
		this.dispatchingUserId = this.scanCodeData.deliveryUserDTO.id

		this.receptionName = this.userInfo.name;
		this.connectUserId = this.userInfo.id;

		this.receptionModal = true
		this.barCode = null
	}

	// 确定接收包
	submitReceptionForm(){
		for (const i in this.validateConnectForm.controls) {
		  this.validateConnectForm.controls[i].markAsDirty();
		  this.validateConnectForm.controls[i].updateValueAndValidity();
		}
		if (this.validateConnectForm.invalid) return;
		let data = {
			receiveUser:this.connectUserId,
			deliveryUser:this.dispatchingUserId,
			operationType:'bagReceive',
			id:this.scanCodeData.id,
      busiType: 'pathology',//病理打包
		};
		this.btnConnectLoading = true
		this.mainService
		  .simplePost("updData", "pathologyPackInfo", data)
		  .subscribe((data) => {
				this.btnConnectLoading = false
				if (data.status == 200) {
					this.message.success('交接成功')
					setTimeout(_=>{
						this.hideSpecimenModal()
					},500)
				} else {
				  this.message.error(data.msg)
				}
		  });
	}

	// 关闭配送接收
	hideReceptionModal(){
		this.receptionModal = false
	}

	// 选择固定时间
	formChangeDate(result){
	  this.startDate = format(result, 'yyyy-MM-dd HH:mm:ss');
	}

	// 监听人员交接接收人工号输入
	connectUserId:any = null;
	receptionName:any = null;
	receptionChange(e){
		if(e.length < 3) {
			this.receptionName = null;
			return
		}
		let query = {
		  account: e
		};
		this.mainService
		  .jobSearch(query)
		  .subscribe((data:any) => {
				if(data.status==200){
					this.receptionName = data.userName;
					this.connectUserId = data.userId
				}else{
					this.receptionName = null;
					this.connectUserId =null
				}
		  });
	}

	// 监听人员交接配送人工号输入
	dispatchingUserId:any = null;
	dispatchingName:any = null;
	dispatchingChange(e){
		if(e.length < 3) {
			this.dispatchingName = null;
			return
		}
		let query = {
		  account: e
		};
		this.mainService
		  .jobSearch(query)
		  .subscribe((data:any) => {
				if(data.status==200){
					this.dispatchingName = data.userName;
					this.dispatchingUserId = data.userId
				}else{
					this.dispatchingName = null;
					this.dispatchingUserId =null
				}
		  });
	}

	// 确定交接
	mustReceived:any = null;
	currReceived:any = null;
	submitFixationForm(){
		this.btnLoading = true
		this.mainService.getSpecimenInfo(this.batchNo,this.deptId,{}).subscribe((res:any) => {
			this.btnLoading = false
			this.mustReceived = res.data.mustReceived;
			this.currReceived = res.data.currReceived;
			this.btnConnectLoading = false
			if(this.codeData[0].deliveryUserDTO){
				this.validateConnectForm = this.fb.group({
					receptionNumber: [this.userInfo.account, [Validators.required]],
					dispatchingNumber: [this.codeData[0].deliveryUserDTO.account, [Validators.required]]
				});
				this.dispatchingName = this.codeData[0].deliveryUserDTO.name;
				this.dispatchingUserId = this.codeData[0].deliveryUserDTO.id
			}else{
				this.validateConnectForm = this.fb.group({
					receptionNumber: [null, [Validators.required]],
					dispatchingNumber: [null, [Validators.required]]
				});
				this.dispatchingName = null;
				this.dispatchingUserId = null
			}
			this.receptionName = this.userInfo.name;
			this.connectUserId = this.userInfo.id;
			this.connectModal = true
		});
	}
	// 关闭人员交接
	hideConnectModal(){
		this.connectModal = false
	}

	// 确定人员交接
	btnConnectLoading:boolean = false;
	submitConnectForm(){
		for (const i in this.validateConnectForm.controls) {
		  this.validateConnectForm.controls[i].markAsDirty();
		  this.validateConnectForm.controls[i].updateValueAndValidity();
		}
		if (this.validateConnectForm.invalid) return;
		let data = {
			batchNo:this.batchNo,
			receiveDept:this.deptId,
			receiverUser:this.connectUserId,
			deliveryUser:this.dispatchingUserId
		};
		this.btnConnectLoading = true
		this.mainService
		  .handoverCompleted(data)
		  .subscribe((res:any) => {
				this.btnConnectLoading = false
		    if (res.status == 200) {
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, res.msg);
		    }
		  });
	}

	// 确定打包
	packModal:boolean = false;
	submitScanForm(){
		this.packModal = true
		// this.hideSpecimenModal()
	}

	// 确定打包并打印
	btnPackLoading:boolean = false;
	printData:any = [];
	submitPackForm(){
		let that = this
		let data: any = {
			batchNo:this.batchNo,
			deptId:this.deptId
		};

		this.btnPackLoading = true;
		this.mainService
		  .pathologyPack(data)
		  .subscribe((res:any) => {
				if(res.status==200){
					that.btnPackLoading = false;
					if(res.packPrintData){
						res.packPrintData = this.sanitizer.bypassSecurityTrustResourceUrl(res.packPrintData)
					}
					that.printData = res.packPrintData;
					setTimeout(() => {
					  const printContent = document.getElementById("report");
					  const WindowPrt = window.open("", "", "width=100,height=1000");
						WindowPrt.document.body.innerHTML = printContent.innerHTML;
						setTimeout(_=>{
							WindowPrt.document.close();
							WindowPrt.focus();
							WindowPrt.print();
							WindowPrt.close();
							this.hideSpecimenModal()
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
		  });
	}

	// 关闭打包并打印
	hidePackModal(){
		this.packModal = false
		setTimeout(_=>{
			document.getElementById('specimen').focus();
		},200)
	}

	// 关闭交接/打包
	hideSpecimenModal(){
		// 清空data
		localStorage.setItem("scanCodeData",'')
		this.router.navigateByUrl(`/pathology?type=detail`)
	}

	// 获取标本详情
	project:any = [];
	getSampleData(item){
		// this.isSpinning = true
		this.mainService.getFetchData("data", "pathologyForm", item.id)
		.subscribe((data) => {
			// this.isSpinning = false
			this.detailMoadl = true
			this.detailsData = data.data
		  this.specimenList = data.data.pathologySpecimenDTOList||[]
			this.pathologyLogs = data.data.formLogDTOS
			this.stepLength = this.pathologyLogs.length
			if(this.detailsData.pathologyInspectDTOS){
				this.project = this.detailsData.pathologyInspectDTOS.map(i=>{
					return i.inspectProject.name
				})
				this.project = this.project.join('、')
			}
		});
	}

	// 获取科室
	getDept(){
		this.setSpecimen()
		var that = this;
		that.mainService.getDictionary("list", "dept_type").subscribe((res2) => {
			let item1 = res2.find(i=>i.name=='手术室科室')
			let item2 = res2.find(i=>i.name=='标本间科室')
			let data1 = {
			  idx: 0,
			  sum: 9999,
			  department: {
			    hospital: { id: that.hosId || "" },
			    type: { id: item1.id || "" },
			  },
			};
			let data2 = {
			  idx: 0,
			  sum: 9999,
			  department: {
			    hospital: { id: that.hosId || "" },
			    type: { id: item2.id || "" },
			  },
			};
			that.mainService
			  .getFetchDataList("data", "department", data1)
			  .subscribe((res) => {
			    that.operationData = res.list;
			  });

			that.mainService
			  .getFetchDataList("data", "department", data2)
			  .subscribe((res) => {
					that.specimenData = res.list
					this.getDeptDetail()
			  });
		});
	}

	// 获取关联科室详情
	getDeptDetail(){
		this.mainService
		  .transfusionPrint("user", this.userId)
		  .subscribe((res) => {
				let data = res.data;
				if(data.surgeryDepts){
					let deptArr = []
					for(let i of data.surgeryDepts){
						deptArr.push(i.id)
					}
					this.validateForm.controls.operation.setValue(deptArr);
				}
				this.validateForm.controls.specimen.setValue(data.dept.id);
				if(data.autoCreateOrder){
					this.validateForm.controls.generate.setValue(data.autoCreateOrder);
				}
		  });
	}

	// 获取是否关联标本间
	setSpecimen(){
		this.validateForm = this.fb.group({
		  specimen: [null, [Validators.required]],
			operation: [null, [Validators.required]],
			generate:[1, [Validators.required]],
		});
		this.relevanceModal = true
	}

	// 确定关联科室
	btnLoading:boolean = false;
	submitForm(){
		for (const i in this.validateForm.controls) {
		  this.validateForm.controls[i].markAsDirty();
		  this.validateForm.controls[i].updateValueAndValidity();
		}
		if (this.validateForm.invalid) return;
		let deptArr = this.validateForm.value.operation.join(',')
		let data = {
		  user: {
				upType: "changeDept",
				account: JSON.parse(localStorage.getItem("user")).user.account,
		    autoCreateOrder: this.validateForm.value.generate,
				dept:{
					id:this.validateForm.value.specimen
				},
				surgeryDeptIds:deptArr,
				id:this.userId
		  },
		};
		this.btnLoading = true
		this.mainService
		  .coopData("updData", "user", data)
		  .subscribe((data) => {
				this.getNewDept()
				this.btnLoading = false
				this.relevanceModal = false
		    if (data.status == 200) {
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, data.msg);
		    }
		  });
	}

	getNewDept(){
		let postData = {
		  currentHosId: this.hosId,
		  loginType: "PC",
		};
		this.mainService.changeHospital(postData).subscribe((result) => {
		  if (result.status == 200) {
		    let dataObj = {
		      user: {
						upType: "changeDept",
						account: JSON.parse(localStorage.getItem("user")).user.account,
		        dept: {
		          id: this.validateForm.value.specimen,
		        },
		        id: JSON.parse(localStorage.getItem("user")).user.id,
		      },
		    };
		    this.mainService
		      .coopData("updData", "user", dataObj)
		      .subscribe((data) => {
		        if (data.status == 200) {
		          this.getCurrentUserNow();
		        }
		      });
		  }
		});
	}

	// 获取当前用户信息
	getCurrentUserNow() {
	  this.mainService.getCurrentUser1().subscribe((data:any) => {
	    if (data["status"] == 200) {
				this.loginUser = data.data
	      let user = JSON.parse(localStorage.getItem("user"));
	      user.user.dept = data["data"].dept;
	      user.user.currentHospital = data["data"].currentHospital;
	      localStorage.setItem("user", JSON.stringify(user));
	    }
	  });
	}

	// 输入工号查询姓名
	handoverUserId:any = null;
	numberChange(e){
		if(e.length < 3) {
			this.distributionName = null;
			return
		}
		let query = {
		  account: e
		};
		this.mainService
		  .jobSearch(query)
		  .subscribe((data:any) => {
				if(data.status==200){
					this.distributionName = data.userName;
					this.handoverUserId = data.userId
				}else{
					this.distributionName = null;
					this.handoverUserId =null
				}
		  });
	}

	// 提交固定标本接收
	submitVerificationForm(){
		for (const i in this.validateVerificationForm.controls) {
		  this.validateVerificationForm.controls[i].markAsDirty();
		  this.validateVerificationForm.controls[i].updateValueAndValidity();
		}
		if (this.validateVerificationForm.invalid) return;

		let data: any = {
			id:this.codeData.id,
			specimenDeptId:this.validateForm.value.specimen,
			specimenFixingLiquid:{
				id:this.validateVerificationForm.value.fixative
			},
			fixationTime:this.startDate,
			hosId: this.hosId || "" ,
			handoverUserId:this.handoverUserId
		};
		this.btnInfoLoading = true;
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((res) => {
			this.btnInfoLoading = false;
			this.barCode = null;
			if (res.status == 200) {
				this.showPromptModal("操作", true, "");
			} else {
				this.showPromptModal("操作", false, res.msg);
			}
		});
	}

	// 成功/失败提示框
	closeModel(){
		localStorage.setItem("scanCodeData",'')
		this.router.navigateByUrl(`/pathology?type=detail`);
	}

	// 关闭配送信息
	hideVerificationModal(){
		this.verificationMoadl = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}


	// 监听交接/打包扫描条码
	tableLoading:boolean = false;
	codeChange(e){
		this.changeInpSubject.next([e]);
	}

	// 标本接收搜索条码
	errorMsg:any = null;
	searchSpecimenData(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		let data = {
			barcode:e,
			deptId:this.deptId,
			batchNo:this.batchNo,
			tabType:null
		}
		if(this.dataType=='receive'){
			data.tabType = 'receive'
		}else if(this.dataType=='pack'){
			data.tabType = 'pack'
		}else{
			delete data.tabType
		}
		this.tableLoading = true
		this.mainService.pathologyScanCode(data)
		.subscribe((res:any) => {
			this.tableLoading = false
			this.specimenCode = null
			if(res.status==200){
				this.scanCodeData = res.data[0]
				this.dataType = res.dataType
				console.log(44555,this.dataType)
				if(res.data[0].pathologySpecimenDTOList.length>1){
					for(let i of res.data[0].pathologySpecimenDTOList){
						if(i.isScan==1){
							this.muArr.push(i)
						}
					}
					this.multiModal = true
					this.codeMultiData = res.data[0].pathologySpecimenDTOList
					localStorage.setItem("scanCodeData",JSON.stringify(res))
				}else{
					this.getJsData(1)
				}
				this.errorMsg = null
			}else{
				this.errorMsg = res.msg
			}
		})
	}

	// 关闭多只标本
	hideMultiModal(){
		localStorage.setItem("scanCodeData",'');
		this.multiModal = false;
		this.errorMultiMsg = null;
		this.muArr = [];
		this.getJsData(1);
		setTimeout(_=>{
			document.getElementById('specimen').focus();
		},200)
	}

	// 监听多只标本扫描
	codeMultiChange(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		let data={
			barcode:e,
			deptId:this.deptId,
			pathologyFormId:this.scanCodeData.id,
			tabType:null
		}
		if(this.dataType=='receive'){
			data.tabType = 'receive'
		}else if(this.dataType=='pack'){
			data.tabType = 'pack'
		}else{
			delete data.tabType
		}
		setTimeout(_=>{
			this.tableLoading = true
			this.mainService.pathologyScanCode(data)
			.subscribe((res:any) => {
				this.tableLoading = false
				this.specimenMultiCode = null
				if(res.status==200){
					this.dataType = res.dataType
					this.muArr = []
					this.codeMultiData = res.data[0].pathologySpecimenDTOList
					for(let i of res.data[0].pathologySpecimenDTOList){
						if(i.isScan==1){
							this.muArr.push(i)
						}
					}
					this.multiModal = true
					localStorage.setItem("scanCodeData",JSON.stringify(res))
					this.errorMultiMsg = null
					// this.hideMultiModal()
				}else{
					this.errorMultiMsg = res.msg
				}
			})
		},500)
	}

	// 多只标本确定接受
	btnMultiLoading:boolean = false;
	submitMultiForm(){
		let data1 = JSON.parse(localStorage.getItem("scanCodeData"))
		this.scanCodeData = data1.data[0]
		for(let i of this.scanCodeData.pathologySpecimenDTOList){
			if(i.isScan==0){
				this.message.error('有未扫描的标本，请继续扫描')
				return
			}
		}
		let data: any = {
			id:this.scanCodeData.id,
			operationType:'pathologyReceive',
			batchNo:this.batchNo
		};
		this.btnMultiLoading = true;
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((res) => {
			this.message.success('操作成功')
			setTimeout(_=>{
				this.btnMultiLoading = false;
				this.hideMultiModal()
			},500)
		});
	}

	// 多只标本打包
	submitMultiScanForm(){
		let data1 = JSON.parse(localStorage.getItem("scanCodeData"))
		this.scanCodeData = data1.data[0]
		for(let i of this.scanCodeData.pathologySpecimenDTOList){
			if(i.isScan==0){
				this.message.error('有未扫描的标本，请继续扫描')
				return
			}
		}
		let data: any = {
			id:this.scanCodeData.id,
			operationType:'pathologyPack',
			batchNo:this.batchNo
		};
		this.btnMultiLoading = true;
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((res) => {
			this.message.success('操作成功')
			setTimeout(_=>{
				this.btnMultiLoading = false;
				this.hideMultiModal()
			},500)
		});
	}

	// 查看详情
	pathologyLogs:any=[];
	specimenList:any=[]
	stepLength:any = 0;
	viewDetail(item,type){
		this.isSpinning = true
		this.getSampleData(item)
		clearInterval(this.logTimer);
		if(type==1){

		}else if(type==2){

		}else{

		}
	}

	closeDetailMoadl(){
		this.detailMoadl = false
	}


  // 自动刷新倒计时
  autoUpdate(flag = true) {
    if (flag) {
      this.logTime = this.logTimeConst;
    }
    clearInterval(this.logTimer);
    this.logTimer = setInterval(() => {
      this.logTime--;
      if (this.logTime === 0) {
        this.logTime = this.logTimeConst;

      }
    }, 1000);
  }
  // 退出
  logOut(): void {
    // 假退出
    let hospital = this.tool.getCurrentHospital();
    if(hospital){
      this.router.navigate(["login", hospital.id]);
    }else{
      this.router.navigateByUrl("login");
    }
    localStorage.removeItem("user");
    localStorage.removeItem("menu");
    localStorage.removeItem("index");
    // 假退出
    this.mainService.logOut().subscribe((data) => {
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("index");
      }
    });

  }

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

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

  mainRole: boolean = false; //回到系统管理权限
  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;
    }
  }
  //药房端科室切换
  changeShow = true;
  closeTime = 3;
  closeTimeFlag = 0;
  hsPromptModalShow: boolean = false; //科室切换提示框是否展示
  timerCloseTime = null;
  deptDisplay = 1; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  //子传父接收
  closeModelHs(e) {
    this.hsPromptModalShow = JSON.parse(e).show;
    this.changeShow = JSON.parse(e).changeShow;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
  }
  //子传父接收
  clearModelHs(e) {
    if (JSON.parse(e).clear === true) {
      clearInterval(this.timerCloseTime);
    }
    this.changeShow = JSON.parse(e).changeShow;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
  }
  // 头部切换科室
  changeKsNow() {
    this.hsPromptModalShow = true;
    clearInterval(this.timerCloseTime);
    this.changeShow = false;
  }
  // 切换科室
  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);
  }

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

