import { Component, OnInit, ViewChild, OnDestroy } from "@angular/core";
import { MainService } from "../../services/main.service";
import { 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 {
  FormBuilder,
  Validators,
  FormGroup,
  FormControl,
} from "@angular/forms";

@Component({
  selector: "app-specimen-room-view",
  templateUrl: "./specimen-room-view.component.html",
  styleUrls: ["./specimen-room-view.component.less"],
})
export class SpecimenRoomViewComponent 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,
	public tool: ToolService,
	private fb: FormBuilder,
	private message: NzMessageService,
	) {}
  // 今日药单量
  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; //核验标本
	specimenData:any = []; //标本间数据
	operationData:any = []; //手术间数据
	fixationModal:boolean = false //标本接收固定
	verificationMoadl:boolean = false //标本核验
	specimenCode:any; //标本条码
	listOfData:any=[];
	fixativeData:any = []; //固体液类型
	hosId:any;
	userId:any;
	detailsData:any;
	isSpinning:boolean = false; //全屏加载状态
	codeData:any; //标本条码数据
	btnInfoLoading :boolean = false; //标本加固加载
	searchMsg:any = null;
	changeInpSubject = new Subject(); //防抖
	changeInpSubjectSpecimen = new Subject(); //防抖
	user:any;
  ngOnDestroy() {
    clearTimeout(this.timer);
    clearTimeout(this.logTimer);
  }

  ngOnInit() {
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchSpecimenData(v[0])
		});
		this.changeInpSubjectSpecimen.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchSpecimen(v[0])
		});
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId()
		this.user = this.tool.getCurrentUserInfo();
		// 手术间列表
		this.getPharmacyList(this.printPharmacyIdx, 'surgeryDept', this.printPharmacySearchKey);
		// 标本间列表
		this.getPharmacyList(this.waitPharmacyIdx, 'specimenDept', this.waitPharmacySearchKey);
		// 今日离科标本列表
		this.getPharmacyList(this.pharmacyIdx, 'leavedDept', this.pharmacySearchKey);
    this.runTime();
		this.getDept()
    this.initRole();
    // 自动刷新倒计时 start
    this.autoUpdate();
    // 自动刷新倒计时 end
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
  }
  // 当前时间日期
  runTime() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.time = Date.now();
      this.runTime();
    }, 500);
  }
	
	// 标本核对
	batchNo:any = null;
	specimenCheck(){
		this.batchNo = localStorage.getItem("specimenBatchNo")
		if(this.batchNo){
			localStorage.setItem("checkType",'specimenDept')
			this.router.navigateByUrl(`/pathologyCheck?batchNo=${this.batchNo}`);
		}else{
			this.mainService.generateBatchNumber()
			.subscribe((res:any) =>{
				localStorage.setItem("specimenBatchNo",res.data)
				localStorage.setItem("checkType",'specimenDept')
				this.router.navigateByUrl(`/pathologyCheck?batchNo=${res.data}`);
			})
		}
	}
	
	// 标本条码搜索
	codeDataSpecimenList:any = null;
	fixType:any = false
	searchSpecimen(e){
		if(!this.barCode){
			return
		}
		if(this.barCode.length < 10) {
			return
		}
		let data={
			barcode:e
		}
		this.isSpinning = true
		clearInterval(this.logTimer);
		this.mainService.pathologyScanCode(data)
		.subscribe((res:any) => {
			this.isSpinning = false
			if(res.status==200){
				this.codeData = res.data[0]
				this.codeDataSpecimenList = this.codeData.pathologySpecimenDTOList
				// this.codeDataSpecimenList = this.codeData.pathologySpecimenDTOList.filter(i=>!i.fixationTime)
				let item = null
				let str = null
				if(e.indexOf(':')!=-1){
					str = e.split(':')
					item = this.codeData.pathologySpecimenDTOList.find(i=>i.specimenCode == str[1])
				}else{
					item = this.codeData.pathologySpecimenDTOList.find(i=>i.specimenCode == e)
				}
				if(!item.fixationTime && this.codeData.pathologyFormType==0){
					if(this.codeData.status.value==2 || this.codeData.status.value==3 ||
						this.codeData.status.value==4){
							// this.fixType = false
							if(this.codeData.pathologyInspectDTOS){
								this.project = this.codeData.pathologyInspectDTOS.map(i=>{
									return i.inspectProject.name
								})
								this.project = this.project.join('、')
							}
							this.getFixationNum(this.codeData.id)
						}else{
							this.viewDetail(this.codeData,'4')
						}
					this.fixationError = null
					this.searchMsg = null
				}else if(item.fixationTime && this.codeData.pathologyFormType==0){
					if(item.storageTime){
						this.viewDetail(this.codeData,'4')
					}else{
						if(this.codeData.pathologyInspectDTOS){
							this.project = this.codeData.pathologyInspectDTOS.map(i=>{
								return i.inspectProject.name
							})
							this.project = this.project.join('、')
						}
						this.getFixationNum(this.codeData.id)
					}
					// if(this.codeData.status.value==2 || this.codeData.status.value==3 || this.codeData.status.value==4){
					// 	if(this.codeData.pathologyInspectDTOS){
					// 		this.project = this.codeData.pathologyInspectDTOS.map(i=>{
					// 			return i.inspectProject.name
					// 		})
					// 		this.project = this.project.join('、')
					// 	}
					// 	this.getFixationNum(this.codeData.id)
					// }else{
					// 	this.viewDetail(this.codeData,'4')
					// }
					this.barCode = null
					this.fixationError = null
					this.searchMsg = null
				}else{
					this.barCode = null
					this.fixationError = null
					this.searchMsg = '您扫描的是快速标本,' +'扫描结果: '+ '"' +this.codeData.pathologySpecimenDTOList[0].specimenCode +'"'
				}
				
			}else{
				this.barCode = null
				this.searchMsg = res.msg
			}
		})
	}
	
	// 获取申请单扫标本信息
	fixationNum:any;
	specimenNum:any;
	totalNum:any
	getFixationNum(id){
		this.mainService.pathologyCheckPrint('pathologyForm',id,{
			operationType:'fixation'
		}).subscribe((res:any)=>{
			this.fixationModal = true
			this.fixationNum = res.fixationNum
			this.specimenNum = res.specimenNum
			this.totalNum = res.totalNum
			setTimeout(_=>{
				document.getElementById('specimen').focus();
			},200)
		})
	}
	
	// 选择固定时间
	fixationTime:any;
	fixationData:any;
	fixationDateChange(result){
		this.fixationData = format(result, 'yyyy-MM-dd');
		console.log(this.fixationData)
	}
	fixationTimeSelect:any = null;
	fixationTimeChange(result){
		if(result){
			this.fixationTimeSelect = format(result, 'HH:mm');
		}else{
			this.fixationTimeSelect = null
		}
		console.log(this.fixationData + ' ' + this.fixationTimeSelect)
	}

	// 确定接受固定标本
	startDate:any;
	ifFixType:any = false;
	submitFixationForm(){
		let item = this.codeDataSpecimenList.filter(i=>!i.fixationTime)
		console.log(1111,item)
		this.validateVerificationForm = this.fb.group({
		  fixationTimes: [null, [Validators.required]],
		  fixationDate: [null, [Validators.required]],
			jobNumber: [null, [Validators.required]],
			name:[null, [Validators.required]],
			// nurseJobNumber: [null, [Validators.required]],
			// nurseName:[null, [Validators.required]],
			fixative:[null, [Validators.required]],
		});
		let date = new Date();
		let inVitroDate = format(date, "yyyy-MM-dd")
		if(item.length==0){
			this.ifFixType = true
			this.validateVerificationForm.removeControl('fixationTimes')
			this.validateVerificationForm.removeControl('fixationDate')
			this.validateVerificationForm.removeControl('fixative')
		}else{
			this.ifFixType = false
			this.validateVerificationForm.addControl(
				'fixationTimes',
				new FormControl(null, Validators.required)
			);
			this.validateVerificationForm.addControl(
				'fixationDate',
				new FormControl(null, Validators.required)
			);
			this.validateVerificationForm.addControl(
				'fixative',
				new FormControl(null, Validators.required)
			);
			this.validateVerificationForm.controls.fixationDate.setValue(inVitroDate);
			this.validateVerificationForm.controls.fixationTimes.setValue(date);
			this.fixationData = inVitroDate;
			this.fixationTimeSelect = format(date, 'HH:mm');
		}

		this.btnLoading = true
		this.mainService.getDictionary("list", "fixing_liquid_type").subscribe((res) => {
			this.fixativeData = res
			if(!this.ifFixType){
				let item = this.fixativeData.find(i=>i.value==1)
				this.validateVerificationForm.controls.fixative.setValue(item.id);
			}
			this.btnLoading = false
			this.verificationMoadl = true
		});
	}

	// 关闭接受固定标本
	hideSpecimenModal(){
		this.autoUpdate()
		this.cancelSpecimenModal()
		this.barCode = null;
		this.specimenCode = null;
		this.fixationError = null
		this.fixationModal = false;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}
	
	cancelSpecimenModal(){
		let ids = []
		for(let i of this.codeDataSpecimenList){
			ids.push(i.id)
		}
		let data = {
			pathologySpecimenIds:ids.join(',')
		}
		this.mainService.pathologyOperation(data,'cancel').subscribe((res) =>{
			
		})
	}
	
	// 获取标本详情
	project:any = [];
	getSampleData(item){
		this.mainService.getFetchData("data", "pathologyForm", item.id)
		.subscribe((data) => {
			this.isSpinning = false
			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('、')
			}
		  this.detailMoadl = true
		});
	}
	
	// 关闭查看标本
	closeSpecimenModal(){
		this.specimenViewDialog = false
	}
	
	// 查看标本
	specimenViewDialog:any = false;
	viewData:any = [];
	specimenItem:any;
	specimenView(item){
		this.viewData = []
		this.specimenViewDialog = true
		this.specimenItem = item;
		this.viewData.push(item)
	}
	
	// 获取科室
	getDept(){
		this.validateForm = this.fb.group({
		  specimen: [null, [Validators.required]],
			operation: [null, [Validators.required]],
			generate:[null, [Validators.required]],
			showFrozen:[null, [Validators.required]],
		});
		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.showFrozen!=null){
					this.validateForm.controls.showFrozen.setValue(data.showFrozen);
				}else{
					this.validateForm.controls.showFrozen.setValue(0);
				}
				if(data.autoCreateOrder!=null){
					this.validateForm.controls.generate.setValue(data.autoCreateOrder);
				}else{
					this.validateForm.controls.generate.setValue(1);
				}
		  });
	}

	// 获取是否关联标本间
	setSpecimen(){
		this.relevanceModal = true
	}
	
	hideModal(){
		this.relevanceModal = false
	}
	
	// 确定关联科室
	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: this.user.account,
		    autoCreateOrder: this.validateForm.value.generate,
				showFrozen: this.validateForm.value.showFrozen,
				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.getPharmacyList(this.printPharmacyIdx, 'surgeryDept', this.printPharmacySearchKey);
				// 标本间列表
				this.getPharmacyList(this.waitPharmacyIdx, 'specimenDept', this.waitPharmacySearchKey);
				// 今日离科标本列表
				this.getPharmacyList(this.pharmacyIdx, 'leavedDept', this.pharmacySearchKey);
				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) {
				this.getCurrentUserNow();
		    // let dataObj = {
		    //   user: {
		    //     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) {
		    //     }
		    //   });
		  }
		});
	}

	// 获取当前用户信息
	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.autoCreateOrder = data["data"].autoCreateOrder;
	      user.user.currentHospital = data["data"].currentHospital;
	      localStorage.setItem("user", JSON.stringify(user));
	    }
	  });
	}
	
	// 工号回车
	onEnterPress(){
		if(this.ifFixType){
			if(this.validateVerificationForm.value.jobNumber &&
				this.validateVerificationForm.value.name){
				this.submitVerificationForm()
			}
		}else{
			if(this.fixationData && this.fixationTimeSelect &&
				this.validateVerificationForm.value.jobNumber &&
				this.validateVerificationForm.value.name &&
				this.validateVerificationForm.value.fixative){
				this.submitVerificationForm()
			}
		}
	}
	
	// 输入工号查询姓名
	handoverUserId:any = null; //医生工号
	nurseId:any = null; //护士工号
	numberChange(e,type){
		if(e.length < 3) {
			this.validateVerificationForm.controls.name.setValue('');
			return
		}
		let query = {
		  account: e
		};
		this.mainService
		  .jobSearch(query)
		  .subscribe((data:any) => {
				if(data.status==200){
					if(type==1){
						this.validateVerificationForm.controls.name.setValue(data.userName);
						this.handoverUserId = data.userId
					}else{
						// this.validateVerificationForm.controls.nurseName.setValue(data.userName);
						// this.nurseId = data.userId
					}
				}
		  });
	}

	// 提交固定标本接收
	submitVerificationForm(){
		if(!this.ifFixType && !this.fixationTimeSelect && this.fixationTimeSelect == null){
			this.message.error('请选择固定时间')
			return
		}
		for (const i in this.validateVerificationForm.controls) {
		  this.validateVerificationForm.controls[i].markAsDirty();
		  this.validateVerificationForm.controls[i].updateValueAndValidity();
		}
		if (this.validateVerificationForm.invalid) return;
		let arr = []
		// if(!this.ifFixType){
		// 	arr = this.codeDataSpecimenList.filter(i=>!i.fixationTime)
		// }else{
		// 	arr = this.codeDataSpecimenList.filter(i=>i.fixationTime)
		// }
		let str = this.codeDataSpecimenList.map(i=>{
			return i.specimenCode
		})
		let data: any = {
			id:this.codeData.id,
			specimenDeptId:this.validateForm.value.specimen,
			specimenFixingLiquid:{
				id:''
			},
			specimenCodes:str.join(','),
			fixationTime:'',
			hosId: this.hosId || "" ,
			doctor:this.handoverUserId,
			nurse:this.nurseId
		};
		if(!this.ifFixType){
			data.specimenFixingLiquid.id = this.validateVerificationForm.value.fixative
			data.fixationTime = this.fixationData + ' ' + this.fixationTimeSelect+':00'
		}else{
			delete data.specimenFixingLiquid.id
			delete data.fixationTime
		}
		this.btnInfoLoading = true;
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((res) => {
			this.autoUpdate(false)
			this.btnInfoLoading = false;
			this.barCode = null;
			// 手术间列表
			this.getPharmacyList(this.printPharmacyIdx, 'surgeryDept', this.printPharmacySearchKey);
			// 标本间列表
			this.getPharmacyList(this.waitPharmacyIdx, 'specimenDept', this.waitPharmacySearchKey);
			// 今日离科标本列表
			this.getPharmacyList(this.pharmacyIdx, 'leavedDept', this.pharmacySearchKey);
			if (res.status == 200) {
				this.message.success('操作成功')
				setTimeout(_=>{
					this.verificationMoadl = false
					this.fixationModal = false
					document.getElementById('Binput').focus();
				},200)
				// this.showPromptModal("操作", true, "");
			} else {
				this.message.error(res.msg)
				// this.showPromptModal("操作", false, res.msg);
			}
		});
	}

	closeModel(){
		this.verificationMoadl = false
		this.fixationModal = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	// 关闭固定接受标本
	hideVerificationModal(){
		this.verificationMoadl = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}


	// 监听标本条码
	specimenCodeChange(e){
		this.changeInpSubjectSpecimen.next([e]);
	}

	// 监听接受固定标本条码
	tableLoading:boolean = false;
	codeChange(e){
		this.changeInpSubject.next([e]);
	}
	
	fixationError:any;
	searchSpecimenData(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		this.tableLoading = true
		this.mainService.pathologyScanCode({
			barcode:e,
			pathologyFormId:this.codeData.id
		})
		.subscribe((res:any) => {
			this.autoUpdate(false)
			this.tableLoading = false
			this.specimenCode = null
			if(res.status==200){
				let item = null
				let str = null
				if(e.indexOf(':')!=-1){
					str = e.split(':')
					item = res.data[0].pathologySpecimenDTOList.find(i=>i.specimenCode == str[1])
				}else{
					item = res.data[0].pathologySpecimenDTOList.find(i=>i.specimenCode == e)
				}
				// let item = res.data[0].pathologySpecimenDTOList.find(i=>i.specimenCode == e)
				if(item.fixationTime && item.storageTime){
					this.fixationError = '该标本已存放标本间'
				}else{
					this.getFixationNum(res.data[0].id)
					this.codeData = res.data[0]
					// this.codeDataSpecimenList = this.codeData.pathologySpecimenDTOList.filter(i=>!i.fixationTime)
					this.codeDataSpecimenList = this.codeData.pathologySpecimenDTOList
					this.fixationError = null
				}
			}else{
				this.fixationError = res.msg
			}
		})
	}

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

	closeDetailMoadl(){
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
		this.detailMoadl = false
		this.autoUpdate(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;
        // 代收急查标本（标本信息）列表
        this.getPharmacyList(0, 'surgeryDept', this.printPharmacySearchKey);
        // 已收取（工单信息）列表
        this.getPharmacyList(0, 'specimenDept', this.waitPharmacySearchKey);
        // 中转标本（标本统计信息）列表
        this.getPharmacyList(0, 'leavedDept', this.pharmacySearchKey);

      }
    }, 1000);
  }
  // 药房端药房列表查询、搜索
  // 1为pc待打印状态、2为pc配药中、3为pc核对中、4为pc配送中
  // searchKey  为搜索的关键字，没有就不传
  loading1 = false;
  loading2 = false;
  loading3 = false;
  loading4 = false;
  loading5 = false;
	otherData1 = null;
	otherData2 = null;
	otherData3 = null;
  getPharmacyList(idx, type, searchKey) {
    let hosId = JSON.parse(localStorage.getItem("user")).user.currentHospital.id;
    switch (type) {
      case 'surgeryDept':
        this.loading1 = true;
        break;
      case 'specimenDept':
        this.loading2 = true;
        break;
      case 'leavedDept':
        this.loading3 = true;
        break;
    }
    let postData = {
			idx: 0,
			sum: 50,
			pathologyForm:{
				detailsType: type,
				keyWords:searchKey,
				hosId,
			}
    };
    this.mainService
      .getFetchDataList("data", "pathologyForm", postData)
      .subscribe((result) => {
        switch (type) {
          case 'surgeryDept':
            this.loading1 = false;
            break;
          case 'specimenDept':
            this.loading2 = false;
            break;
          case 'leavedDept':
            this.loading3 = false;
            break;
        }
        if (result["status"] == 200) {
          switch (type) {
            case 'surgeryDept':
              // 总数
              this.printPharmacyTotal = result.totalNum;
              // 隐藏按钮的loading
              this.printPharmacyLoad = false;
              // 查看更多，是否显示
              if (result["list"].length < 10) {
                this.printPharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.printPharmacyFlag = false;
              } else {
                this.printPharmacyFlag = true;
              }
							this.otherData1 = result.otherData;
              // 列表数据合并
              if (idx === 0) {
                this.printPharmacyList = result["list"];
              } else {
                this.printPharmacyList = [
                  ...this.printPharmacyList,
                  ...result["list"],
                ];
              }
              break;
            case 'specimenDept':
              this.waitPharmacyTotal = result.totalNum;
              this.waitPharmacyLoad = false;
              if (result["list"].length < 10) {
                this.waitPharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.waitPharmacyFlag = false;
              } else {
                this.waitPharmacyFlag = true;
              }
							this.otherData2 = result.otherData;
              if (idx === 0) {
                this.waitPharmacyList = result["list"];
              } else {
                this.waitPharmacyList = [
                  ...this.waitPharmacyList,
                  ...result["list"],
                ];
              }
              break;
            case 'leavedDept':
              this.pharmacyTotal = result.totalNum;
              this.pharmacyLoad = false;
              if (result["list"].length < 10) {
                this.pharmacyFlag = false;
              } else if (result["list"].length === 0 && idx === 0) {
                this.pharmacyFlag = false;
              } else {
                this.pharmacyFlag = true;
              }
							this.otherData3 = result.otherData;
              if (idx === 0) {
                this.pharmacyList = result["list"];
              } else {
                this.pharmacyList = [...this.pharmacyList, ...result["list"]];
              }
              break;
          }
        }
      });
  }
  // 加载更多
  // loadMore(type) {
  //   switch (type) {
  //     case 'surgeryDept':
  //       this.printPharmacyIdx++;
  //       this.printPharmacyLoad = true;
  //       this.getPharmacyList(
  //         this.printPharmacyIdx,
  //         type,
  //         this.printPharmacySearchKey
  //       );
  //       break;
  //     case 'specimenDept':
  //       this.waitPharmacyIdx++;
  //       this.waitPharmacyLoad = true;
  //       this.getPharmacyList(
  //         this.waitPharmacyIdx,
  //         type,
  //         this.waitPharmacySearchKey
  //       );
  //       break;
  //     case 'leavedDept':
  //       this.pharmacyIdx++;
  //       this.pharmacyLoad = true;
  //       this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
  //       break;
  //   }
  // }
  // 搜索关键词
  searchKeyHandle(type) {
    switch (type) {
      case 'surgeryDept':
        this.printPharmacyIdx = 0; //页码重置
        this.printPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.printPharmacyIdx,
          type,
          this.printPharmacySearchKey
        );
        break;
      case 'specimenDept':
        this.waitPharmacyIdx = 0; //页码重置
        this.waitPharmacyList = []; //列表重置
        this.getPharmacyList(
          this.waitPharmacyIdx,
          type,
          this.waitPharmacySearchKey
        );
        break;
      case 'leavedDept':
        this.pharmacyIdx = 0; //页码重置
        this.pharmacyList = []; //列表重置
        this.getPharmacyList(this.pharmacyIdx, type, this.pharmacySearchKey);
        break;
    }
  }
  // 退出
  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;
	showDropdown:boolean = false;
  // 下拉
  fixedMenuXiala() {
    this.showLastItems = true;
  }

  // 上拉
  fixedMenuShangla() {
    this.showLastItems = false;
  }
	
	// 回到系统管理
	toMain() {
	  this.router.navigateByUrl("main");
	}
	
	// 配送记录
	distributionRecord(){
		this.router.navigateByUrl("main/batchDistribution");
	}
	
  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;
  }
  //子传父接收
  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;
  }
  // 切换科室
  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);
	}
}

