import { Component, ElementRef, Output, Input, OnInit, EventEmitter } from '@angular/core';
import { HttpHeaders, HttpRequest, HttpClient  } from "@angular/common/http";
import host from "../../../assets/js/http";
import { NzMessageService } from "ng-zorro-antd";
import { MainService } from '../../services/main.service';
import { DomSanitizer } from '@angular/platform-browser';
import {
  FormBuilder,
  Validators,
  FormGroup,
  FormControl,
} from "@angular/forms";
import { format, startOfDay, endOfDay, subDays} from "date-fns";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: 'app-pathology-add',
  templateUrl: './pathology-add.component.html',
  styleUrls: ['./pathology-add.component.less']
})
export class PathologyAddComponent implements OnInit {
	
	@Output() pathologyCancel = new EventEmitter();
	@Input() surgeryId: string;
	@Input() patientId: string;
	@Input() detailId: string;
	@Input() applicationType: string;
	
	constructor(
		private http: HttpClient,
		private message: NzMessageService,
		private mainService: MainService,
		private fb: FormBuilder,
		private tool: ToolService,
		private sanitizer: DomSanitizer
	) { }
	
	btnLoading:boolean = false;
	validateForm: FormGroup; //新增/编辑表单
	validateSpecimenForm: FormGroup; //选择标本表单
	validatePrintForm: FormGroup;
	specimenData:any=[]; //标本类型
	projectData:any=[]; //检验项目
	isDeptLoading:boolean = false;
	specimenModal:boolean = false; //选择标本状态
	isSpinning:boolean = false; //页面加载状态
	detailsData:any;
	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 = '未打印';
	notModal:boolean = false;
	hosId:any;
	startDate: string; //离体开始
	
  ngOnInit() {
		this.hosId = this.tool.getCurrentHospital().id;
		this.initForm()
		this.fetchDataList()
		this.getStationaryLiquid()
  }
	
