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-distribution-search-more',
  templateUrl: './distribution-search-more.component.html',
  styleUrls: ['./distribution-search-more.component.less']
})
export class DistributionSearchMoreComponent 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;
	@Input() going: boolean = false;
  validateForm: FormGroup;//表单
  searchTimerSubject = new Subject();
  constructor(
    private fb: FormBuilder,
    private tool: ToolService,
    private mainService: MainService,
  ) { }
	
	minuteClose:any;
	specialList:any = [
		{name:'是',id:1},
		{name:'否',id:0}
	]
	overtimeList:any = [
		{name:'是',id:1},
		{name:'否',id:0}
	]
	abnormalList:any = [
		{name:'是',id:1},
		{name:'否',id:0}
	]
  ngOnInit() {
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
		console.log(4444,this.fieldConfig)
    this.initForm();
    this.getSourceList();
		this.getSourceDataList();
		this.getWorkHourEvaluateList();
		this.getTimeFrameList();
  }
  // 隐藏模态框
  hideModal() {
    this.cancelEvent.emit()
  }
  // 初始化form表单
  initForm() {
    this.groupList = this.fieldConfig.fields.groupDTO ? [this.fieldConfig.fields.groupDTO] : [];
    this.userList = this.fieldConfig.fields.userDTO ? [this.fieldConfig.fields.userDTO] : [];
    this.statisticsTypeList = this.fieldConfig.fields.statisticsTypeDTO ? [this.fieldConfig.fields.statisticsTypeDTO] : [];
    this.buildingList = this.fieldConfig.fields.buildingDTO ? [this.fieldConfig.fields.buildingDTO] : [];
    this.taskTypeList = this.fieldConfig.fields.taskTypeDTO ? [this.fieldConfig.fields.taskTypeDTO] : [];
    this.deptList = this.fieldConfig.fields.deptDTO ? [this.fieldConfig.fields.deptDTO] : [];
		this.sourceList = this.fieldConfig.fields.sourceDTO ? [this.fieldConfig.fields.sourceDTO] : [];
		this.specialList = [{name:'是',id:1},{name:'否',id:0}];
		this.overtimeList = [{name:'是',id:1},{name:'否',id:0}];
		this.abnormalList = [{name:'是',id:1},{name:'否',id:0}];
		this.evaluateList = this.fieldConfig.fields.evaluateDTO ? [this.fieldConfig.fields.evaluateDTO] : [];
		this.executeUserList =  this.fieldConfig.fields.executeUserDTO ? [this.fieldConfig.fields.executeUserDTO] : [];
		this.timeFrameList = this.fieldConfig.fields.timeFrameDTO ? [this.fieldConfig.fields.timeFrameDTO] : [];
		
		this.validateForm = this.fb.group({
      groupId: [this.fieldConfig.fields.groupId || null],
      userId: [this.fieldConfig.fields.userId === undefined ? null : this.fieldConfig.fields.userId],
      statisticsTypeId: [this.fieldConfig.fields.statisticsTypeId || null],
      buildingId: [this.fieldConfig.fields.buildingId || null],
      taskTypeId: [this.fieldConfig.fields.taskTypeDTO ? this.fieldConfig.fields.taskTypeDTO.id  : null],
      deptId: [this.fieldConfig.fields.deptDTO ? this.fieldConfig.fields.deptDTO.id  : null],
			sourceId: [this.fieldConfig.fields.sourceId || null],
			minuteClose: [this.fieldConfig.fields.minuteClose || null],
			specialId: [this.fieldConfig.fields.specialDTO ? this.fieldConfig.fields.specialDTO.id  : null],
			overtimeId: [this.fieldConfig.fields.overtimeDTO ? this.fieldConfig.fields.overtimeDTO.id  : null],
			abnormalId: [this.fieldConfig.fields.abnormalDTO ? this.fieldConfig.fields.abnormalDTO.id  : null],
			evaluateId: [this.fieldConfig.fields.evaluateId || null],
			executeUserId: [this.fieldConfig.fields.executeUserId || null],
			codeNum: [this.fieldConfig.fields.codeNum || null],
			timeFrameId: [this.fieldConfig.fields.timeFrameDTO ? this.fieldConfig.fields.timeFrameDTO.id  : null],
		});
		
		
		if(this.going && this.fieldConfig.fields.taskTypeId){
			this.getTaskTypeList();
		}
		
		if(this.going && this.fieldConfig.fields.deptId){
			this.getRepairDeptList();
		}
		
		if(this.going && this.fieldConfig.fields.sourceId){
			this.getSourceList();
		}
		
		if(this.going && this.fieldConfig.fields.evaluateId){
			this.getWorkHourEvaluateList();
		}
		
		if(this.going && this.fieldConfig.fields.executeUserId){
			this.getExecuteUserList();
		}
		
		if(this.going && this.fieldConfig.fields.timeFrameId){
			this.getTimeFrameList();
		}
		
  }
  // 表单提交
  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.group){
      fields.groupId = this.validateForm.value.groupId;
      fields.groupDTO = this.groupList.find(item => item.id == this.validateForm.value.groupId);
    }

    if(this.fieldConfig.config.groupAndUser){
      fields.groupId = this.validateForm.value.groupId;
      fields.groupDTO = this.groupList.find(item => item.id == this.validateForm.value.groupId);
      fields.userId = this.validateForm.value.userId;
      fields.userDTO = this.userList.find(item => item.id == this.validateForm.value.userId);
    }

    if(this.fieldConfig.config.statisticsType){
      fields.statisticsTypeId = this.validateForm.value.statisticsTypeId;
      fields.statisticsTypeDTO = this.statisticsTypeList.find(item => item.id == this.validateForm.value.statisticsTypeId);
    }
    if(this.fieldConfig.config.building){
      fields.buildingId = this.validateForm.value.buildingId;
      fields.buildingDTO = this.buildingList.find(item => item.id == this.validateForm.value.buildingId);
    }
    if(this.fieldConfig.config.taskType){
      fields.taskTypeId = this.validateForm.value.taskTypeId;
      fields.taskTypeDTO = this.taskTypeList.find(item => item.id == this.validateForm.value.taskTypeId);
    }
    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.source){
		  fields.sourceId = this.validateForm.value.sourceId;
		  fields.sourceDTO = this.sourceList.find(item => item.name == this.validateForm.value.sourceId);
		}
		if(this.fieldConfig.config.minute){
		  fields.minuteClose = this.validateForm.value.minuteClose;
		  fields.minuteDTO = this.validateForm.value.minuteClose;
		}
		if(this.fieldConfig.config.special){
		  fields.specialId = this.validateForm.value.specialId;
		  fields.specialDTO = this.specialList.find(item => item.id == this.validateForm.value.specialId);
		}
		if(this.fieldConfig.config.overtime){
		  fields.overtimeId = this.validateForm.value.overtimeId;
		  fields.overtimeDTO = this.overtimeList.find(item => item.id == this.validateForm.value.overtimeId);
		}
		if(this.fieldConfig.config.abnormal){
		  fields.abnormalId = this.validateForm.value.abnormalId;
		  fields.abnormalDTO = this.abnormalList.find(item => item.id == this.validateForm.value.abnormalId);
		}
		if(this.fieldConfig.config.evaluate){
		  fields.evaluateId = this.validateForm.value.evaluateId;
		  fields.evaluateDTO = this.evaluateList.find(item => item.id == this.validateForm.value.evaluateId);
		}
		if(this.fieldConfig.config.executeUser){
		  fields.executeUserId = this.validateForm.value.executeUserId;
		  fields.executeUserDTO = this.executeUserList.find(item => item.id == this.validateForm.value.executeUserId);
		}
		if(this.fieldConfig.config.code){
			fields.codeNum = this.validateForm.value.codeNum;
			fields.codeNumDTO = this.validateForm.value.codeNum;
		}
		if(this.fieldConfig.config.timeFrame){
		  fields.timeFrameId = this.validateForm.value.timeFrameId;
		  fields.timeFrameDTO = this.timeFrameList.find(item => item.id == this.validateForm.value.timeFrameId);
		}
		
    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; // 设置标志
  }

  // =================分组===================

  // 分组搜索
  changeGroupInp(e) {
    this.searchTimer(this.getGroupList, e);
  }

  // 获取分组列表
  groupList:any[] = [];
  getGroupList(keyword?){
    let postData: any = {
      idx: 0,
      sum: 20,
      group2: {
        statisticalHosId: this.getHosId,
        groupName: keyword,
        type: 1,
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "group2", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
        this.groupList = result.list || [];
      }else{
        this.groupList = [];
      }
    });
  }
  openChangeGroup(flag){
    flag && this.setIsSelecting(false);
    flag && this.getGroupList();
  }

  changeGroup(id){
    this.setIsSelecting(true);
    // this.userList = [];
    // this.validateForm.controls.userId.setValue(null);
    this.getUserList();
  }

  // =================人员===================

  // 人员搜索
  changeUserInp(e) {
    this.searchTimer(this.getUserList, e);
  }

  // 获取人员列表
  userList:any[] = [];
  getUserList(keyword = ''){
    // if(!this.validateForm.value.groupId){
    //   this.isLoading = false;
    //   this.userList = [];
    //   return;
    // }
    let postData: any = {
      idx: 0,
      sum: 20,
      user: {
        name: keyword,
        simpleQuery: true,
				statisticalHosId: this.getHosId,
        // groupdata: { id: this.validateForm.value.groupId },
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "user", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
				if(!result.list.find(i=> i.id == -1)){
					result.list.push({
						name:'未知',
						id:-1
					})
				}
        this.userList = result.list || [];
      }else{
        this.userList = [];
      }
    });
  }
  openChangeUser(flag){
    flag && this.setIsSelecting(false);
    flag && this.getUserList();
  }

  // =================统计分类===================

  // 获取统计分类列表
  statisticsTypeList:any[] = [];
  getSourceList(){
    this.mainService.getDictionary("list", "statistics_date_type").subscribe(result => {
      this.statisticsTypeList = result;
    });
  }

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

  // 楼栋搜索
  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();
  }

  // =================任务类型===================

  // 任务类型搜索
  changeTaskTypeInp(e) {
    this.searchTimer(this.getTaskTypeList, e);
  }

  // 获取任务类型列表
  taskTypeList:any[] = [];
  getTaskTypeList(keyword?){
    let postData: any = {
      idx: 0,
      sum: 20,
      taskType: {
        simpleQuery: true,
        taskName: keyword,
        statisticalHosId: this.getHosId,
      },
    };
    this.isLoading = true;
    this.mainService.getFetchDataList("simple/data", "taskType", postData).subscribe(result => {
      this.isLoading = false;
      if(result.status == 200){
        this.taskTypeList = result.list || [];
      }else{
        this.taskTypeList = [];
      }
    });
  }
  openChangeTaskType(flag){
    flag && this.setIsSelecting(false);
    flag && this.getTaskTypeList();
  }

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

  // 科室搜索
  changeRepairDeptInp(e) {
    this.searchTimer(this.getRepairDeptList, e);
  }

  // 获取科室列表
  deptList:any[] = [];
  getRepairDeptList(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 = [];
      }
    });
  }
  openChangeRepairDept(flag){
    flag && this.setIsSelecting(false);
    flag && this.getRepairDeptList();
  }
	
	// =================来源===================
	
	// 获取来源列表
	sourceList:any[] = [];
	getSourceDataList(keyword?){
		this.sourceList = [
			{
				sourceId:1,
				name:"服务台"
			},
			{
				sourceId:2,
				name:"护士端"
			},
			{
				sourceId:3,
				name:"系统自动"
			},
			{
				sourceId:4,
				name:"微信端"
			},
		]
	}
	
	// =================评价===================
	
	// 获取评价列表 
	evaluateList:any[] = [];
	getWorkHourEvaluateList(){
		this.isLoading = true;
		this.mainService
		  .getDictionary("list", "workorderEvaluation")
		  .subscribe((data) => {
		    this.isLoading = false;
		    this.evaluateList = data;
		  });
	}
	
	// =================执行人===================
	
	// 执行人搜索
	changeExecuteUserInp(e) {
	  this.searchTimer(this.getExecuteUserList, e);
	}
	
	// 获取执行人列表
	executeUserList:any[] = [];
	getExecuteUserList(keyword?){
	  let postData = {
	    user: {
	      name: keyword,
	      hospital: { id: this.getHosId },
	      usertype: { id: 106 }, //配送人员
	    },
	    idx: 0,
	    sum: 20,
	  };
	  this.isLoading = true;
	  this.mainService
	    .getFetchDataList("data", "user", postData)
	    .subscribe((data) => {
				this.isLoading = false;
				if(data.status == 200){
				  this.executeUserList = data.list || [];
				}else{
				  this.executeUserList = [];
				}
	    });
	}
	openChangeExecuteUser(flag){
	  flag && this.setIsSelecting(false);
	  flag && this.getExecuteUserList();
	}
	
	// =================时段===================
	
	// 获取时段列表
	timeFrameList:any[] = [];
	getTimeFrameList(){
		this.timeFrameList = [];
	  for(let i=0; i<24; i++){
			this.timeFrameList.push({
				name: i < 10 ? '0'+i.toString() : i.toString(),
				id: i < 10 ? '0'+i.toString() : i.toString(),
			})
		}
	}
}
