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-communication-book",
  templateUrl: "./pathology-communication-book.component.html",
  styleUrls: ["./pathology-communication-book.component.less"],
})
export class PathologyCommunicationBookComponent implements OnInit, OnDestroy {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef4", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef4: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef5", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef5: OverlayScrollbarsComponent;
  constructor(
	private mainService: MainService,
	public router: Router,
	private route: ActivatedRoute,
	public tool: ToolService,
	private fb: FormBuilder,
	private message: NzMessageService,
	private sanitizer: DomSanitizer,
	) {}
  // 今日药单量
  todayTotal: undefined;
  // 今日已完成
  todayComplete: undefined;
  //手术间数据
  printPharmacyList = []; //数据列表
  printPharmacyIdx = 0; //页码
  printPharmacyTotal = 0; //总数
  printPharmacyFlag = false; //是否查看更多
  printPharmacySearchKey = ""; //搜索的内容
  printPharmacyLoad = false; //按钮的loading
  // 标本间列表
  waitPharmacyList = [];
  waitPharmacyIdx = 0;
  waitPharmacyTotal = 0;
  waitPharmacyFlag = false;
  waitPharmacySearchKey = "";
  waitPharmacyLoad = false;
  // 今日离科列表
  pharmacyList = [];
  pharmacyIdx = 0;
  pharmacyTotal = 0;
  pharmacyFlag = false;
  pharmacySearchKey = "";
  pharmacyLoad = false;
  // 配送中列表
  distributionList = [];
  distributionIdx = 0;
  distributionTotal = 0;
  distributionFlag = false;
  distributionSearchKey = "";
  distributionLoad = false;
  // 已完成列表
  completedList = [];
  completedIdx = 0;
  completedTotal = 0;
  completedFlag = false;
  completedSearchKey = "";
  completedLoad = false;

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

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

  time = new Date().getTime(); // 时间戳
  timer = null; // 时间定时器
	showDropdown:boolean = false;
	relevanceModal:boolean = false //关联标本和手术室
	validateForm: FormGroup; //关联标本和手术室表单
	validateVerificationForm: FormGroup; //核验标本
	validateConnectForm: FormGroup; //核验标本
	specimenData:any = []; //标本间数据
	operationData:any = []; //手术间数据
	fixationModal:boolean = false //标本接收固定
	verificationMoadl:boolean = false //标本核验
	specimenCode:any; //标本条码
	listOneData:any=[];
	listOneLength:any;
	pageOneIndex:any = 1;
	pageSize:any = 10;
	listTwoData:any=[];
	listTwoLength:any;
	pageTwoIndex:any = 1;
	listThreeData:any=[];
	listThreeLength:any;
	pageThreeIndex:any = 1;
	loading1:boolean = false;
	loading2:boolean = false;
	loading3:boolean = false;
	loading4:boolean = false;
	loading5:boolean = false;
	fixativeData:any = []; //固体液类型
	hosId:any;
	userId:any;
	detailsData:any;
	isSpinning:boolean = false; //全屏加载状态
	codeData:any = []; //标本条码数据
	btnInfoLoading :boolean = false; //标本加固加载
	activeIndex:any = 0; //tabs选择状态
	changeInpSubject = new Subject(); //防抖
	changeInpSubjectUser = new Subject(); //防抖
	changeInpSubjectSpecimen = new Subject(); //防抖
	changeInpSubjectDepartment = new Subject(); //防抖
	pathologyFormType:any = null; //术中快速
	status:any; //状态
	deliveryUser:any //配送人
	userData:any = []; //患者数据
	statusData:any = []; //状态数据
	isLoading:boolean = false;
	listDetailMoadl:boolean = false; //详情弹框
	department:any = []; //科室数据
	hospital:any = []; //院区数据
	distributionName:any;
	businessType:any = null;
	multiModal:boolean = false;
	specimenMultiCode:any = null;
	codeMultiData:any=[];
	errorMultiMsg:any = null;
	connectModal:boolean = false; //标本交接弹框
	receptionModal:boolean = false; //标本接收弹框
	deptId:any = null;
	detailMoadl:boolean = false;
	rowData:any = null; //table选中数据
	toDayData:any = null;
	toDayTime:any = null;
	backType:any = 'list';
	mainRole:any = false;
	coopBtns:any = {};
	deptName:any = null;
	loginUserDeptId: number = JSON.parse(localStorage.getItem("user")).user.dept
	  .id; //登录人所属科室
  ngOnDestroy() {
    clearTimeout(this.timer);
    clearTimeout(this.logTimer);
		clearTimeout(this.timer);
		clearInterval(this.toDayTime)
  }

