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-sample",
  templateUrl: "./pathology-sample.component.html",
  styleUrls: ["./pathology-sample.component.less"],
})
export class PathologySampleComponent implements OnInit {
  constructor(
	private mainService: MainService,
	public router: Router,
	public route: ActivatedRoute,
	public tool: ToolService,
	private fb: FormBuilder,
	private message: NzMessageService,
	private sanitizer: DomSanitizer
	) {}
	validatePrintForm: FormGroup;
	validateSpecimenForm: FormGroup;
	showDropdown:boolean = false;
  printPharmacyList = []; //数据列表
  printPharmacyIdx = 0; //页码
  printPharmacyTotal = 0; //总数
  printPharmacyFlag = false; //是否查看更多
  printPharmacySearchKey = ""; //搜索的内容
  printPharmacyLoad = false; //按钮的loading

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

	relevanceModal:boolean = false //关联标本和手术室
	validateForm: 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(); //防抖
	specimenList:any=[]; //已选标本
	placeIndex:any = null;
	systemIndex:any = null;
	apparatusIndex:any = null;
	specimenNameIndex:any = null;
	placeList:any=[]; //位置来源数据
	systemList:any=[]; //系统数据
	apparatusList:any=[]; //器官数据
	specimenNameList:any=[]; //标本名称数据
	promptContent: string; //操作提示框提示信息
	ifSuccess: boolean; //操作成功/失败
	promptInfo: string; //操作结果提示信息
	promptModalShow: boolean; //操作提示框是否展示
	specimenModalShow: boolean; //操作提示框是否展示
	type:any = '未打印';
	projectData:any;
	detailId:any = '200';
	project:any;
	viewType:any = 'no';
	mainRole:any;
	deptId:any = null;
	btnDelLoading:any = false;
	activeIndex:any = 0;
	pathologyFormCode:any = null;
	cardNO:any = null;
	
