import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { ToolService } from './../../../../services/tool.service';
import { Component, OnInit, Output, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { EventEmitter } from '@angular/core';
import { MainService } from 'src/app/services/main.service';

@Component({
  selector: 'app-phone-search-more',
  templateUrl: './phone-search-more.component.html',
  styleUrls: ['./phone-search-more.component.less']
})
export class PhoneSearchMoreComponent implements OnInit {
  @Output() submitEvent = new EventEmitter();
  @Output() cancelEvent = new EventEmitter();
  @Input() fieldConfig: any = { fields: [], config: [] };
  @Input() hosId: any;
  @Input() parentDutyId: any;
  @Input() dutyId: any;
  @Input() queryType: any;
  validateForm: FormGroup;//表单
  searchTimerSubject = new Subject();
  constructor(
    private fb: FormBuilder,
    private tool: ToolService,
    private mainService: MainService,
  ) { }

  ngOnInit() {
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
    this.initForm();
  }
  // 隐藏模态框
  hideModal() {
    this.cancelEvent.emit()
  }
  // 初始化form表单
  initForm() {
    this.buildingList = this.fieldConfig.fields.buildingDTO ? [this.fieldConfig.fields.buildingDTO] : [];
    this.floorList = this.fieldConfig.fields.floorDTO ? [this.fieldConfig.fields.floorDTO] : [];
    this.deptList = this.fieldConfig.fields.deptDTO ? [this.fieldConfig.fields.deptDTO] : [];
		this.deptTypeList = this.fieldConfig.fields.deptTypeDTO ? [this.fieldConfig.fields.deptTypeDTO] : [];

    this.validateForm = this.fb.group({
      buildingId: [this.fieldConfig.fields.buildingId || null],
      floorId: [this.fieldConfig.fields.floorId === undefined ? null : this.fieldConfig.fields.floorId],
      deptId: [this.fieldConfig.fields.deptDTO ? this.fieldConfig.fields.deptDTO.id  : null],
			deptTypeId: [this.fieldConfig.fields.deptTypeId || null],
		});
  }
  // 表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty({ onlySelf: true });
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;

    let fields:any = {}
    if(this.fieldConfig.config.buildingAndFloor){
      fields.buildingId = this.validateForm.value.buildingId;
      fields.buildingDTO = this.buildingList.find(item => item.id == this.validateForm.value.buildingId);
      fields.floorId = this.validateForm.value.floorId;
      fields.floorDTO = this.floorList.find(item => item.id == this.validateForm.value.floorId);
    }
    if(this.fieldConfig.config.dept){
      fields.deptId = this.validateForm.value.deptId;
      fields.deptDTO = this.deptList.find(item => item.id == this.validateForm.value.deptId);
    }
		if(this.fieldConfig.config.deptType){
		  fields.deptTypeId = this.validateForm.value.deptTypeId;
		  fields.deptTypeDTO = this.deptTypeList.find(item => item.id == this.validateForm.value.deptTypeId);
		}

    this.submitEvent.emit(fields);
    this.hideModal();
  }

  get getHosId(){
    return this.parentDutyId || this.dutyId || this.hosId;
  }

  // 防抖
  isLoading = false;
  isSelecting:boolean = false; // 是否在选中状态
  searchTimer(fun, e) {
    if (this.isSelecting) {
      this.isSelecting = false; // 重置标志
      return; // 跳过处理
    }
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

  // 设置标志
  setIsSelecting(flag){
    this.isSelecting = flag; // 设置标志
  }

	// =================科室类型===================

	// 科室类型
	openChangeDeptType(flag){
	  flag && this.getDeptTypeList();
	}

	// 获取科室类型列表
	deptTypeList:any[] = [];
	getDeptTypeList(keyword?) {
	  this.isLoading = true;
	  this.mainService
	    .getDictionary("list", "dept_type")
	    .subscribe((data) => {
	      this.isLoading = false;
	      this.deptTypeList = data;
	    });
	}

  // =================楼栋===================

  // 楼栋搜索
  changeBuildingInp(e) {
    this.searchTimer(this.getBuildingList, e);
  }

  // 获取楼栋列表
  buildingList:any[] = [];
  getBuildingList(keyword?){
    let postData: any = {
      idx: 0,
      sum: 20,
      building: {
        simpleQuery: true,
        buildingName: keyword,
        statisticalHosId:this.getHosId,
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "building", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
        this.buildingList = result.list || [];
      }else{
        this.buildingList = [];
      }
    });
  }
  openChangeBuilding(flag){
    flag && this.setIsSelecting(false);
    flag && this.getBuildingList();
  }

  changeBuilding(id){
    this.setIsSelecting(true);
    this.floorList = [];
    this.validateForm.controls.floorId.setValue(null);
    this.getFloorList();
  }

  // =================楼层===================

  // 楼层搜索
  changeFloorInp(e) {
    this.searchTimer(this.getFloorList, e);
  }

  // 获取楼层列表
  floorList:any[] = [];
  getFloorList(keyword = ''){
    if(!this.validateForm.value.buildingId){
      this.isLoading = false;
      this.floorList = [];
      return;
    }
    let postData: any = {
      idx: 0,
      sum: 20,
      floor: {
        floorName: keyword,
        buildId : this.validateForm.value.buildingId,
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "floor", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
        this.floorList = result.list || [];
      }else{
        this.floorList = [];
      }
    });
  }
  openChangeFloor(flag){
    flag && this.setIsSelecting(false);
    flag && this.getFloorList();
  }

  // =================科室===================

  // 科室搜索
  changeDeptInp(e) {
    this.searchTimer(this.getDeptList, e);
  }

  // 获取科室列表
  deptList:any[] = [];
  getDeptList(keyword?){
    let postData: any = {
      idx: 0,
      sum: 20,
      department: {
        statisticalHosId: this.getHosId,
        dept: keyword,
        searchType: 1,
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "department", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
        this.deptList = result.list || [];
      }else{
        this.deptList = [];
      }
    });
  }
  openChangeDept(flag){
    flag && this.setIsSelecting(false);
    flag && this.getDeptList();
  }
}