  ngOnInit() {
		// this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		//   this.searchSpecimenData(v[0])
		// });
		this.changeInpSubjectSpecimen.pipe(debounceTime(100)).subscribe((v) => {
		  this.searchSpecimen(v[0])
		});
		// this.changeInpSubjectUser.pipe(debounceTime(500)).subscribe((v) => {
		// 	this.isLoading = true
		//   this.getUserData(v[0])
		// });
		this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId()
		this.deptId = this.tool.getCurrentUserDept().id
		this.deptName = this.tool.getCurrentUserDept().dept
		this.getTaskTypesId()
		this.getConnectList()
		if(this.route.snapshot.queryParams && this.route.snapshot.queryParams.type){
			this.backType = this.route.snapshot.queryParams.type
		}
		// this.getUserData('')
		this.getToday()
		if(this.backType=='list'){
			this.changeKs();
		}
		this.getStatusDic()
		clearInterval(this.toDayTime)
		this.toDayTime = setInterval(_=>{
			this.getToday()
		},60000)
  }
	
	isAllDisplayDataChecked:any = false;
	isOperating:any  = false;
	isIndeterminate:any = false;
	listOfAllData: any = [];
	mapOfCheckedId: { [key: string]: boolean } = {};
	numberOfChecked = 0;
	selectedData:any = null;
	
	refreshStatus(): void {
		let arr = [];
		if (this.listOneData.length) {
		  this.isAllDisplayDataChecked = this.listOneData.every(
		    (item) => this.mapOfCheckedId[item.id]
		  );
		} else {
		  this.isAllDisplayDataChecked = false;
		}
		
		for (var m in this.mapOfCheckedId) {
		  if (this.mapOfCheckedId[m]) {
		    arr.push(m);
		  }
		}
		this.selectedData = arr;
	}

	checkAll(value: boolean): void {
		this.listOneData.forEach(item => (this.mapOfCheckedId[item.id] = value));
		this.refreshStatus();
	}
	
	taskTypeData:any;
	getTaskTypesId() {
		this.mainService.getDictionary("list", "ordinary_field").subscribe((data) => {
			this.taskTypeData = data.find(i=>i.value=='pathology')
			this.getConfig();
		});
	}
	