  ngOnInit() {
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchSpecimenData(v[0])
		});
		this.changeInpSubjectSpecimen.pipe(debounceTime(500)).subscribe((v) => {
			this.pressType = false
		  this.searchSpecimen(v[0],'search','new')
		});
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId();
		this.deptId = this.tool.getCurrentUserDept().id;
		this.getProDicData()
		this.getDicData()
		this.getSourceData()
		this.getSysData()
		this.getTaskTypesId();
		this.getStationaryLiquid();
		this.getSpecimenName();
		this.validateForm = this.fb.group({
			specimenGenre: [null, [Validators.required]],
			intraoperativeFindings: [null, []],
			project: [null, [Validators.required]],
			surgicalPlan: [null, []],
			specimenNum: [{value: null, disabled: true},[Validators.required]],
			takePart: [null, [Validators.required]]
		});
		if(this.route.snapshot.params && (this.route.snapshot.params.cardNO 
			|| this.route.snapshot.params.pathologyFormCode)){
			this.cardNO = this.route.snapshot.params.cardNO
			this.pathologyFormCode = this.route.snapshot.params.pathologyFormCode
			this.searchSpecimen('','load','new')
		}
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},500)
  }
	
	// 初始化新增form表单
	initForm(data) {
		this.syncFlag = data.syncFlag;
		if(data.syncFlag==1){
			this.validateForm.removeControl('project')
		}else{
			this.validateForm.addControl(
				'project',
				new FormControl(null, Validators.required)
			);
		}
		setTimeout(_=>{
			this.detailsData = data
			this.surgeryId = data.surgeryId;
			if(this.detailsData.status && this.detailsData.status.value>=5){
				this.viewType = 'view'
			}else{
				this.viewType = 'edit'
			}
			this.statusValue = this.detailsData.status.value
			this.pathologyLogs = data.formLogDTOS
			this.stepLength = this.pathologyLogs.length
			
			if(this.detailsData.medicalRecords){
				this.medicalRecordsLength = this.detailsData.medicalRecords.length
			}else{
				this.medicalRecordsLength = 0
			}
			
			if(this.detailsData.intraoperativeFindings){
				this.validateForm.controls.intraoperativeFindings.setValue(this.detailsData.intraoperativeFindings);
			}else{
				this.validateForm.controls.intraoperativeFindings.setValue('');
			}
			
			if(this.detailsData.surgicalPlan){
				this.validateForm.controls.surgicalPlan.setValue(this.detailsData.surgicalPlan);
			}else{
				this.validateForm.controls.surgicalPlan.setValue('');
			}
			
			// 检验项目
			if(this.detailsData.status && this.detailsData.status.value==5){
				if(this.detailsData.pathologyInspectDTOS&&this.detailsData.pathologyInspectDTOS.length>0){
					this.project = this.detailsData.pathologyInspectDTOS[0].inspectProject.name
				}
			}else{
				let str = null
				if(this.detailsData.pathologyInspectDTOS){
					if(data.syncFlag==1){
						str = this.detailsData.pathologyInspectDTOS[0].inspectProject.name
						this.project = str
					}else{
						str = this.detailsData.pathologyInspectDTOS[0].inspectProject.id
						this.validateForm.controls.project.setValue(str);
					}
				}else{
					if(data.syncFlag==1){
						this.project = ''
					}else{
						this.validateForm.controls.project.setValue(str);
					}
				}
			}
			
			// 标本类型
			if(this.detailsData.specimenType){
				this.validateForm.controls.specimenGenre.setValue(this.detailsData.specimenType.id);
			}else{
				let item = this.specimenData.find(i=>i.value==10)
				this.validateForm.controls.specimenGenre.setValue(item.id);
			}
			if(this.detailsData.specimenNum){
				this.validateForm.controls.specimenNum.setValue(this.detailsData.specimenNum);
			}else{
				this.validateForm.controls.specimenNum.setValue('');
			}
			if(this.detailsData.takePart){
				this.validateForm.controls.takePart.setValue(this.detailsData.takePart);
			}else{
				this.validateForm.controls.takePart.setValue('');
			}
			this.getSampleData('load')
		},0)
	}
	
	// 获取标本名称
	specimenNameData:any = [];
	getSpecimenName() {
	  let data = {
	    idx: 0,
	    sum: 999,
	    pathologySpecimenName: {
				deptId:this.deptId
	    }
	  };
	  this.mainService
	    .getFetchDataList("data", "pathologySpecimenName", data)
	    .subscribe((data) => {
	      this.specimenNameData = data.list;
	    });
	}
	
	//tab切换
	tabClick(type){
		this.activeIndex = type
	}
	
	// 快捷标本点击
	specimenEditType:any = null;
	fastSpecimenClick(e, item, index){
		if(item.containPosition==1){
			this.isSpinning = true
			let data = {
				pathologyFormId:this.detailsData.id,
				partSource:{
					id:item.position.id
				},
				system:{
					id:item.system.id
				},
				organ:{
					id:item.organ.id
				},
				hosId:this.hosId,
				specimenName:item.specimenName,
			};
			this.mainService
			  .simplePost('addData', "pathologySpecimen", data)
			  .subscribe((res) => {
					this.isSpinning = false;
			    if (res.status == 200) {
						this.message.success('操作成功')
						this.getSampleData('')
			    } else {
						this.message.error(res.msg)
			    }
			  });
		}else{
			this.placeIndex = null
			this.specimenEditType = 'fast'
			this.specimenEdit(e, item, index, 'fast')
		}
	}
	
	// 新增申请单
	applicationType:any;
	addLoading:any = false;
	addPathology(type){
		let data = {
			idx: 0,
			sum: 9999,
			pathologyAdviceId: "",
			patientId: this.patientId || "",
			hosId: this.hosId || "" ,
			operationType: 'outpatientPathologyForm',
			pathologyFormType: 0
		};
		if(type==0){
			delete data.pathologyAdviceId
		}else{
			data.pathologyAdviceId = this.adviceItem.id
		}
		this.addLoading = true
		this.mainService
		.simplePost("addData", "pathologyForm", data)
		.subscribe((data) => {
			this.addLoading = false
			this.viewType = 'edit';
			if(this.leftIndex == null){
				this.leftIndex = 0
			}
			this.searchSpecimen(this.residenceNo,'add','bottom');
		});
	}
	
	// 获取任务类型（病理标本）
	taskTypeData:any;
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='pathology')
			this.getConfig();
		});
	}
	
	// 获取配置
	pathologyBarCode:any = 1;
	ifImmobilization:any = false;
	ifAddapplication:any = false;
	outpatientPathologyLabelSizeType:any = 1; //1:大标本打印 2：小标本打印
	getConfig() {
		let postData = {
			idx: 0,
			sum: 10,
			taskTypeConfig: {
				hosId:this.hosId,
				taskType:this.taskTypeData.id
			}
		}
	  this.mainService
	    .getFetchDataList("simple/data", "taskTypeConfig", postData)
	    .subscribe((result) => {
	      if (result.status == 200) {
					if(result.list[0].outpatientInVitroFixation && result.list[0].outpatientInVitroFixation==1){
						this.ifImmobilization = true
					}else{
						this.ifImmobilization = false
					}
					if(result.list[0].outpatientCreatePathologyForm && result.list[0].outpatientCreatePathologyForm==1){
						this.ifAddapplication = true
					}else{
						this.ifAddapplication = false
					}
					if(result.list[0].outpatientPathologyLabelSize){
						this.outpatientPathologyLabelSizeType = result.list[0].outpatientPathologyLabelSize.value;
					}
					this.pathologyBarCode = result.list[0].pathologyBarCode?result.list[0].pathologyBarCode:1;
	      }
	    });
	}
	
	// 病理申请单删除
	itemData:any;
	delAdviceModal:any = false;
	itemDataType:any = 2;
	delItem(e,data){
		e.stopPropagation();
		this.itemDataType = 1
		this.itemData = data
		this.delAdviceModal = true
	}
	
	// 确定删除
	confirmAdvice(){
		this.btnDelLoading = true;
		this.mainService
		  .coopTypeConfig(
		    "rmvData",
		    "pathologyForm",
		     [this.itemData.id]
		  )
		  .subscribe((data) => {
		    this.btnDelLoading = false;
		    this.delAdviceModal = false;
				this.searchSpecimen(this.residenceNo,'load', 'new');
		    if (data.status==200) {
		      this.showSpecimenModal("删除", true, "");
		    } else {
		      this.showSpecimenModal("删除", false, data.data[0].msg);
		    }
		  });
	}
	// 确定删除
	hideAdviceModal() {
	  this.delAdviceModal = false;
	}
	
	// 病理点击
	leftIndex:any = null;
	adviceItem:any;
	listClick(item,index){
		this.leftIndex = index
		this.adviceItem = item
		if(item.status.value > 4){
			this.activeIndex = 1
		}
		if(item.id){
			this.fetchDataList(item.id);
		}else{
			this.viewType = 'add'
		}
	}
	
	isShowMove:any = true
	showLook(){
		this.isShowMove = !this.isShowMove
	}
	
	// 标本条码搜索
	adviceList:any = null;
	residenceNo:any = null;
	searchSpecimen(e,type,optType){
		if(type!='add' && type!='load'){
			if(!this.barCode){
				return
			}
			if(this.barCode.length < 10 && !this.pressType) {
				return
			}
		}
		let data:any = {
			// idx: 0,
			// sum: 10,
			// pathologyForm:{
				order: "createTime desc",
				// patientNo:this.barCode?this.barCode:e,
				surgeryDeptId:this.deptId,
				// operationType:'outpatientPathologyForm'
			// }
		}
		let name = null
		let value = null
		if(this.cardNO){
			name = 'cardNO'
			value = this.cardNO
			delete data.surgeryDeptId
		} else if (this.pathologyFormCode){
			name = 'pathologyFormCode'
			value = this.pathologyFormCode
			delete data.surgeryDeptId
		} else if (this.barCode || this.residenceNo){
			name = 'patientNo'
			value = this.barCode ? this.barCode : this.residenceNo
			data.surgeryDeptId = this.deptId
		}
		this.isSpinning = true
		// this.mainService.getFetchDataList("data", "pathologyForm", data)
		this.mainService.registerOutpatient(name, value, data)
		.subscribe((res:any) => {
			this.isSpinning = false
			if(res.status==200){
				this.barCode = null
				this.searchMsg = null
				this.isShowMove = true
				if(type=='search' || type=='load'){
					this.leftIndex = null
					this.detailsData = null
					this.statusValue = 1
					this.pathologyLogs = []
					this.adviceList = null
					this.stepLength = 0
					this.viewType = 'no';
				}
				if(res.data.length>0){
					if(res.data[0].pathologyFormDTOS.length>0){
						for(let i of res.data[0].pathologyFormDTOS){
							i.project = []
							if(i.pathologyInspectDTOS){
								for(let x of i.pathologyInspectDTOS){
									i.project.push(x.inspectProject.name)
								}
							}
						}
					}
					this.adviceList = res.data[0]
					this.residenceNo = this.adviceList.patientDTO.residenceNo?this.adviceList.patientDTO.residenceNo:this.adviceList.patientDTO.patientCode
					this.patientId = this.adviceList.patientDTO.id
					if(optType=='bottom'){
						this.leftIndex = 0;
						this.adviceItem = this.adviceList.pathologyFormDTOS[0];
						this.fetchDataList(this.adviceList.pathologyFormDTOS[0].id);
					}
				}else{
					this.adviceList = null
					this.viewType = 'no';
				}
			}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)
		})
	}
	
	// 固定液类型
	getStationaryLiquid(){
		this.mainService.getDictionary("list", "fixing_liquid_type").subscribe((res) => {
			this.fixativeData = res
		});
	}
	
	// 选择固定时间
	fixationTime:any;
	fixationData:any;
	fixationDateChange(result){
		this.fixationData = format(result, 'yyyy-MM-dd');
		console.log(this.fixationData)
	}
	fixationTimeSelect:any;
	fixationTimeChange(result){
		if(result){
			this.fixationTimeSelect = format(result, 'HH:mm');
		}else{
			this.fixationTimeSelect = null;
		}
		console.log(this.fixationData + ' ' + this.fixationTimeSelect)
	}
	
	// 选择离体时间
	inVitroTime:any;
	inVitroData:any;
	inVitroDateChange(result){
		this.inVitroData = format(result, 'yyyy-MM-dd');
		console.log(this.inVitroData)
	}
	inVitroTimeSelect:any = null;
	inVitroTimeChange(result){
		if(result){
			this.inVitroTimeSelect = format(result, 'HH:mm');
		}else{
			this.inVitroTimeSelect = null;
		}
		console.log(this.inVitroData + ' ' + this.inVitroTimeSelect)
	}
	
	// 提交固定标本接收
	startDate:any;
	printLoading:any = false;
	submitVerificationForm(){
		let that = this
		if(this.ifImmobilization && this.detailsData.pathologyFormType==0 && (!this.fixationTimeSelect || this.fixationTimeSelect == null)){
			this.message.error('请选择固定时间')
			return
		}
		if(!this.inVitroTimeSelect || this.inVitroTimeSelect == null){
			this.message.error('请选择离体时间')
			return
		}
		for (const i in this.validatePrintForm.controls) {
		  this.validatePrintForm.controls[i].markAsDirty();
		  this.validatePrintForm.controls[i].updateValueAndValidity();
		}
		if (this.validatePrintForm.invalid) return;
		let ids = this.validateForm.value.project
		let data: any = {
			pathologyForm:{
				...this.detailsData,
				...this.validateForm.value,
				inVitroTime:this.inVitroData + ' ' + this.inVitroTimeSelect+':00',
				fixationTime:this.fixationData + ' ' + this.fixationTimeSelect+':00',
				specimenFixingLiquid:{
					id:this.validatePrintForm.value.fixative
				},
				surgeryId: this.surgeryId || "",
				patientId: this.patientId || "",
				hosId: this.hosId || "" ,
				handoverUserId:this.handoverUserId,
				pathologyInspectIds:ids,
				specimenType:{
					id:this.validateForm.value.specimenGenre
				}
			},
			operation:'',
			pathologySpecimenIds:'',
			deptType:'outpatient'
		};
		delete data.pathologyForm.patientDTO
		delete data.pathologyForm.surgeryDeptDTO
		delete data.pathologyForm.surgeryDoctorDTO
		delete data.pathologyForm.specimenGenre
		data.pathologyForm.specimenNum = this.specimenList.length
		if(this.operation=='addPrint' || this.operation=='wholePrint'){
			data.operation = this.operation
			data.pathologySpecimenIds = this.pathologySpecimenIds
		}else{
			delete data.operation
			delete data.pathologySpecimenIds
		}
		if(this.ifImmobilization){
			data.pathologyForm.fixationTime = this.fixationData + ' ' + this.fixationTimeSelect +':00'
			data.pathologyForm.specimenFixingLiquid.id = this.validatePrintForm.value.fixative
		}else{
			delete data.pathologyForm.fixationTime
			delete data.pathologyForm.specimenFixingLiquid
		}
		this.printLoading = true;
		this.coverType = 0;
		this.mainService
		  .pathologyPrint(data)
		  .subscribe((res:any) => {
				if(res.status==200){
					let arr = res.data;
					if(arr.applyBarCode){
						arr.applyBarCode = this.sanitizer.bypassSecurityTrustResourceUrl(arr.applyBarCode)
					}
					for(let i of arr.specimenList){
						i.applyCode = arr.applyCode?arr.applyCode:data.pathologyForm.applyCode
						i.barCode = this.sanitizer.bypassSecurityTrustResourceUrl(i.barCode)
					}
					that.printLoading = false;
					that.printData = arr;
					this.searchSpecimen(this.residenceNo,'load', 'new');
					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.notModal = false
							// this.fetchDataList(this.detailsData.id)
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
		  });
	}
	
	cancelSpecimenModal(){
		let ids = []
		for(let i of this.codeData.pathologySpecimenDTOList){
			ids.push(i.id)
		}
		let data = {
			pathologySpecimenIds:ids.join(',')
		}
		this.mainService.pathologyOperation(data,'cancel').subscribe((res) =>{
			
		})
	}
	
	medicalRecordsLength:any = 0;
	syncFlag: any = 0;
	fetchDataList(id){
		this.isSpinning = true;
		this.mainService.getFetchData("data", "pathologyForm", id)
		.subscribe((data) => {
			this.isSpinning = false;
			this.initForm(data.data);
			// this.detailsData = data.data;
		});
	}
	
	// 获取标本类型
	getDicData(){
		this.mainService.getDictionary("list", "specimen_type").subscribe((res) => {
			this.specimenData = res.filter(i=>i.extra1 == 'pathologySpecimen')
		});
	}
	
	// 获取检验项目
	getProDicData(){
		this.mainService.getDictionary("list", "pathology_inspect_type").subscribe((res) => {
			this.projectData = res
		});
	}
	
	// 获取标本-位置来源
	getSourceData(){
		this.mainService.getDictionary("list", "pathology_position").subscribe((res) => {
			this.placeList = res
		});
	}
	
	// 获取标本-系统
	getSysData(){
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 1,
		    key: 'pathology_specimen',
		    deleted: 0,
		  },
		};
		this.mainService
		  .getFetchDataList("simple/data", "dictionaryTree", postData)
		  .subscribe((data) => {
		    this.systemList = data.list;
		  });
	
	}
	
	// 获取标本-器官
	getApparatusData(id,item,type){
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 2,
				parent:id,
		    key: 'pathology_specimen',
		    deleted: 0,
		  },
		};
		this.mainService
		  .getFetchDataList("simple/data", "dictionaryTree", postData)
		  .subscribe((data) => {
				if(data.list.length>0){
					this.apparatusList = data.list;
					if(type=='edit'){
						setTimeout(_=>{
							let index3 = this.apparatusList.findIndex(i=>i.id==item.organ.id)
							this.apparatusIndex = index3
							this.apparatusId = Number(item.organ.id);
						},100)
					}
				}else{
					this.message.info('暂无数据')
				}
		  });
	}
	
	// 获取标本-标本名称
	getSpNameData(id,item,type){
		this.selectItem = this.specimenData.find(i=>i.id == this.validateForm.value.specimenGenre)
		let postData: any = {
		  idx: 0,
		  sum: 9999,
		  dictionaryTree: {
		    level: 3,
				parent:id,
		    key: 'pathology_specimen',
		    deleted: 0,
				extra1:'',
		  },
		};
		
		if(this.selectType){
			postData.dictionaryTree.key = 'cell_specimen'
			postData.dictionaryTree.extra1 = this.selectItem.value
			delete postData.dictionaryTree.parent
			delete postData.dictionaryTree.level
			this.mainService.getFetchDataList("simple/data", "dictionaryTree", postData).subscribe((res) => {
				this.specimenNameList = res.list;
				if(type=='edit'){
					this.validateSpecimenForm = this.fb.group({
					  remark: [null, []],
						specimenName: [null, [Validators.required]]
					});
					if(item.sample && this.specimenEditType=='direct'){
						let index4 = this.specimenNameList.findIndex(i=>i.id==item.sample.id)
						this.specimenNameIndex = index4
						this.specimenNameName = item.sample.name
						this.specimenNameId = Number(item.sample.id);
						this.specimenNameLength = item.specimenName.length;
						this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
						this.validateSpecimenForm.controls.remark.setValue(item.remark);
					}else{
						this.specimenNameLength = item.specimenName.length;
						this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
					}
					setTimeout(_=>{
						this.specimenModal = true
					},50)
				}
			});
		}else{
			postData.dictionaryTree.key = 'pathology_specimen'
			postData.dictionaryTree.parent = id
			postData.dictionaryTree.level = 3
			delete postData.dictionaryTree.extra1
			this.mainService.getFetchDataList("simple/data", "dictionaryTree", postData)
			  .subscribe((data) => {
			    this.specimenNameList = data.list;
					if(type=='edit'){
						this.validateSpecimenForm = this.fb.group({
						  remark: [null, []],
							specimenName: [null, [Validators.required]]
						});
						if(item.sample && this.specimenEditType=='direct'){
							let index4 = this.specimenNameList.findIndex(i=>i.id==item.sample.id)
							this.specimenNameIndex = index4
							this.specimenNameName = item.sample.name
							this.specimenNameId = Number(item.sample.id);
							this.specimenNameLength = item.specimenName.length;
							this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
							this.validateSpecimenForm.controls.remark.setValue(item.remark);
						}else{
							this.specimenNameLength = item.specimenName.length;
							this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
						}
						setTimeout(_=>{
							this.specimenModal = true
						},50)
					}
			  });
		}

	}
	
	// 删除标本
	delModal:boolean = false
	coopId:any;
	specimenDel(e,item,index){
		this.delModal = true
		this.itemDataType = 2
		this.coopId = item.id
	}
	
	// 确定删除
	confirmDel(){
		this.mainService
		  .coopTypeConfig(
		    "rmvData",
		    "pathologySpecimen",
		     [this.coopId]
		  )
		  .subscribe((data) => {
		    this.btnLoading = false;
		    this.delModal = false;
				this.getSampleData('')
		    if (data.status==200) {
		      this.showSpecimenModal("删除", true, "");
		    } else {
		      this.showSpecimenModal("删除", false, data.data[0].msg);
		    }
		  });
	}
	// 确定删除
	hideDelModal() {
	  this.delModal = false;
	}
	
	// 编辑标本
	specimenDetailId:any = null;
	specimenEdit(e,item,index,type){
		this.specimenEditType = type
		this.fastIndex = null
		if(type=='fast'){
			this.specimenDetailId = null
		}else{
			this.specimenDetailId = item.id
		}
		if(item.system && item.organ){
			this.selectType = false
			let index1 = null
			if(item.partSource){
				index1 = this.placeList.findIndex(i=>i.id==item.partSource.id)
				this.placeIndex = index1
				this.placeId = Number(item.partSource.id)
				this.placeName = item.partSource.value==1?'':item.partSource.name
				this.nzSmNum = item.partSource.value==1 ? 21 : 20
			}
			let index2 = this.systemList.findIndex(i=>i.id==item.system.id)
			this.systemIndex = index2
			this.systemId = Number(item.system.id)
			this.getApparatusData(item.system.id,item,'edit')
			this.getSpNameData(item.organ.id,item,'edit')
		}else{
			this.selectType = true
			this.getSpNameData(item.specimenId,item,'edit')
		}
	}
	
	// 选择标本
	selectItem:any;
	selectType:any = false;
	openSpecimen(){
		this.selectItem = this.specimenData.find(i=>i.id == this.validateForm.value.specimenGenre)
		console.log(this.selectItem.value) //20 21 22 24 60 80
		this.validateSpecimenForm = this.fb.group({
		  remark: [null, []],
			specimenName:[null, [Validators.required]],
		});
		this.fastIndex = null;
		this.specimenDetailId = null;
		this.placeIndex = null;
		this.systemIndex = null;
		this.apparatusIndex = null;
		this.specimenNameIndex = null;
		this.placeId = null;
		this.systemId = null;
		this.apparatusId = null;
		this.specimenNameId = null;
		this.placeList=[]; //位置来源数据
		this.systemList=[]; //系统数据
		this.apparatusList=[]; //器官数据
		this.specimenNameList=[]; //标本名称数据
		this.specimenNameName = null
		this.specimenModal = true
		if(this.selectItem.value==20 || this.selectItem.value==21 ||
		this.selectItem.value==22 || this.selectItem.value==23 ||
		this.selectItem.value==24 || this.selectItem.value==60 || 
		this.selectItem.value==70 || this.selectItem.value==80){
			this.selectType = true
			this.getSpNameData('',{},'select')
		}else{
			this.selectType = false
			this.getSourceData()
			this.getSysData()
		}
	}
	
	// 选择位置来源
	placeId:any = null;
	placeName:any = null;
	nzSmNum:any = 21;
	placeClick(e,item,index){
		this.placeId = item.id
		this.placeName = item.value==1?'':item.name
		this.nzSmNum = item.value==1 ? 21 : 20
		this.placeIndex = index
	}
	
	// 选择系统
	systemId:any = null;
	systemClick(e,item,index){
		this.systemId = Number(item.id)
		this.systemIndex = index
		this.apparatusList = [];
		this.apparatusId = null;
		this.apparatusIndex = null;
		
		this.specimenNameList = [];
		this.specimenNameId = null;
		this.specimenNameIndex = null;
		this.specimenNameName = null;
		this.fastIndex = null;
		if(this.validateSpecimenForm.value.specimenName){
			this.validateSpecimenForm.controls.specimenName.setValue('')
		}
		this.getApparatusData(item.id,{},'select')
	}
	
	// 选择器官
	apparatusId:any = null;
	apparatusClick(e,item,index){
		this.apparatusId = Number(item.id)
		this.apparatusIndex = index
		this.specimenNameList = [];
		this.specimenNameId = null;
		this.specimenNameIndex = null;
		this.specimenNameName = null;
		this.fastIndex = null;
		if(this.validateSpecimenForm.value.specimenName){
			this.validateSpecimenForm.controls.specimenName.setValue('')
		}
		this.getSpNameData(item.id,{},'select')
	}
	
	// 选择标本名称
	specimenNameId:any = null;
	specimenNameName:any = null;
	specimenNameClick(e,item,index){
		this.specimenNameIndex = index
		let remark = this.validateSpecimenForm.value.remark
			this.specimenNameId = item.id
			this.specimenNameName = item.name
			if(this.validateSpecimenForm.value.specimenName && this.validateSpecimenForm.value.specimenName.length){
				if(item.name.length+this.validateSpecimenForm.value.specimenName.length>19){
					this.message.error('字符长度不能超过20个')
					return
				}
			}
			
			let namn = null
			if(this.validateSpecimenForm.value.specimenName){
				namn = this.validateSpecimenForm.value.specimenName + '、'+ item.name
			}else{
				namn = item.name
			}
			this.validateSpecimenForm.controls.specimenName.setValue(namn);
	}
	
	// 选择标本名称
	fastList:any = [
		{name:'活检'},
		{name:'切除'},
		{name:'穿刺'}
	];
	fastIndex:any = null;
	fastClick(e,item,index){
		this.fastIndex = index
			if(this.validateSpecimenForm.value.specimenName && this.validateSpecimenForm.value.specimenName.length){
				if(item.name.length+this.validateSpecimenForm.value.specimenName.length>19){
					this.message.error('字符长度不能超过20个')
					return
				}
			}
			
			let namn = null
			if(this.validateSpecimenForm.value.specimenName){
				namn = this.validateSpecimenForm.value.specimenName + item.name
			}else{
				namn = item.name
			}
			this.validateSpecimenForm.controls.specimenName.setValue(namn);
	}
	
	// 保存标本
	btnSpLoading:boolean = false;
	addSpLoading:boolean = false;
	addMadal:boolean = false;
	submitSpecimen(type){
		if(!this.selectType){
			if(this.placeIndex==null){
				this.message.error('请选择位置来源')
				return
			}
			if(this.systemIndex==null){
				this.message.error('请选择系统')
				return
			}
			if(this.apparatusIndex==null){
				this.message.error('请选择器官')
				return
			}
		}
		
		if(this.specimenNameIndex==null && this.validateSpecimenForm.value.specimenName == ''){
			this.message.error('请选择标本名称')
			return
		}
		for (const i in this.validateSpecimenForm.controls) {
		  this.validateSpecimenForm.controls[i].markAsDirty();
		  this.validateSpecimenForm.controls[i].updateValueAndValidity();
		}
		if (this.validateSpecimenForm.invalid) return;
		if(this.validateSpecimenForm.value.specimenName.length>19){
			this.message.error('字符长度不能超过20个')
			return
		}
		if(type==2){
			this.addMadal = true
			return
		}
		let data = {
			pathologyFormId:this.detailsData.id,
			partSource:{
				id:this.placeId
			},
			system:{
				id:this.systemId
			},
			organ:{
				id:this.apparatusId
			},
			sample:{
				id:this.specimenNameId
			},
			hosId:this.hosId,
			specimenName:this.validateSpecimenForm.value.specimenName,
			id:'',
			remark:this.validateSpecimenForm.value.remark
		};
		if(this.specimenNameId){
			data.sample.id = this.specimenNameId
		}else{
			delete data.sample
		}
		let queryType = null
		if(this.specimenDetailId){
			queryType = 'updData'
			data.id = this.specimenDetailId
		}else{
			queryType = 'addData'
			delete data.id
		}
		this.btnSpLoading = true;
		this.mainService
		  .simplePost(queryType, "pathologySpecimen", data)
		  .subscribe((res) => {
		    this.btnSpLoading = false;
		    if (res.status == 200) {
					this.message.success('操作成功')
					setTimeout(_=>{
						this.closeSpecimenModel()
					},200)
		    } else {
					this.message.error(res.msg)
		    }
		  });
	}
	
	// 新增下一个标本
	confirmAdd(){
		this.addSpLoading = true
		let data = {
			pathologyFormId:this.detailsData.id,
			partSource:{
				id:this.placeId
			},
			system:{
				id:this.systemId
			},
			organ:{
				id:this.apparatusId
			},
			sample:{
				id:this.specimenNameId
			},
			hosId:this.hosId,
			specimenName:this.validateSpecimenForm.value.specimenName,
			id:'',
			remark:this.validateSpecimenForm.value.remark
		};
		let queryType = null
		if(this.specimenDetailId){
			queryType = 'updData'
			data.id = this.specimenDetailId
		}else{
			queryType = 'addData'
			delete data.id
		}
		this.mainService
		  .simplePost(queryType, "pathologySpecimen", data)
		  .subscribe((res) => {
		    if (res.status == 200) {
					this.message.success('操作成功')
					this.validateSpecimenForm = this.fb.group({
					  remark: [null, []],
						specimenName:[null, [Validators.required]],
					});
					this.specimenDetailId = null;
					this.specimenNameIndex = null;
					this.specimenNameId = null;
					
					this.placeIndex = null;
					this.placeId = null;
					this.addSpLoading = false;
					this.addMadal = false;
					
		    } else {
					this.message.error(res.msg)
		    }
		  });
	}
	
	// 新增下一个标本
	hideAddModal() {
	  this.addMadal = false;
	}
	
	//清空标本名称
	emptData(e){
		e.stopPropagation()
		this.validateSpecimenForm.controls.specimenName.setValue('')
	}
	
	// 监听输入字数
	specimenNameLength:any=0;
	specimenInput(e){
		if(e.length>20){
			return
		}
		this.specimenNameLength = e.length
	}
	
	// 获取标本列表
	getSampleData(type){
		let data={
			idx: 0,
			sum: 9999,
			pathologySpecimen:{
				pathologyFormId:this.detailsData.id
			}
		}
		this.mainService
		  .getFetchDataList("data", "pathologySpecimen", data)
		  .subscribe((res) => {
		    this.specimenList = res.list
				if(type!='load'){
					let str = []
					if(res.list.length>0){
						for(let i of res.list){
							if(i.system && i.organ){
								str.push(i.system.name + '-' + i.organ.name)
							}else{
								str.push(i.specimenName)
							}
						}
						const newStr = new Set(str);
						const newData = Array.from(newStr);
						this.validateForm.controls.takePart.setValue(newData.join('、'));
					}
				}
				this.validateForm.controls.specimenNum.setValue(this.specimenList.length);
		  });
	}
	
	// 关闭标本
	closeSpecimenModel(){
		this.itemDataType = 2
		this.hideSpecimenModal()
	}
	
	specimenModal:any = false;
	hideSpecimenModal(){
		if(this.itemDataType==2){
			this.getSampleData('')
		}
		this.specimenModal = false
	}
	
	hideNotModal(){
		this.notModal = false
	}
	
	// 追加打印
	zjLoading:any = false;
	operation:any;
	pathologySpecimenIds:any;
	superaddition(): void{
		var that = this;
		this.operation = 'addPrint'
		for (const i in that.validateForm.controls) {
			that.validateForm.controls[i].markAsDirty();
			that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
		if(this.specimenList.length==0){
			this.message.error('标本不能为空')
			return
		}
		that.mainService.pathologyCheckPrint('pathologyForm',this.detailsData.id,{}).subscribe((res:any)=>{
			this.separationMsg = res.msg
			if(res.ids){
				this.notModal = true
				this.totalNum = res.totalNum
				this.specimenNum = res.specimenNum
				this.pathologySpecimenIds = res.ids
				let date = new Date();
				
				let inVitroDate = format(date, "yyyy-MM-dd")
				if(this.ifImmobilization){
					this.validatePrintForm = this.fb.group({
						inVitroTimes: [null, [Validators.required]],
						inVitroDate: [null, [Validators.required]],
						fixationTimes: [null, [Validators.required]],
						fixationDate: [null, [Validators.required]],
						fixative:[null, [Validators.required]],
						jobNumber: [null, [Validators.required]],
						name:[null, [Validators.required]],
					});
					let item = this.fixativeData.find(i=>i.value==1)
					this.validatePrintForm.controls.fixative.setValue(item.id);
					this.validatePrintForm.controls.fixationDate.setValue(inVitroDate);
					this.validatePrintForm.controls.fixationTimes.setValue(date);
					this.fixationData = inVitroDate;
					this.fixationTimeSelect = format(date, 'HH:mm');
				}else{
					this.validatePrintForm = this.fb.group({
						inVitroTimes: [null, [Validators.required]],
						inVitroDate: [null, [Validators.required]],
						jobNumber: [null, [Validators.required]],
						name:[null, [Validators.required]],
					});
				}
				this.validatePrintForm.controls.inVitroDate.setValue(inVitroDate);
				this.validatePrintForm.controls.inVitroTimes.setValue(date);
				this.inVitroData = inVitroDate;
				this.inVitroTimeSelect = format(date, 'HH:mm');
				// if(this.detailsData.surgeryDoctorDTO){
				// 	this.validatePrintForm.controls.jobNumber.setValue(this.detailsData.surgeryDoctorDTO.account);
				// 	this.validatePrintForm.controls.name.setValue(this.detailsData.surgeryDoctorDTO.name);
				// }
			}else{
				this.message.info('无新标本需要打印')
			}
		})
	}
	
	// 打印标本/全量
	surgeryId:any;
	patientId:any;
	notModal:any;
	btnLoading:any = false;
	printData:any;
	statusValue:any = 1;
	separationMsg:any = '本次需要记录离体标本6份，本申请单共6份标本';
	submitForm(type): void{
		var that = this;
		this.operation = 'wholePrint'
		for (const i in that.validateForm.controls) {
			that.validateForm.controls[i].markAsDirty();
			that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
		// if(this.validateForm.controls.takePart.value==''){
		// 	this.message.error('请输入采取部位')
		// 	return
		// }
		if(this.specimenList.length==0){
			this.message.error('标本不能为空')
			return
		}
		if(type=='all'){
			that.mainService.pathologyCheckPrint('pathologyForm',this.detailsData.id,{}).subscribe((res:any)=>{
				this.separationMsg = res.msg
				if(res.ids){
					this.notModal = true
					this.totalNum = res.totalNum
					this.specimenNum = res.specimenNum
					this.pathologySpecimenIds = res.ids
					let date = new Date();
					
					let inVitroDate = format(date, "yyyy-MM-dd")
					if(this.ifImmobilization){
						this.validatePrintForm = this.fb.group({
							inVitroTimes: [null, [Validators.required]],
							inVitroDate: [null, [Validators.required]],
							fixationTimes: [null, [Validators.required]],
							fixationDate: [null, [Validators.required]],
							fixative:[null, [Validators.required]],
							jobNumber: [null, [Validators.required]],
							name:[null, [Validators.required]],
						});
						let item = this.fixativeData.find(i=>i.value==1)
						this.validatePrintForm.controls.fixative.setValue(item.id);
						this.validatePrintForm.controls.fixationDate.setValue(inVitroDate);
						this.validatePrintForm.controls.fixationTimes.setValue(date);
						this.fixationData = inVitroDate;
						this.fixationTimeSelect = format(date, 'HH:mm');
					}else{
						this.validatePrintForm = this.fb.group({
							inVitroTimes: [null, [Validators.required]],
							inVitroDate: [null, [Validators.required]],
							jobNumber: [null, [Validators.required]],
							name:[null, [Validators.required]],
						});
					}
					this.validatePrintForm.controls.inVitroDate.setValue(inVitroDate);
					this.validatePrintForm.controls.inVitroTimes.setValue(date);
					this.inVitroData = inVitroDate;
					this.inVitroTimeSelect = format(date, 'HH:mm');
					// if(this.detailsData.surgeryDoctorDTO){
					// 	this.validatePrintForm.controls.jobNumber.setValue(this.detailsData.surgeryDoctorDTO.account);
					// 	this.validatePrintForm.controls.name.setValue(this.detailsData.surgeryDoctorDTO.name);
					// }
				}else{
					let data: any = {
						pathologyForm:{
							...this.detailsData,
							...this.validateForm.value,
							surgeryId: this.surgeryId || "",
							patientId: this.patientId || "",
							hosId: this.hosId || "" ,
							pathologyInspectIds: this.validateForm.value.project,
							specimenType:{
								id:this.validateForm.value.specimenGenre
							}
						},
						operation:'',
						pathologySpecimenIds:'',
						deptType:'outpatient'
					};
					data.pathologyForm.specimenNum = this.specimenList.length
					if(this.operation=='addPrint' || this.operation=='wholePrint'){
						data.operation = this.operation
						data.pathologySpecimenIds = this.pathologySpecimenIds
					}else{
						delete data.operation
						delete data.pathologySpecimenIds
					}
					delete data.pathologyForm.patientDTO
					delete data.pathologyForm.surgeryDeptDTO
					delete data.pathologyForm.surgeryDoctorDTO 
					delete data.pathologyForm.specimenGenre 
					that.btnLoading = true;
					this.printFun(data)
				}
			})
		}else{
			console.log(5555,this.statusValue)
			this.operation = 'null'
			if(this.statusValue==1){
				this.mainService.pathologyCheckPrint('pathologyForm',this.detailsData.id,{}).subscribe((res:any)=>{
					this.separationMsg = res.msg
					this.notModal = true
					this.totalNum = res.totalNum
					this.specimenNum = res.specimenNum
					let date = new Date();
					
					let inVitroDate = format(date, "yyyy-MM-dd")
					if(this.ifImmobilization){
						this.validatePrintForm = this.fb.group({
							inVitroTimes: [null, [Validators.required]],
							inVitroDate: [null, [Validators.required]],
							fixationTimes: [null, [Validators.required]],
							fixationDate: [null, [Validators.required]],
							fixative:[null, [Validators.required]],
							jobNumber: [null, [Validators.required]],
							name:[null, [Validators.required]],
						});
						let item = this.fixativeData.find(i=>i.value==1)
						this.validatePrintForm.controls.fixative.setValue(item.id);
						this.validatePrintForm.controls.fixationDate.setValue(inVitroDate);
						this.validatePrintForm.controls.fixationTimes.setValue(date);
						this.fixationData = inVitroDate;
						this.fixationTimeSelect = format(date, 'HH:mm');
					}else{
						this.validatePrintForm = this.fb.group({
							inVitroTimes: [null, [Validators.required]],
							inVitroDate: [null, [Validators.required]],
							jobNumber: [null, [Validators.required]],
							name:[null, [Validators.required]],
						});
					}
					this.validatePrintForm.controls.inVitroDate.setValue(inVitroDate);
					this.validatePrintForm.controls.inVitroTimes.setValue(date);
					this.inVitroData = inVitroDate;
					this.inVitroTimeSelect = format(date, 'HH:mm');
					// if(this.detailsData.surgeryDoctorDTO){
					// 	this.validatePrintForm.controls.jobNumber.setValue(this.detailsData.surgeryDoctorDTO.account);
					// 	this.validatePrintForm.controls.name.setValue(this.detailsData.surgeryDoctorDTO.name);
					// }
				})
				return
			}
			let data: any = {
				pathologyForm:{
					...this.detailsData,
					...this.validateForm.value,
					surgeryId: this.surgeryId || "",
					patientId: this.patientId || "",
					hosId: this.hosId || "" ,
					pathologyInspectIds:this.validateForm.value.project,
					specimenType:{
						id:this.validateForm.value.specimenGenre
					},
				},
				deptType:'outpatient'
			};
			data.pathologyForm.specimenNum = this.specimenList.length
			delete data.pathologyForm.patientDTO
			delete data.pathologyForm.surgeryDeptDTO
			delete data.pathologyForm.surgeryDoctorDTO 
			delete data.pathologyForm.specimenGenre 
			this.btnLoading = true;
			this.printFun(data)
		}
	}
	
	// 封面打印
	coverType:any;
	coverSubmitForm(){
		this.coverType = 1
		if(this.detailsData.barCode){
			this.detailsData.barCode = this.sanitizer.bypassSecurityTrustResourceUrl(this.detailsData.barCode)
		}
		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();
			},500)
		}, 500);
	}
	
	// 打印
	printFun(data){
		this.coverType = 0;
		this.mainService
			.pathologyPrint(data)
			.subscribe((res:any) => {
				if(res.status==200){
					let arr = res.data;
					if(arr.applyBarCode){
						arr.applyBarCode = this.sanitizer.bypassSecurityTrustResourceUrl(arr.applyBarCode)
					}
					for(let i of arr.specimenList){
						i.applyCode = arr.applyCode?arr.applyCode:data.pathologyForm.applyCode
						i.barCode = this.sanitizer.bypassSecurityTrustResourceUrl(i.barCode)
					}
					this.btnLoading = false;
					this.printData = arr;
					this.searchSpecimen(this.residenceNo,'load', 'new');
					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();
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
			});
	}
	
	// 关闭查看标本
	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(){
		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
			  });
		});
	}

	// 获取当前用户信息
	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.validatePrintForm.controls.name.setValue('');
			return
		}
		let query = {
		  account: e
		};
		this.mainService
		  .jobSearch(query)
		  .subscribe((data:any) => {
				if(data.status==200){
					this.validatePrintForm.controls.name.setValue(data.userName);
					this.handoverUserId = data.userId
				}else{
					this.validatePrintForm.controls.name.setValue('');
					this.handoverUserId =null
					// this.message.error(data.data)
				}
		  });
	}

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

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

	// 按了回车键
	pressType:any = false;
	onEnterPress(){
		if(this.barCode.length < 10) {
			this.pressType = true
			console.log(1,this.barCode)
			this.searchSpecimen(this.barCode,'search','new')
		}else{
			this.pressType = false
			console.log(2,this.barCode)
		}
	}
	
	// 监听标本条码
	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.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){
					this.fixationError = '该标本已经固定过'
				}else{
					this.getFixationNum(res.data[0].id)
					this.codeData = res.data[0]
					this.fixationError = null
				}
			}else{
				this.fixationError = res.msg
			}
		})
	}

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

	closeDetailMoadl(){
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
		this.detailMoadl = false
	}
  // 退出
  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;
  }
	
	// 回到系统管理
	toMain() {
	  this.router.navigateByUrl("main");
	}
	
  // 切换右侧菜单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);
  }
	
	// 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
	showPromptModal(con, success, promptInfo?) {
	  this.promptModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.promptModalShow = true;
	  }, 100);
	}
	
	showSpecimenModal(con, success, promptInfo?) {
	  this.specimenModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.specimenModalShow = true;
	  }, 100);
	}
}