	// 获取任务类型（病理标本）
	taskTypeData:any;
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='pathology')
			this.getPathologySys();
		});
	}
	
	// 获取标本配置
	pathologyBarCode:any = 1;
	ifImmobilization:any = false;
	surgeryPathologyLabelSize:any = 1;
	prompt:any;
	pathologyFrozenSpecimen:boolean = false;
	taskTypeConfig:any;
	getPathologySys(){
		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) {
					this.taskTypeConfig = result.list[0]
					this.pathologyBarCode = result.list[0].pathologyBarCode?result.list[0].pathologyBarCode:1;
					if(result.list[0].surgeryPathologyLabelSize){
						this.surgeryPathologyLabelSize = result.list[0].surgeryPathologyLabelSize.value;
					}
					if(result.list[0].outpatientInVitroFixation && result.list[0].outpatientInVitroFixation==1){
						this.ifImmobilization = true
					}else{
						this.ifImmobilization = false
					}
					
					if(this.detailsData.pathologyFormType==1 && this.taskTypeConfig.pathologyFrozenSpecimenNum==1){
						this.pathologyFrozenSpecimen = true
						this.prompt = this.taskTypeConfig.prompt
						console.log(4444)
					}else{
						this.pathologyFrozenSpecimen = false
						this.prompt = null
					}
				}
		  });
	}
	
	radioChange(data){
		let arr = [];
		let item = null
		// if(!this.validateForm.value.project){
			if(data==1){
				item = this.projectData.find(i=>i.value=='2241') //冰冻切片检查
			}else{
				item = this.projectData.find(i=>i.value=='1810') //病理小标本
			}
			console.log(5555,item)
			arr.push(item.id)
			this.validateForm.controls.project.setValue(arr);
		// }
	}
	
	// 初始化新增form表单
	initForm() {
		this.validateForm = this.fb.group({
		  pathologyFormType: [null, [Validators.required]],
			specimenGenre: [null, [Validators.required]],
			intraoperativeFindings: [null, []],
			project: [null, [Validators.required]],
			// surgicalPlan: [null, [Validators.required]],
			specimenNum: [null,[Validators.required]],
			takePart: [null, [Validators.required]]
		});
	}
	
	statusValue:any = 1;
	fetchDataList(){
		// let data = {
		//   idx: 0,
		//   sum: 9999,
		//   pathologyForm: {
		// 		surgeryId: "",
		//     patientId: this.patientId || "",
		//     hosId: this.hosId || "" ,
		//   },
		// };
		this.isSpinning = true;
		// this.mainService
		//   .getFetchDataList("data", "pathologyForm", data)
			this.mainService.getFetchData("data", "pathologyForm", this.detailId)
		  .subscribe((data) => {
		    this.isSpinning = false;
		    this.detailsData = data.data;
				this.patientId = data.data.patientId;
				this.surgeryId = data.data.surgeryId;
				if(this.detailsData.status){
					this.statusValue = this.detailsData.status.value
				}
				if(this.detailsData.pathologyFormType!=null){
					this.validateForm.controls.pathologyFormType.setValue(this.detailsData.pathologyFormType);
				}

				if(this.detailsData.intraoperativeFindings){
					this.validateForm.controls.intraoperativeFindings.setValue(this.detailsData.intraoperativeFindings);
				}
			
				this.getTaskTypesId()
				this.getSpecimenName()
				this.getProDicData()
				this.getDicData()
				this.getSampleData('load')
				this.getSourceData()
				this.getSysData()
		  });
	}
	
	// 获取标本名称
	specimenNameData:any = [];
	getSpecimenName() {
	  let data = {
	    idx: 0,
	    sum: 999,
	    pathologySpecimenName: {
				deptId:this.detailsData.patientDTO.department.id
	    }
	  };
	  this.mainService
	    .getFetchDataList("data", "pathologySpecimenName", data)
	    .subscribe((data) => {
	      this.specimenNameData = data.list;
	    });
	}
	
	//tab切换
	activeIndex:any = 1;
	tabClick(type){
		this.activeIndex = type
	}
	
	// 快捷标本点击
	specimenEditType:any = null;
	fastSpecimenClick(e, item, index){
		if(this.detailsData.pathologyFormType==1 && this.pathologyFrozenSpecimen && this.specimenList.length>0){
			this.message.error(this.prompt)
			return
		}
		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')
		}
	}
	
	// 固定液类型
	fixativeData:any = [];
	getStationaryLiquid(){
		this.mainService.getDictionary("list", "fixing_liquid_type").subscribe((res) => {
			this.fixativeData = res
		});
	}
	
	// 获取标本类型
	getDicData(){
		this.mainService.getDictionary("list", "specimen_type").subscribe((res) => {
			this.specimenData = res.filter(i=>i.extra1 == 'pathologySpecimen')
			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);
			}
			if(this.detailsData.takePart){
				this.validateForm.controls.takePart.setValue(this.detailsData.takePart);
			}
		});
	}
	
	// 获取检验项目
	getProDicData(){
		this.mainService.getDictionary("list", "pathology_inspect_type").subscribe((res) => {
			this.projectData = res
			let arr = []
			if(this.detailsData.pathologyInspectDTOS){
				for(let i of this.detailsData.pathologyInspectDTOS){
					arr.push(i.inspectProject.id)
				}
				this.validateForm.controls.project.setValue(arr);
			}
		});
	}
	
	// 获取标本-位置来源
	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]]
					});
					this.fastIndex = null
					if(item.sample){
						setTimeout(_=>{
							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);
							this.specimenModal = true
						},50)
					}else{
						if(this.specimenEditType=='direct'){
							setTimeout(_=>{
								this.specimenNameIndex = null
								this.specimenNameName = ''
								this.specimenNameId = null
								this.specimenNameLength = item.specimenName.length;
								this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
								this.validateSpecimenForm.controls.remark.setValue(item.remark);
								this.specimenModal = true
							},50)
						}else{
							setTimeout(_=>{
								this.specimenNameIndex = null
								this.specimenNameName = ''
								this.specimenNameId = null
								this.specimenNameLength = item.specimenName.length;
								this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
								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){
							setTimeout(_=>{
								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);
								this.specimenModal = true
							},50)
						}else{
							if(this.specimenEditType=='direct'){
								setTimeout(_=>{
									this.specimenNameIndex = null
									this.specimenNameName = ''
									this.specimenNameId = null
									this.specimenNameLength = item.specimenName.length;
									this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
									this.validateSpecimenForm.controls.remark.setValue(item.remark);
									this.specimenModal = true
								},50)
							}else{
								setTimeout(_=>{
									this.specimenNameIndex = null
									this.specimenNameName = ''
									this.specimenNameId = null
									this.specimenNameLength = item.specimenName.length;
									this.validateSpecimenForm.controls.specimenName.setValue(item.specimenName);
									this.specimenModal = true
								},50)
							}
						}
					}
			  });
		}
	}
	
	// 删除标本
	delModal:boolean = false
	coopId:any;
	specimenDel(e,item,index){
		this.delModal = true
		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
		};
		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('、'));
						// if(this.selectType){
						// 	this.validateForm.controls.takePart.setValue(
						// 	this.validateSpecimenForm.controls.specimenName
						// 	)
						// }else{
							
						// }
					}
				}
				this.validateForm.controls.specimenNum.setValue(this.specimenList.length);
		  });
	}
	
	hideSpecimenModal(){
		this.getSampleData('')
		this.specimenModal = false
	}
	
	hideNotModal(){
		this.notModal = false
	}
	
	// 选择固定时间
	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)
	}
	
	// 选择离体时间
	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)
	}
	
	//未打印提交
	printLoading:boolean = false;
	submitPrintForm(): void{
		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.join(',')
		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:'surgery'
		};
		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 && this.detailsData.pathologyFormType==0){
			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.coverType = 0
		this.printLoading = true;
		this.mainService
		  .pathologyPrint(data)
		  .subscribe((res:any) => {
				if(res.status==200){
					let arr = res.data;
					// if(arr.specimenList.length==1){
					// 	for(let i of arr.specimenList){
					// 		i.applyCode = data.pathologyForm.applyCode
					// 	}
					// }
					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;
					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.hideModal();
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
		  });
	}
	
	// 监听工号数据
	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)
				}
		  });
	}
	
	// 暂存/保存
	zcLoading:any = false;
	temporary(type): void{
		var that = this;
		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
		}
		let data = {
			pathologyForm:{
				...this.detailsData,
				...this.validateForm.value,
				surgeryId: this.surgeryId || "",
				patientId: this.patientId || "",
				hosId: this.hosId || "" ,
				pathologyInspectIds: this.validateForm.value.project.join(','),
				specimenType:{
					id:this.validateForm.value.specimenGenre
				}
			}
		};
		data.pathologyForm.specimenNum = this.specimenList.length
		delete data.pathologyForm.patientDTO
		delete data.pathologyForm.surgeryDeptDTO
		delete data.pathologyForm.surgeryDoctorDTO 
		delete data.pathologyForm.specimenGenre 
		that.zcLoading = true;
		this.mainService.pathologyOperation(data,'storage').subscribe((res:any) => {
			that.zcLoading = false;
			if(res.status==200){
				this.message.success('操作成功')
				this.hideModal()
			}else{
				this.message.error(res.msg)
			}
		});
	}
	
	// 追加打印
	zjLoading:any = false;
	operation:any;
	pathologySpecimenIds:any;
	totalNum:any;
	specimenNum: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.detailsData.pathologyFormType==0){
					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 = null;
				}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');
			}else{
				this.message.info('无新标本需要打印')
			}
		})
	}
	
	// 打印标本/全量
	printData:any;
	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.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.detailsData.pathologyFormType==0){
						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 = null;
					}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');
				}else{
					let data: any = {
						pathologyForm:{
							...this.detailsData,
							...this.validateForm.value,
							surgeryId: this.surgeryId || "",
							patientId: this.patientId || "",
							hosId: this.hosId || "" ,
							pathologyInspectIds: this.validateForm.value.project.join(','),
							specimenType:{
								id:this.validateForm.value.specimenGenre
							}
						},
						deptType:'surgery',
						operation:'',
						pathologySpecimenIds:'',
					};
					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{
			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.detailsData.pathologyFormType==0){
						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 = null;
					}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');
				})
				return
			}
			let data: any = {
				pathologyForm:{
					...this.detailsData,
					...this.validateForm.value,
					surgeryId: this.surgeryId || "",
					patientId: this.patientId || "",
					hosId: this.hosId || "" ,
					pathologyInspectIds:this.validateForm.value.project.join(','),
					specimenType:{
						id:this.validateForm.value.specimenGenre
					},
				},
				deptType:'surgery'
			};
			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();
				this.hideModal();
			},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;
					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.hideModal();
						},500)
					}, 500);
				}else{
					this.message.error(res.msg)
				}
		  });
	}
	
	// 关闭标本
	closeSpecimenModel(){
		this.getSampleData('')
		this.hideSpecimenModal()
	}
	
	closeModel(){
		this.hideModal()
	}
	hideModal(){
		this.pathologyCancel.emit()
	}
	
	// 展示信息提示框（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);
	}
}