	// 获取配置
	pathologyBarCode:any = 1;
	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) {
					this.pathologyBarCode = result.list[0].pathologyBarCode?result.list[0].pathologyBarCode:1;
	      }
	    });
	}
	
	// 打印
	btnLoading:any = false;
	printData:any = [];
	print(type, data){
		let ids = null
		if(type=='batchPrint'){
			if(!this.selectedData || this.selectedData.length==0){
				this.message.error('请先选择申请单')
				return
			}
			ids = this.selectedData.join(',')
		}
		this.isSpinning = true
		let query = {
			operation: 'pathologyHandoverBook',
			pathologyFormIds: type=='batchPrint' ? ids : data.id
		}
		this.mainService
			.pathologyPrint(query)
			.subscribe((res:any) => {
				if(res.status==200){
					let arr = res.data;
					for(let i of arr){
						if(i.barCode){
							i.barCode = this.sanitizer.bypassSecurityTrustResourceUrl(i.barCode)
						}
					}
					this.isSpinning = false;
					this.printData = arr;
					this.getConnectList();
					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)
				}
			});
	}
	
	//tab切换
	tabClick(type){
		this.activeIndex = type
		localStorage.setItem("pathologyActiveIndex",type)
		this.pageOneIndex = 1;
		if(type==0){
			this.getConnectList()
		}else{
			this.getConnectList()
		}
	}
	
	// 获取状态字典
	getStatusDic(){
		this.mainService.getDictionary("list", "pathology_form_status").subscribe((res) => {
			this.statusData = res
		});
	}
	
	// 获取今日接收数据
	getToday(){
		this.mainService
		  .pathologyToday({
				deptId:this.deptId,
				platform:'pathologyHandoverBook'
			})
		  .subscribe((data:any) => {
		    this.toDayData = data.data
		  });
	}
	
	//配送人搜索
	changeUserInp(e){
		this.changeInpSubjectUser.next([e]);
	}

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

	// 搜索
	search() {
	  this.pageOneIndex = 1;
	  this.getConnectList();
	}
	// 重置
	reset() {
	  this.pageOneIndex = 1;
		this.status = null;
		this.pathologyFormType = null;
		this.deliveryUser = null;
	  this.getConnectList();
	}
	// 交接本数据
	getConnectList() {
	  var that = this;
	  let data = {
	    idx: that.pageOneIndex - 1,
	    sum: that.pageSize,
	    pathologyForm: {
	      startTime: this.startDate,
	  		endTime: this.endDate,
				surgeryDeptId:this.deptId,
				keyWords:this.deliveryUser,
				operationType:'pathologyHandoverBookList',
				status:{
					id:this.status
				},
				pathologyFormType:this.pathologyFormType,
				printFlag:null
	    },
	  };
		if(this.activeIndex==1){
			data.pathologyForm.printFlag = 0
			this.isAllDisplayDataChecked = false;
			this.mapOfCheckedId = {};
			this.selectedData = null;
		}else{
			delete data.pathologyForm.printFlag
		}
	  this.loading1 = true;
	  that.mainService
	    .getFetchDataList("data", "pathologyForm", data)
	    .subscribe((data) => {
	      this.loading1 = false;
	      that.listOneData = data.list;
	      that.listOneLength = data.totalNum;
	    });
	}

	// 查看
	project:any = [];
	oneLook(e,data){
		this.isSpinning = true
		this.mainService.getFetchData("data", "pathologyForm", data.id)
		.subscribe((data) => {
			this.isSpinning = false
			this.detailMoadl = true
			// this.distributionModal = true
			this.detailsData = data.data
		  this.specimenList = data.data.pathologySpecimenDTOList||[]
			this.pathologyLogs = data.data.formLogDTOS
			this.stepLength = this.pathologyLogs.length
			if(this.detailsData.pathologyInspectDTOS){
				this.project = this.detailsData.pathologyInspectDTOS.map(i=>{
					return i.inspectProject.name
				})
				this.project = this.project.join('、')
			}
		});
	}

	// 配送清点
	distributionTab(){
		this.batchNo = localStorage.getItem("bookBatchNo")
		if(this.batchNo){
			localStorage.setItem("scanCodeData",'')
			localStorage.setItem("checkType",'pathologyHandoverBook')
			this.router.navigateByUrl(`/pathologyCheck?batchNo=${this.batchNo}`);
		}else{
			this.mainService.generateBatchNumber()
			.subscribe((res:any) =>{
				this.batchNo = res.data
				localStorage.setItem("bookBatchNo",res.data)
				localStorage.setItem("scanCodeData",'')
				localStorage.setItem("checkType",'pathologyHandoverBook')
				this.router.navigateByUrl(`/pathologyCheck?batchNo=${this.batchNo}`);
			})
		}
	}
	
	// 关闭查看标本
	closeSpecimenModal(){
		this.specimenViewDialog = false
	}
	
	// 查看标本
	specimenViewDialog:any = false;
	viewData:any = [];
	specimenItem:any;
	specimenView(item){
		this.viewData = []
		this.specimenViewDialog = true
		this.specimenItem = item;
		this.viewData.push(item)
	}
	
	// 获取院区
	getHospitalData(){
		let arr = this.tool.getHospitalList().filter(i=>i.parent==undefined)
		this.hospital = arr
		// let data = {
		//   idx: 0,
		//   sum: 9999,
		// 	hospital:{
		// 		selectType:'level1'
		// 	}
		// };
		// this.mainService
		//   .getFetchDataList("data", "hospital", data)
		//   .subscribe((res) => {
		//     this.hospital = res.list;
		//   });
	}

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

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

	// 接收时间
	startDate:any = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	endDate:any = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	acceptTime:any = [this.startDate,this.endDate];
	changeDate(result){
		if(result.length>0){
			this.startDate = format(result[0], 'yyyy-MM-dd' +' '+'00:00:00');
			this.endDate = format(result[1], 'yyyy-MM-dd' +' '+'23:59:59');
			this.acceptTime = [this.startDate,this.endDate]
		}else{
			this.startDate = null;
			this.endDate = null;
			this.acceptTime = []
		}
	}

	// 标本条码搜索
	searchMsg:any = null
	batchNo:any = null;
	scanCodeData:any = null;
	dataType:any = null;
	searchSpecimen(e){
		if(!e){
			return
		}
		if(e.length < 10) {
			return
		}
		this.isSpinning = true
		this.batchNo = localStorage.getItem("bookBatchNo")
		if(this.batchNo){
			let data={
				barcode:e,
				deptId:this.deptId,
				batchNo:this.batchNo,
				platform:'pathologyHandoverBook',
			}
			this.mainService.pathologyScanCode(data)
			.subscribe((res:any) => {
				this.isSpinning = false
				if(res.status==200){
					localStorage.setItem("scanCodeData",JSON.stringify(res))
					localStorage.setItem("dataType",res.dataType)
					localStorage.setItem("checkType",'pathologyHandoverBook')
					this.router.navigateByUrl(`/pathologyCheck?batchNo=${this.batchNo}&businessType=connect`);
					this.searchMsg = null
				}else{
					this.barCode = null
					this.searchMsg = res.msg
				}
			})
		}else{
			this.mainService.generateBatchNumber()
			.subscribe((res1:any) => {
				if(res1.status==200){
					this.batchNo = res1.data
					localStorage.setItem("bookBatchNo",res1.data)
					let data={
						barcode:e,
						deptId:this.deptId,
						batchNo:this.batchNo,
						platform:'pathologyHandoverBook',
					}
					this.mainService.pathologyScanCode(data)
					.subscribe((res:any) => {
						this.isSpinning = false
						if(res.status==200){
							localStorage.setItem("scanCodeData",JSON.stringify(res))
							localStorage.setItem("dataType",res.dataType)
							localStorage.setItem("checkType",'pathologyHandoverBook')
							this.router.navigateByUrl(`/pathologyCheck?batchNo=${this.batchNo}&businessType=connect`);
							this.searchMsg = null
						}else{
							this.barCode = null
							this.searchMsg = res.msg
						}
					})
				}
			})
		}
	}
	
	// 获取标本接收数据
	pageReceptionIndex:any = 1;
	listReceptionLength:any = 0;
	tableLoading:any = false;
	otherData:any=null;
	getJsData(type){
		let data = {
		  idx: this.pageReceptionIndex-1,
		  sum: this.pageSize,
		  pathologyForm: {
		    batchNo:this.batchNo,
		  },
		};
		this.tableLoading = true;
		this.mainService
		  .getFetchDataList("data", "pathologyForm", data)
		  .subscribe((res) => {
				this.tableLoading = false;
				if(type==1){
					this.fixationModal = true
					setTimeout(_=>{
						document.getElementById('specimen').focus();
					},200)
				}else if(type==3){
					this.fixationModal = true
					this.multiModal = true
					setTimeout(_=>{
						document.getElementById('multiSpecimen').focus();
					},200)
				}
		    this.codeData = res.list;
				this.otherData = res.otherData;
				this.listReceptionLength = res.totalNum;
		  });
	}

	getNewDept(){
		let postData = {
		  currentHosId: this.hosId,
		  loginType: "PC",
		};
		this.mainService.changeHospital(postData).subscribe((result) => {
		  if (result.status == 200) {
		    let dataObj = {
		      user: {
						upType: "changeDept",
						account: JSON.parse(localStorage.getItem("user")).user.account,
		        dept: {
		          id: this.validateForm.value.specimen,
		        },
		        id: JSON.parse(localStorage.getItem("user")).user.id,
		      },
		    };
		    this.mainService
		      .coopData("updData", "user", dataObj)
		      .subscribe((data) => {
		        if (data.status == 200) {
		          this.getCurrentUserNow();
		        }
		      });
		  }
		});
	}

	// 获取当前用户信息
	getCurrentUserNow() {
	  this.mainService.getCurrentUser1().subscribe((data:any) => {
	    if (data["status"] == 200) {
				this.loginUser = data.data
	      let user = JSON.parse(localStorage.getItem("user"));
	      user.user.dept = data["data"].dept;
	      user.user.currentHospital = data["data"].currentHospital;
	      localStorage.setItem("user", JSON.stringify(user));
	    }
	  });
	}

	// 成功/失败提示框
	closeModel(){
		
	}

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

	pathologyLogs:any=[];
	specimenList:any=[]
	stepLength:any = 0;
	closeDetailMoadl(){
		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");
		localStorage.removeItem("scanCodeData");
		localStorage.removeItem("dataType");
		localStorage.removeItem("pathologyActiveIndex");
    // 假退出
    this.mainService.logOut().subscribe((data) => {
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("index");
				localStorage.removeItem("scanCodeData");
				localStorage.removeItem("dataType");
				localStorage.removeItem("pathologyActiveIndex");
      }
    });

  }

  // 右侧菜单
  showLastItems: boolean = false;
  // 下拉
  fixedMenuXiala() {
    this.showLastItems = true;
  }

  // 上拉
  fixedMenuShangla() {
    this.showLastItems = false;
  }
	
	// 回到系统管理
	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;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
  }
  //子传父接收
  clearModelHs(e) {
    if (JSON.parse(e).clear === true) {
      clearInterval(this.timerCloseTime);
    }
    this.changeShow = JSON.parse(e).changeShow;
		setTimeout(_=>{
			document.getElementById('Binput').focus();
		},200)
  }
  // 头部切换科室
  changeKsNow() {
    this.hsPromptModalShow = true;
    clearInterval(this.timerCloseTime);
    this.changeShow = false;
  }
  // 切换科室
  changeKs() {
    this.hsPromptModalShow = true;
    // (1)	当用户设置为正数时，用户必须查看此窗体指定秒数。
    // (2)	当用户设置为负数时，用户可点击知道了也可倒计时自动关闭。
    // (3)	如果用户填写0则为无自动关闭和强制查看时间。
    if (this.closeTimeFlag === 0) {
      return;
    }
    this.closeTime = Math.abs(this.closeTimeFlag);
    clearInterval(this.timerCloseTime);
    this.timerCloseTime = setInterval(() => {
      this.closeTime = Math.max(--this.closeTime, 0);
      if (this.closeTime === 0) {
        if (this.closeTimeFlag <= 0) {
          this.hsPromptModalShow = false;
        }
        clearInterval(this.timerCloseTime);
      }
    }, 1000);
  }

	promptModalShow:boolean = false;
	promptContent:any = null;
	ifSuccess:any = null;
	promptInfo:any = null;
	// 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
	showPromptModal(con, success, promptInfo?) {
	  this.promptModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.promptModalShow = true;
	  }, 100);
	}
}

