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, NzNotificationService } 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-check",
  templateUrl: "./pathology-check.component.html",
  styleUrls: ["./pathology-check.component.less"],
})
export class PathologyCheckComponent 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 notification: NzNotificationService,
	private sanitizer: DomSanitizer,

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

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

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

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

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

  }

	//tab切换
	tabClick(type){
		this.pageReceptionIndex = 1;
		this.activeIndex = type
		localStorage.setItem("pathologyActiveIndex",type)
		this.getJsData(1)
	}

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

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

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

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

		this.receptionModal = true
		this.barCode = null
	}

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

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

	// 监听人员交接接收人工号输入
	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;
	btnLoading:any = false;
	submitFixationForm(){
		this.btnLoading = true
		this.mainService.getSpecimenInfo(this.batchNo,this.deptId,{
			operationType:'handoverDelivery'
		}).subscribe((res:any) => {
			this.btnLoading = false
			this.mustReceived = res;
			// this.currReceived = res.data.currReceived;
			this.btnConnectLoading = false
			// if(this.codeData[0].deliveryUserDTO){
			// 	this.validateConnectForm = this.fb.group({
			// 		receptionNumber: [this.userInfo.account, [Validators.required]],
			// 		dispatchingNumber: [this.codeData[0].deliveryUserDTO.account, [Validators.required]]
			// 	});
			// 	this.dispatchingName = this.codeData[0].deliveryUserDTO.name;
			// 	this.dispatchingUserId = this.codeData[0].deliveryUserDTO.id
			// }else{
			// 	this.validateConnectForm = this.fb.group({
			// 		receptionNumber: [null, [Validators.required]],
			// 		dispatchingNumber: [null, [Validators.required]]
			// 	});
			// 	this.dispatchingName = null;
			// 	this.dispatchingUserId = null
			// }
			// this.receptionName = this.userInfo.name;
			// this.connectUserId = this.userInfo.id;
			this.validateConnectForm = this.fb.group({
				receptionNumber: [null, [Validators.required]],
				dispatchingNumber: [null, [Validators.required]]
			});
			this.dispatchingName = null;
			this.dispatchingUserId = 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,
			checkUser:this.connectUserId,
			deliveryUser:this.dispatchingUserId
		};
		this.btnConnectLoading = true
		this.mainService
		  .handoverCompleted(data)
		  .subscribe((res:any) => {
				this.btnConnectLoading = false
		    if (res.status == 200) {
					if(this.operationType=='pathologyHandoverBook'){
						localStorage.setItem("bookBatchNo",'')
					}else{
						localStorage.setItem("specimenBatchNo",'')
					}
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, res.msg);
		    }
		  });
	}

	// 返回
	hideSpecimenModal(){
		localStorage.setItem("scanCodeData",'')
		if(this.operationType=='pathologyHandoverBook'){//交接本
			this.router.navigateByUrl(`/pathologyCommunicationBook?type=detail`)
		}else if(this.operationType=='surgery'){//手术间
			this.router.navigateByUrl(`/nurse`)
		}else if(this.operationType=='specimenDept'){//标本间
			this.router.navigateByUrl(`/specimenRoomView`)
		}else if(this.operationType=='pathology'){//病理端
			this.router.navigateByUrl(`/pathology`)
		}else if(this.operationType=='sample'){//门诊病理
			this.router.navigateByUrl(`/pathologySample`)
		}
	}

	// 输入工号查询姓名
	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
				}
		  });
	}

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

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


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

	// 标本搜索条码
	errorMsg:any = null;
	searchSpecimenData(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		let data = {
			barcode:e,
			deptId:this.deptId,
			batchNo:this.batchNo,
			platform:this.operationType,
		}
		this.tableLoading = true
		this.mainService.pathologyScanCode(data)
		.subscribe((res:any) => {
			this.tableLoading = false
			this.specimenCode = null
			if(res.status==200){
				this.scanCodeData = res.data[0]
				this.dataType = res.dataType
				if(res.data[0].pathologySpecimenDTOList.length>1){
          this.muArr = [];
					for(let i of res.data[0].pathologySpecimenDTOList){
						if(i.isScan==1){
							this.muArr.push(i)
						}
					}
					this.multiModal = true
					this.codeMultiData = res.data[0].pathologySpecimenDTOList
					localStorage.setItem("scanCodeData",JSON.stringify(res))
					if(this.muArr.length === this.codeMultiData.length){
						this.submitMultiForm()
					}
				}else{
					this.notification.create('success','提示',res.msg);
					this.activeIndex = 0
					this.pageReceptionIndex = 1;
					this.codeData = []
					this.getJsData(1)
				}
				this.errorMsg = null
			}else{
				this.errorMsg = res.msg
			}
		})
	}

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

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

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

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

	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);
	}
}

