import { Component, OnInit, Output, Input } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { addDays, startOfMinute, format, addMinutes } from 'date-fns';
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { ToolService } from 'src/app/services/tool.service';
import { MainService } from '../../services/main.service';

@Component({
  selector: 'app-edit-inspect-info2',
  templateUrl: './edit-inspect-info2.component.html',
  styleUrls: ['./edit-inspect-info2.component.less']
})

export class EditInspectInfo2Component implements OnInit {
  @Input() date:any;
  @Input() execDeptId:any;
  @Input() remarkText:any;
  @Input() applyDept:any = {};
  @Input() patient:any = {};
  @Input() execDeptList:any;
	@Input() extra1:any;
	@Input() inspectAndPatientTransportConfig:any = {};
	@Input() endCheckTime:any = null;
  @Output() submitFormHand = new EventEmitter();
  @Output() cancelFlagHand = new EventEmitter();
  yyDate = null; //预约日期-患者其他服务
  yyTime = null; //预约时间-患者其他服务
  deptId = null;
  remark = '';
  deptList:any[] = [];
  isLoading:boolean = false;
  hosId;

  changePatientSubject = new Subject(); //防抖
  changeApplyDeptSubject = new Subject(); //防抖

  constructor(
    private message: NzMessageService,
    private tool: ToolService,
    private mainService: MainService,
  ) { }

  ngOnInit() {
    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;

    if(this.applyDept){
      this.inspectData.applyDeptId = this.applyDept.id;
      this.applyDeptList = [this.applyDept];
    }

    if(this.patient){
      this.inspectData.patientId = this.patient.id;
      this.patientList = [this.patient];
      this.patientDTO = this.patient;
    }

    if(this.date){
      this.yyDate = new Date(this.date);
      this.yyTime = new Date(this.date);
			this.mdData = format(this.yyDate, 'yyyy-MM-dd')
			if(this.endCheckTime){
				this.setTimeData();
			}
    }

    if(this.execDeptList){
      this.deptList = this.execDeptList;
    }

    console.log('this.remarkText:', this.remarkText)
    if(this.remarkText){
      this.remark = this.remarkText;
    }

    if(this.execDeptId){
      let flag = this.deptList.some(v => v.id == this.execDeptId);
      if(flag){
        this.deptId = this.execDeptId;
      }
    }
  }

  patientDTO:any = {};
  inspectData:any = {}; //检查项目
  changePatient(e){
    this.patientDTO = this.patientList.find(v => v.id == this.inspectData.patientId) || {};
  }

  changeApplyDept(e){
    this.inspectData.patientId = undefined;
  }
	
	// 选择日期
	mdData:any;
	dateChange(e){
		if(e){
			this.mdData = format(e, 'yyyy-MM-dd')
			this.setTimeData();
		}else{
			this.endTime = null
		}
	}
	
	// 选择时间
	endTime:any;
	timeChange(e){
		if(e){
			this.mdData = format(this.yyDate, 'yyyy-MM-dd')
			this.setTimeData();
		}else{
			this.endTime = null
		}
	}
	
	// 设置结束时间
	setTimeData(){
		if(this.mdData && this.yyTime){
			let num = this.extra1 ? Number(this.extra1) : undefined
			let time = addMinutes(this.yyTime, 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()
		}
	}
	
  // =========================申请科室=====================
  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();
    }
  }
  // =========================患者=====================

  // 下一日(患者其他服务)
  nextDay() {
    this.yyDate = addDays(this.yyDate, 1);
  }

  // 隐藏模态框
  hideModal() {
    this.cancelFlagHand.emit(false)
  }

  // 表单提交
  submitForm(): void {
    if(!this.inspectData.applyDeptId) {
      this.message.warning('请选择申请科室！');
      return;
    }
    if(!this.inspectData.patientId) {
      this.message.warning('请选择患者信息！');
      return;
    }
    if(!this.deptId) {
      this.message.warning('请选择检查科室！');
      return;
    }
    if(!this.yyDate || !this.yyTime) {
      this.message.warning('请选择完整预约时间！');
      return;
    }
    this.submitFormHand.emit({
      applyDeptId: this.inspectData.applyDeptId,
      patientDTO: this.patientDTO,
      deptId: this.deptId,
      remark: this.remark,
      date: format(this.yyDate, 'yyyy-MM-dd') + ' ' + format(startOfMinute(this.yyTime), 'HH:mm:ss'),
			endCheckTime: this.inspectData.endCheckTime
		});
  }
}

