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-pathology",
  templateUrl: "./pathology.component.html",
  styleUrls: ["./pathology.component.less"],
})
export class PathologyComponent 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(); //防抖
	changeInpSubjectSpecimen = new Subject(); //防抖
	changeInpSubjectDepartment = new Subject(); //防抖
	pathologyFormType: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;
	rowData:any = null; //table选中数据
	toDayData:any = null;
	toDayTime:any = null;
	backType='list';
	user:any;
	loginUserDeptId: number = JSON.parse(localStorage.getItem("user")).user.dept
	  .id; //登录人所属科室
  ngOnDestroy() {
    clearTimeout(this.timer);
    clearTimeout(this.logTimer);
		clearTimeout(this.timer);
  }

  ngOnInit() {
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchSpecimenData(v[0])
		});
		this.changeInpSubjectSpecimen.pipe(debounceTime(100)).subscribe((v) => {
		  this.searchSpecimen(v[0])
		});
		this.changeInpSubjectUser.pipe(debounceTime(500)).subscribe((v) => {
			this.isLoading = true
		  this.getUserData(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.user = this.tool.getCurrentUserInfo();
		if(localStorage.getItem("pathologyActiveIndex")){
			this.activeIndex = localStorage.getItem("pathologyActiveIndex")
			if(this.activeIndex==0){
				this.getConnectList()
			}else if(this.activeIndex==1){
				this.getSpeedinessList()
			}else{
				this.getPackList()
				this.getHospitalData()
			}
		}else{
			this.getConnectList()
		}
		if(this.route.snapshot.queryParams && this.route.snapshot.queryParams.type){
			this.backType = this.route.snapshot.queryParams.type
		}
		if(this.backType=='list'){
			this.changeKs();
		}
		this.getUserData('')
		this.getToday()
		clearInterval(this.toDayTime)
		this.toDayTime = setInterval(_=>{
			this.getToday()
		},60000)
  }

	isShowNurseCode = false; //是否展开科室二维码
	nurseCodeImg = ""; //图片
	refreshQRCodeTime = 0; //刷新时间间隔
	// 关闭科室二维码
	closeNurseCode() {
	  this.isShowNurseCode = false;
	  clearInterval(this.timers);
	  this.timer = null;
	}
	// 展开科室二维码
	timers = null;
	showNurseCode() {
	  this.isShowNurseCode = true;
	  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.timers);
	      this.timers = setInterval(() => {
	        this.refreshQRCodeTime = Math.max(--this.refreshQRCodeTime, 0);
	        if (this.refreshQRCodeTime === 0) {
	          clearInterval(this.timers);
	          this.showNurseCode();
	        }
	      }, 1000);
	    }
	  });
	}

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

	//tab切换
	tabClick(type){
		this.activeIndex = type
		localStorage.setItem("pathologyActiveIndex",type)
		if(type==0){
			this.getConnectList()
		}else if(type==1){
			this.getSpeedinessList()
		}else{
			this.getPackList()
			this.getHospitalData()
		}
	}

	// 获取今日接收数据
	getToday(){
		this.mainService
		  .pathologyToday({
				deptId:this.deptId
			})
		  .subscribe((data:any) => {
		    this.toDayData = data.data
		  });
	}
	//配送人搜索
	changeUserInp(e){
		this.changeInpSubjectUser.next([e]);
	}

	// 获取配送人
	getUserData(e){
		let query={
			idx: 0,
			sum: 10,
			user: {
			  name: e,
			},
		}
		this.mainService
		.getFetchDataList("data", "user", query)
		.subscribe((res) => {
			this.isLoading = false
			this.userData = res.list
		});
	}

	// 搜索
	search() {
	  this.pageOneIndex = 1;
	  this.getConnectList();
	}
	// 重置
	reset() {
	  this.pageOneIndex = 1;
	  this.startDate = null;
		this.endDate = null;
		this.acceptTime = [];
		this.pathologyFormType = null;
		this.deliveryUser = null;
	  this.getConnectList();
	}
	// 交接本数据
	getConnectList() {
	  var that = this;
	  let data = {
	    idx: that.pageOneIndex - 1,
	    sum: that.pageSize,
	    pathologyForm: {
	      startTime: this.startDate,
	  		endTime: this.endDate,
				receiveDept:this.deptId,
				deliveryUser:this.deliveryUser,
				pathologyFormType:this.pathologyFormType
	    },
	  };
	  this.loading1 = true;
	  that.mainService
	    .getFetchDataList("data", "pathologyForm", data)
	    .subscribe((data) => {
	      this.loading1 = false;
	      that.listOneData = data.list;
	      that.listOneLength = data.totalNum;
	    });
	}

	// 实时术中快速数据
	getSpeedinessList() {
		var that = this;
		let data = {
		  idx: that.pageTwoIndex - 1,
		  sum: that.pageSize,
		  pathologyForm: {
				executiveDept:this.deptId,
				pathologyFormType:1,
				operationType:'pathologyFormType'
		  },
		};
		this.loading2 = true;
		that.mainService
		  .getFetchDataList("data", "pathologyForm", data)
		  .subscribe((data) => {
		    this.loading2 = false;
		    that.listTwoData = data.list;
		    that.listTwoLength = data.totalNum;
		  });
	}

	// 打包配送
	getPackList() {
	  var that = this;
	  let data = {
	    idx: that.pageThreeIndex - 1,
	    sum: that.pageSize,
	    pathologyPackInfo: {
	  		deptId: this.deptId,
        busiType: 'pathology',//病理打包
	    },
	  };
	  this.loading3 = true;
	  that.mainService
	    .getFetchDataList("data", "pathologyPackInfo", data)
	    .subscribe((data) => {
	      this.loading3 = false;
	      that.listThreeData = data.list;
	      that.listThreeLength = data.totalNum;
	    });
	}

	// 查看
	project:any = [];
	oneLook(e,data){
		this.isSpinning = true
		this.mainService.getFetchData("data", "pathologyForm", data.id)
		.subscribe((data) => {
			this.isSpinning = false
			this.detailMoadl = true
			// this.distributionModal = 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('、')
			}
		});
	}

	// 关闭查看
	closeDetail(){
		this.listDetailMoadl = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	// 接收
	connect(){
		this.mainService.generateBatchNumber()
		.subscribe((res1:any) => {
			if(res1.status==200){
				this.batchNo = res1.data
				localStorage.setItem("scanCodeData",'')
				localStorage.setItem("dataType",'');
				localStorage.setItem("pathologyActiveIndex",this.activeIndex)
				this.router.navigateByUrl(`/pathologyScan?batchNo=${this.batchNo}&businessType=connect&placeholder=1`);
				this.businessType = 'connect'
			}
		})
	}

	// 打包
	packaging(){
		this.mainService.generateBatchNumber()
		.subscribe((res1:any) => {
			if(res1.status==200){
				this.batchNo = res1.data
				localStorage.setItem("scanCodeData",'')
				localStorage.setItem("dataType",'');
				localStorage.setItem("pathologyActiveIndex",this.activeIndex)
				this.router.navigateByUrl(`/pathologyScan?batchNo=${this.batchNo}&businessType=packaging&placeholder=1`);
				this.businessType = 'packaging'
			}
		})
	}

	//打包查看标本
	threeLook(e,data){
		localStorage.setItem("pathologyActiveIndex",this.activeIndex)
		localStorage.setItem("dataType",'');
		this.router.navigateByUrl(`/pathologyScan?packId=${data.id}&businessType=packagLook`);
	}

	// 配送
	distributionModal:boolean = false
	distribution(e,data){
		this.rowData = 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(){
		for (const i in this.validateForm.controls) {
		  this.validateForm.controls[i].markAsDirty();
		  this.validateForm.controls[i].updateValueAndValidity();
		}
		if (this.validateForm.invalid) return;
		let data = {
			id:this.rowData.id,
			deliveryUser:this.handoverUserId,
			receiveHos:this.validateForm.value.gurop,
			targetDept:this.validateForm.value.department,
			operationType:'bagDelivery',
      busiType: 'pathology',//病理打包
		};
		this.btnLoading = true
		this.mainService
		  .simplePost("updData", "pathologyPackInfo", data)
		  .subscribe((data) => {
				this.btnLoading = false
		    if (data.status == 200) {
					this.message.success('配送成功')
					this.hideDistributionModal()
					this.getPackList()
		    } else {
		      this.message.error(data.msg)
		    }
		  });

	}

	// 取消配送
	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]);
	}

	// 关闭查看标本
	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)
	}

	// 获取院区
	getHospitalData(){
		let arr = this.tool.getHospitalList().filter(i=>i.parent==undefined)
		this.hospital = arr
		// let data = {
		//   idx: 0,
		//   sum: 9999,
		// 	hospital:{
		// 		selectType:'level1'
		// 	}
		// };
		// this.mainService
		//   .getFetchDataList("data", "hospital", data)
		//   .subscribe((res) => {
		//     this.hospital = res.list;
		//   });
	}

	// 选择院区
	hospitalId:any=null;
	changeHospDate(e){
		this.validateForm.controls.department.setValue(null)
		this.hospitalId = e
		this.getDepartmentData('',e)
	}

	// 获取科室
	isDeptLoading:boolean = false;
	getDepartmentData(e,hospital){
		this.mainService.getDictionary("list", "dept_type").subscribe((res2) => {
			let item = res2.find(i=>i.name=='检验科室')
			let data = {
			  idx: 0,
			  sum: 999,
			  department: {
					dept:e,
			    hospital: { id: this.hospitalId || "" },
			    type: {id:item.id},
			  },
			};
			this.mainService
			  .getFetchDataList("data", "department", data)
			  .subscribe((res) => {
					this.isDeptLoading = false
			    this.department = res.list;
			  });
		});
	}

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

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

	// 确定补打
	confirmPrintDel(){
		this.parintLoading = true
		this.mainService.getFetchData("data", "pathologyPackInfo", this.rowData.id)
		.subscribe((data) => {
			this.parintLoading = false
			if(data.status==200){
				if(data.data.qrCode){
					data.data.qrCode = this.sanitizer.bypassSecurityTrustResourceUrl(data.data.qrCode)
				}
				this.printData = data.data;
				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.hidePrintModal()
					},500)
				}, 500);
			}else{
				this.message.error(data.msg)
			}
		});

	}

	// 接收时间
	startDate:any;
	endDate:any;
	changeDate(result){
		this.startDate = format(result[0], 'yyyy-MM-dd' +' '+'00:00:00');
		this.endDate = format(result[1], 'yyyy-MM-dd' +' '+'23:59:59');
		this.acceptTime = [this.startDate,this.endDate]
	}

	// 获取批次号
	generateBatchNumber(){

	}

	// 标本条码搜索
	errorcODEMsg:any = null
	batchNo:any = null;
	scanCodeData:any = null;
	dataType:any = null;
	searchSpecimen(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		this.isSpinning = true
		this.mainService.generateBatchNumber()
		.subscribe((res1:any) => {
			if(res1.status==200){
				this.batchNo = res1.data
				let data={
					barcode:e,
					deptId:this.deptId,
					batchNo:this.batchNo
				}
				this.mainService.pathologyScanCode(data)
				.subscribe((res:any) => {
					this.isSpinning = false
					if(res.status==200){
						localStorage.setItem("scanCodeData",JSON.stringify(res))
						localStorage.setItem("dataType",res.dataType)
						this.router.navigateByUrl(`/pathologyScan?batchNo=${this.batchNo}&businessType=connect`);
						this.errorcODEMsg = null
					}else{
						this.barCode = null
						this.errorcODEMsg = res.msg
					}
				})
			}
		})

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

	// 确定接收包
	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 = {
		  // user: {
		  //   autoCreateOrder: this.validateForm.value.generate,
				// dept:{
				// 	id:this.validateForm.value.specimen
				// },
				// this.dispatchingUserId
				// this.connectUserId
				// id:this.userId
		  // }
		};
		this.btnConnectLoading = true
		this.mainService
		  .coopData("updData", "user", data)
		  .subscribe((data) => {
				this.btnConnectLoading = false
		    if (data.status == 200) {
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, data.msg);
		    }
		  });
	}

	// 关闭配送接收
	hideReceptionModal(){
		this.receptionModal = false
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	// 选择固定时间
	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: [null, [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 = null;
			this.connectUserId = null
			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,
			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 = {

		};

		this.btnPackLoading = true;
		this.mainService
		  .pathologyPrint(data)
		  .subscribe((res:any) => {
				if(res.status==200){
					let arr = res.data;
					that.btnPackLoading = false;
					that.printData = arr;
					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();
							that.hidePackModal();
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
		  });
	}

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

	// 关闭交接/打包
	hideSpecimenModal(){
		this.barCode = null;
		this.specimenCode = null;
		this.fixationModal = false;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
	}

	// 获取标本详情
	getSampleData(item){
		// this.isSpinning = true
		this.mainService.getFetchData("data", "pathologyForm", item.id)
		.subscribe((data) => {
			// this.isSpinning = false
			// this.detailMoadl = true
			this.distributionModal = 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: this.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(){
		this.hideReceptionModal()
		this.hideConnectModal()
		this.hideSpecimenModal()
	}

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

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

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

	// 标本接收搜索条码
	errorMsg:any = null;
	searchSpecimenData(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		this.tableLoading = true
		this.mainService.pathologyScanCode({
			barcode:e,
			deptId:this.deptId,
			batchNo:this.batchNo,
			pathologyFormId:this.scanCodeData.id
		})
		.subscribe((res:any) => {
			this.tableLoading = false
			this.specimenCode = null
			if(res.status==200){
				this.scanCodeData = res.data[0]
				this.dataType = res.dataType
				if(res.data[0].pathologySpecimenDTOList.length>1){
					this.multiModal = true
					this.codeMultiData = res.data[0].pathologySpecimenDTOList
				}else{
					this.getJsData(2)
				}
				this.errorMsg = null
			}else{
				this.errorMsg = res.msg
			}
		})
	}

	// 关闭多只标本
	hideMultiModal(){
		this.multiModal = false
		setTimeout(_=>{
			document.getElementById('specimen').focus();
		},200)
	}

	// 监听多只标本扫描
	codeMultiChange(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		let data={
			barcode:e
		}
		setTimeout(_=>{
			this.tableLoading = true
			this.mainService.pathologyScanCode(data)
			.subscribe((res:any) => {
				this.dataType = res.dataType
				this.tableLoading = false
				this.specimenMultiCode = null
				if(res.status==200){
					this.codeMultiData = res.data
					this.errorMultiMsg = null
					// this.hideMultiModal()
				}else{
					this.errorMultiMsg = res.msg
				}
			})
		},500)
	}

	// 多只标本确定接受
	btnMultiLoading:boolean = false;
	submitMultiForm(){
		this.btnMultiLoading = true
		this.btnMultiLoading = false
		this.hideMultiModal()
	}

	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");
		localStorage.removeItem("scanCodeData");
		localStorage.removeItem("dataType");
		localStorage.removeItem("pathologyActiveIndex");
    // 假退出
    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");
				localStorage.removeItem("scanCodeData");
				localStorage.removeItem("dataType");
				localStorage.removeItem("pathologyActiveIndex");
      }
    });

  }

  // 右侧菜单
  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);
	}
}

