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';
import { NzMessageService } from 'ng-zorro-antd';
import { ToolService } from 'src/app/services/tool.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: 'app-inspection-execute-assign-prompt-modal',
  templateUrl: './inspection-execute-assign-prompt-modal.component.html',
  styleUrls: ['./inspection-execute-assign-prompt-modal.component.less']
})
export class InspectionExecuteAssignPromptModalComponent implements OnInit {
  @Output() submitFormHand = new EventEmitter();
  @Output() deptFlagHand = new EventEmitter();
  @Input() deptFlag: boolean = false;//模态框
  loading = false;//获取科室的loading
  validateForm: FormGroup;//表单
  currentHospital; //当前院区

  changeInpSubject = new Subject(); //防抖
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private message: NzMessageService,
    private tool: ToolService,
  ) { }

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'user'){
        this.getUsers(v[1]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.getUsers();
    this.initForm()
  }
  // 隐藏模态框
  hideModal() {
    this.deptFlagHand.emit(false)
    this.initForm()
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      userId: [null, [Validators.required]]
    });
  }
  // 边输边搜节流阀
  changeInp(model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([model, e]);
  }
  // 获取处理人
  isLoading = false;
  userList: any = [];
  getUsers(keyword = '') {
    let postData = {
      user: {
        hospital: { id: this.currentHospital.id },
        name: keyword,
        simpleQuery: true,
        menuId: 414,
        roleCodes: 'inspectman',
        engineer: 1,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "user", postData)
      .subscribe((data) => {
        this.userList = data.list;
        this.isLoading = false;
      });
  }

  // 表单提交
  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;

    this.submitFormHand.emit(this.validateForm.value.userId);
  }
}

