import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { MainService } from '../../services/main.service';
import { ToolService } from 'src/app/services/tool.service';
import { startOfDay, format, addDays, addMinutes } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
@Component({
  selector: 'app-add-inspect-info',
  templateUrl: './add-inspect-info.component.html',
  styleUrls: ['./add-inspect-info.component.less']
})
export class AddInspectInfoComponent implements OnInit {
  // 切换科室，切换弹窗
  listOfDisplayData2: any[] = [];
  currentDept; //当前科室

  hosId;
  hsLoading = false;

  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() confirmModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
	@Input() inspectAndPatientTransportConfig:any = {};
  constructor(
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
  ) { }

  patientDTO:any = {};
  inspectData:any = {
    date: new Date(),
  }; //检查项目
  changeInspectSubject = new Subject(); //防抖
  changePatientSubject = new Subject(); //防抖
  changeApplyDeptSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInspectSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getInspectList(v[0]);
    });
    this.changePatientSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getPatientList(v[0]);
    });
    this.changeApplyDeptSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getApplyDeptList(v[0]);
    });
    this.hosId = this.tool.getCurrentHospital().id;
    this.currentDept = this.tool.getCurrentUserDept();
  }

  // 确认弹窗
  confirmModal() {
    if(!this.inspectData.patientId){
      this.message.warning('请选择患者！');
      return;
    }
    if(!this.inspectData.id){
      this.message.warning('请选择检查项目！');
      return;
    }
    if(!this.inspectData.execDeptId){
      this.message.warning('请选择检查科室！');
      return;
    }
    if(!this.inspectData.date){
      this.message.warning('请选择预约时间！');
      return;
    }
    if(!this.inspectData.time){
      this.message.warning('请选择预约时间！');
      return;
    }
    this.confirmModelHs.emit(JSON.stringify({ show: false, inspectData: this.inspectData, patientDTO: this.patientDTO }));//emits(向上弹射)事件
  }

  changePatient(e){
    this.patientDTO = this.patientList.find(v => v.id == this.inspectData.patientId) || {};
  }

  changeApplyDept(e){
    this.inspectData.patientId = undefined;
  }

  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }

  // 下一日
  nextDay() {
    this.inspectData.date = addDays(this.inspectData.date, 1);
  }

  isLoading = false;
  inspectList: Array<any>; //检查项目列表
  // 获取检查项目
  getInspectList(keyword = '') {
    let postData = {
      dictionary: {
        key: "inspect_check_type",
        name: keyword || undefined,
      },
      idx: 0,
      sum: 9999,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("simple/data", "dictionary", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.inspectList = data.list || [];
      });
  }

  // 边输边搜节流阀
  searchInspect(e) {
    this.isLoading = true;
    this.changeInspectSubject.next([e]);
  }

  // 修改检查项目
  inspectDTO:any = {};
  execDeptList:any[] = [];
  changeInspect(id){
    this.inspectDTO = this.inspectList.find(v => v.id == id);
    if(this.inspectDTO){
			this.setTimeData();
      this.inspectData.id = this.inspectDTO.id;
      this.execDeptList = this.inspectDTO.deptList || [];
      this.inspectData.execDeptId = this.execDeptList.length === 1 ? this.execDeptList[0].id : undefined;
      this.inspectData.sign = this.inspectDTO.extra6 || '';
      this.inspectData.type = this.inspectDTO.extra5DTO ? this.inspectDTO.extra5DTO.name : '';
    }else{
      this.inspectData.id = undefined;
      this.inspectData.execDeptId= undefined;
      this.execDeptList = [];
      this.inspectData.sign = '';
      this.inspectData.type = '';
    }
  }
	
	// 选择日期
	mdData:any;
	dateChange(e){
		this.mdData = format(e, 'yyyy-MM-dd')
		this.setTimeData();
	}
	
	// 选择时间
	endTime:any;
	timeChange(e){
		if(e){
			this.mdData = format(this.inspectData.date, 'yyyy-MM-dd')
			this.setTimeData();
		}
	}
	
	// 设置结束时间
	setTimeData(){
		if(this.mdData && this.inspectData.time){
			let num = this.inspectDTO.extra1 ? Number(this.inspectDTO.extra1) : undefined
			let time = addMinutes(this.inspectData.time, num ? num : this.inspectAndPatientTransportConfig.yytimeGapMinute)
			let time2 = format(time, 'HH:mm')
			this.endTime = this.mdData +' '+ time2
			let date = new Date(this.endTime);
			this.inspectData.endCheckTime = date.getTime()
		}
	}
	
  // 打开班次
  openInspect(e){
    if(e){
      this.getInspectList();
    }
  }

  // =========================申请科室=====================
  applyDeptList: Array<any>; //申请科室列表
  // 获取申请科室
  getApplyDeptList(keyword = '') {
    let postData = {
      idx: 0,
      sum: 10,
      department:{
	  		hospital: {
					id: this.hosId
				},
				dept: keyword
	  	}
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department",postData)
      .subscribe((data:any) => {
        this.isLoading = false;
        this.applyDeptList = data.list || [];
      });
  }

  // 边输边搜节流阀
  searchApplyDept(e) {
    this.isLoading = true;
    this.changeApplyDeptSubject.next([e]);
  }

  // 打开
  openApplyDept(e){
    if(e){
      this.getApplyDeptList();
    }
  }
  // =========================申请科室=====================

  // =========================患者=====================
  patientList: Array<any>; //患者列表
  // 获取患者
  getPatientList(keyword = '') {
    let postData = {
      idx: 0,
      sum: 10,
      hosId: this.hosId,
      patientName: keyword || undefined,
      hasBedNum: 1,//有床号
      department: this.inspectData.applyDeptId,
    };
    this.isLoading = true;
    this.mainService
      .listMsgByMain('listPatient',postData)
      .subscribe((data:any) => {
        this.isLoading = false;
        this.patientList = data.list || [];
      });
  }

  // 边输边搜节流阀
  searchPatient(e) {
    this.isLoading = true;
    this.changePatientSubject.next([e]);
  }

  // 打开
  openPatient(e){
    if(e){
      this.getPatientList();
    }
  }
  // =========================患者=====================
}



