import { Component, OnInit, Output, Input } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { EventEmitter } from '@angular/core';
import { MainService } from '../../services/main.service';

@Component({
  selector: 'app-select-dept',
  templateUrl: './select-dept.component.html',
  styleUrls: ['./select-dept.component.less']
})
export class SelectDeptComponent implements OnInit {
  @Output() submitFormHand = new EventEmitter();
  @Output() deptFlagHand = new EventEmitter();
  @Input() deptFlag: boolean = false;//模态框
  @Input() createLoading: boolean = false;//确定按钮的loading
  @Input() hosId: any;//院区id
  loading = false;//获取科室的loading
  validateForm: FormGroup;//表单
  deptList = [];//护理单元科室列表
  constructor(private fb: FormBuilder, private mainService: MainService) { }

  ngOnInit() {
    this.getDept(this.hosId);
    this.initForm()
  }
  // 隐藏模态框
  hideModal() {
    this.deptFlagHand.emit(false)
    this.initForm()
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      zrDept: [null, [Validators.required]]
    });
  }
  //获取护理单元类型的科室
  getDept(id, keyword = "") {
    this.loading = true;
    let postData = {
      "idx": 0,
      "sum": 10,
      "department": {
        "hospital": {
          "id": id
        },
        "dept": keyword,
        "type": {
          "id": "281"
        }
      }
    };
    this.mainService.getFetchDataList('data','department', postData).subscribe(result => {
      this.loading = false;
      if (result.status == 200) {
        this.deptList = result.list;
      }
    })
  }
  // 表单提交
  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 id = this.validateForm.value.zrDept;
    this.submitFormHand.emit(id);
    this.hideModal();
  }
}

