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

@Component({
  selector: 'app-inspection-address-department-prompt-modal',
  templateUrl: './inspection-address-department-prompt-modal.component.html',
  styleUrls: ['./inspection-address-department-prompt-modal.component.less']
})
export class InspectionAddressDepartmentPromptModalComponent implements OnInit {
  // 切换科室，切换弹窗
  hsLoading = false;
  historySpecimenList: any = [];
  historySpecimenPageIndex: number = 1;//表格当前页码
  historySpecimenPageSize: number = 10;//表格每页展示条数
  historySpecimenListLength: number = 0;//表格总数据量

  currentHospital; //当前院区
  searchDto: any = {};

  changeInpSubject = new Subject(); //防抖

  @Input() show: Boolean;

  @Output() confirmModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件
  @Output() closeModelHs = new EventEmitter<any>();//1.组件暴露一个 EventEmitter 属性，当事件发生时，子组件利用该属性 emits(向上弹射)事件

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

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'building'){
        this.getBuildings(v[0], v[2]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.getList();
    this.getBuildings('search', '');
    this.getDeptTypeList();
  }

  // 搜索
  search() {
    this.getList();
  }
  // 重置
  reset() {
    this.searchDto = {};
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.getList(1);
  }

  //获取科室类型
  deptTypeList:any[] = [];
  getDeptTypeList() {
    this.mainService
    .getDictionary('list', 'dept_type')
    .subscribe((data) => {
      this.deptTypeList = data || [];
    });
  }

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

  // 获取楼栋
  buildingSearchList: any = [];
  getBuildings(type, keyword, init = false) {
    let postData = {
      building: {
        simpleQuery: true,
        buildingName: keyword,
        cascadeHosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "building", postData)
      .subscribe((data) => {
        this.buildingSearchList = data.list;
        this.isLoading = false;
      });
  }

  // 选中表格单列
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds = []; //已选中单列id
  refreshStatus(): void {
    let listOfData = this.historySpecimenList;
    this.isAllDisplayDataChecked = listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }
  // 整行操作
  selectedListData(data) {
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.historySpecimenList.forEach((item) => {
      this.mapOfCheckedId[item.id] = value;
    });
    this.refreshStatus();
  }
  // 关闭弹窗
  hideModal() {
    this.closeModelHs.emit(JSON.stringify({ show: false }));//emits(向上弹射)事件
  }
  // 获取列表数据
  getList(idx?) {
    if (idx) {
      this.historySpecimenPageIndex = 1;
    }
    let postData = {
      idx: this.historySpecimenPageIndex - 1,
      sum: this.historySpecimenPageSize,
      department: {
        dept: this.searchDto.dept || undefined,
        type: this.searchDto.deptTypeId ? { id: this.searchDto.deptTypeId } : undefined,
        buildIds: this.searchDto.buildId ? this.searchDto.buildId.toString() : undefined,
        cascadeHosId: this.currentHospital.id,
        bussType: 'inspection',
        noBuilding: '查询无楼栋科室',
      }
    }
    this.hsLoading = true;
    this.mainService.getFetchDataList("data", "department", postData).subscribe(data => {
      this.hsLoading = false;
      this.historySpecimenList = data.list || [];
      this.historySpecimenListLength = data.totalNum || 0;
    })
  }
  // 添加表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitForm(): void {
    console.log(this.checkedDepIds);
    if(this.checkedDepIds.length === 0){
      this.message.warning('请选择科室');
      return;
    }
    this.confirmModelHs.emit(this.checkedDepIds);//emits(向上弹射)事件
  }
}


