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

@Component({
  selector: 'app-incident-substitution-assign',
  templateUrl: './incident-substitution-assign.component.html',
  styleUrls: ['./incident-substitution-assign.component.less']
})
export class IncidentSubstitutionAssignComponent implements OnInit {
  constructor(
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
  ) { }

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[0] === 'user'){
        this.getUsers(v[1]);
      } else if(v[0] === 'group'){
        this.getGroups(v[1]);
      }
    });

    this.initForm();
    this.getHospitals(1);
  }

  // 初始化新增form表单
  validateForm: FormGroup; //新增/编辑表单
  initForm() {
    this.validateForm = this.fb.group({
      hosId: [null, [Validators.required]],//院区
      dutyId: [null, [Validators.required]],//责任部门
      userGroup: [0, [Validators.required]],//分配方式
      userId: [null],//人
      groupId: [null, [Validators.required]],//组
    });
    console.log(this.validateForm.controls)

    // 默认回显当前人的院区和责任部门
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'duty'){
      // 是责任部门
      this.changeHospital(hospital.parent.id);
      this.validateForm.controls.hosId.setValue(hospital.parent.id);
      this.validateForm.controls.dutyId.setValue(hospital.id);
      this.changeDuty(hospital.id);
    }else{
      // 不是责任部门
      this.changeHospital(hospital.id);
      this.validateForm.controls.hosId.setValue(hospital.id);
    }
  }

  // 修改院区
  changeHospital(id){
    this.validateForm.controls.dutyId.setValue(null);
    this.validateForm.controls.userId.setValue(null);
    this.validateForm.controls.groupId.setValue(null);

    this.dutyList = [];
    this.userList = [];
    this.groupList = [];
    this.getHospitals(2, id);
  }

  // 修改责任部门
  changeDuty(id){
    this.validateForm.controls.userId.setValue(null);
    this.validateForm.controls.groupId.setValue(null);

    this.userList = [];
    this.groupList = [];
    this.getGroups();
  }

  // 修改组
  changeGroup(id){
    this.validateForm.controls.userId.setValue(null);
    this.getUsers();
  }

  // 选择人|组
  changeUserGroup(id){
    this.validateForm.controls.userId.setValue(null);
    if(id === 1){
      // 人
      this.requiredConfigChange('userId', true);
    }else{
      // 组
      this.requiredConfigChange('userId', false);
    }
  }

  requiredConfigChange(name: string, required: boolean): void {
    if (!required) {
      this.validateForm.get(name)!.clearValidators();
      this.validateForm.get(name)!.markAsPristine();
    } else {
      this.validateForm.get(name)!.setValidators(Validators.required);
      this.validateForm.get(name)!.markAsDirty();
    }
    this.validateForm.get(name)!.updateValueAndValidity();
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([model, e]);
  }

  // 获取院区
  hospitalList: any = [];
  dutyList: any = [];
  getHospitals(type:number, parentId?) {
    if(type === 1){
      this.hospitalList = this.tool.getHospitalList().filter(v => !v.parent);
      return;
    }
    if(type === 2 && !parentId){
      this.dutyList = [];
      return;
    }
    let postData = {
      hospital: {
        parent: { id: parentId },
        type: { key: 'hospital_type', value: '6' },
      },
      idx: 0,
      sum: 9999,
    };
    this.mainService
      .getFetchDataList("data", "hospital", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this.dutyList = data.list || [];
      });
  }

  // 搜索
  // 获取用户
  userList: any = [];
  getUsers(keyword = '') {
    if(!this.validateForm.value.groupId){
      this.userList = [];
      return;
    }
    let postData = {
      user: {
        name: keyword,
        simpleQuery: true,
        groupdata: { id: this.validateForm.value.groupId },
        roleCodes: 'first-line support,second-line support',
        engineer: 1,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        this.isLoading = false;
        let userList = data.list || [];
        this.userList = userList;
      });
  }

  // 获取组
  groupList: any = []; //所有所属科室(搜索)
  getGroups(keyword = '') {
    if(!this.validateForm.value.dutyId){
      this.groupList = [];
      return;
    }
    let postData = {
      group2: {
        groupName: keyword,
        hospitals: this.validateForm.value.dutyId,
        type: 3,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "group2", postData)
      .subscribe((data) => {
        this.isLoading = false;
        let groupList = data.list || [];
        this.groupList = groupList;
      });
  }
}




