import { Component, OnInit, OnDestroy } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from 'ng-zorro-antd/message';
import { format, addDays, addHours } from 'date-fns';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import cloneDeep from 'lodash-es/cloneDeep'
@Component({
  selector: "app-incident-management",
  templateUrl: "./incident-management.component.html",
  styleUrls: ["./incident-management.component.less"],
})
export class IncidentManagementComponent implements OnInit, OnDestroy {
  constructor(
    public route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService,
    private message: NzMessageService,
    private fb: FormBuilder,
  ) {}
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息
  listOfData: any[] = []; //表格数据
  coopId: string; //表格中执行操作的id
  hospital: string; //选中院区
  alldepart: any = []; //当前院区所属科室
  worker: number; //选择执行配送人员
  handleUserList: any = []; //处理人列表
  acceptUserList: any = []; //受理人列表
  gdState: number; //选择工单状态
  gdStates: any; //工单状态列表
  overdueStates: any; //逾期查询列表
  sourceList: any; //报修来源列表
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态

  tabs:any[] = [
    // {key: 'all', value: '全部故障', num: 0, isRed: false},
    {key: 'todo', value: '待我接单', num: 0, isRed: true},
    {key: 'doing', value: '待我处理', num: 0, isRed: true},
    // {key: 'reassign', value: '重新指派', num: 0, isRed: false},
    // {key: 'callback', value: '待我回访', num: 0, isRed: false},
    {key: 'resolve', value: '由我解决', num: 0, isRed: false},
    {key: 'owns', value: '与我关联', num: 0, isRed: false},
    {key: 'storage', value: '暂存', num: 0, isRed: false},
    // {key: 'badEvaluate', value: '异常评价', num: 0, isRed: false},
  ]

  searchDTO: any = {};
	searchParentDeptSubject = new Subject();
  searchTimerSubject = new Subject();
  debounceSubject = new Subject(); //防抖
	maintainDept:any = []; //维修科室
	maintainGroup:any = []; //维修组
	hosIds:any; //当前院区
  // 初始化增删改按钮
  coopBtns: any = {};
  // 选择tab
  queryTask:string = 'todo';//默认待我接单
  changeTab(key){
    this.queryTask = key;
		let itemDept = this.maintainDept.find(i=>i.id == this.hosIds)
		let list = this.tool.getUserInfoPermission().dutyGroupList || []
		if(itemDept){
			this.searchDTO.maintainDepartment = itemDept.id
			if(this.queryTask!='todo' && this.queryTask!='doing' && this.queryTask!='storage'){
				let arr = list.filter(i=>i.hospital.id == itemDept.id)
				if(arr){
					this.maintainGroup = arr
				}else{
					this.maintainGroup = list
				}
			}else{
				this.maintainGroup = list
			}

		}
		this.getDeparts();
		this.getUsers('', 'handle');
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

  ngOnInit() {
		this.maintainDept = this.tool.getUserInfoPermission().dutyList
		this.hosIds = this.tool.getCurrentHospital().id
		if(this.coopBtns.strideLook){
			this.defaDept()
		}
    this.initSearchForm();
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((v: any) => {
		  this.getAllParentdepart(v).subscribe((result) => {
		    this.isLoading = false;
		    if (result.status == 200) {
		      this.allParentdepart = result.list;
		    }
		  });
		});
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1], v[2]);
    });
    this.debounceSubject.pipe(debounceTime(500)).subscribe((v:boolean) => {
      this.getList(v);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initTabs();
    this.getGdStates();
    this.getOverdueStates();
    this.getSourceList();
    this.getIncidentCategoryList();
    this.loading1 = true;
    this.debounceSubject.next(true);
    this.autoRefresh();
		this.getRepairsUser();
  }

  ngOnDestroy(){
    this.cancelRefresh();
  }

  // 定时器自动刷新页面
  timer = null;
  autoRefresh(){
    this.cancelRefresh();
    this.timer = setInterval(() => {
      this.getList();
    }, 60000)
  }

  // 清除定时器
  cancelRefresh(){
    clearInterval(this.timer);
  }

  // 初始化tab
  initTabs(){
    if (this.coopBtns.all) {
        this.tabs.splice(0, 0 , {key: 'all', value: '全部故障', num: 0, isRed: false});
    }
    if (this.coopBtns.callback) {
        let index = this.tabs.findIndex(v => v.key == 'resolve');
        this.tabs.splice(index, 0 , {key: 'callback', value: '待我回访', num: 0, isRed: false});
    }
    if (this.coopBtns.reassign) {
        let index = this.tabs.findIndex(v => v.key == 'doing');
        this.tabs.splice(index + 1, 0 , {key: 'reassign', value: '重新指派', num: 0, isRed: false});
    }
    // if (this.coopBtns.badEvaluate) {
    //     this.tabs.push({key: 'badEvaluate', value: '异常评价', num: 0, isRed: false});
    // }
  }

	defaDept(){
		let itemDept = this.maintainDept.find(i=>i.id == this.hosIds)
		if(itemDept){
			this.searchDTO.maintainDepartment = itemDept.id
		}
		this.getDeparts();
		this.getUsers('', 'handle');
		this.getUsers('', 'acceptUser');
	}

	// 选择维修科室
	deptChange(e){
		this.searchDTO.maintainGroup = null
		let list = this.tool.getUserInfoPermission().dutyGroupList || []
		let arr = list.filter(i=>i.hospital.id == e)
		if(arr){
			this.maintainGroup = arr
		}else{
			this.maintainGroup = list
		}
		this.searchDTO.department = null
		this.searchDTO.todoingUser = null
		this.getDeparts();
		this.getUsers('', 'handle');
	}

  // 搜索
  search() {
    this.loading1 = true;
    this.debounceSubject.next(true);
  }
  // 重置
  reset() {
    this.searchDTO = {};
		if(this.coopBtns.strideLook){
			this.defaDept()
		}
    this.initSearchForm();
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

  // 获取故障现象
  incidentCategoryList:any[] = [];
  getIncidentCategoryList(){
    let { hospital, type } = this.tool.getHospitalOrDuty();
    if(type === 'hospital' || type === 'department'){
      this.incidentCategoryList = [];
      return;
    };
    let postData = {
      hasThird: 'true',//只差有三级的故障现象列表
      category: {
        dutyIds: type === 'duty' ? hospital.id.toString()  : undefined,
      },
    };
    this.mainService.incidentPost("listIncidentCategory", postData).subscribe(res => {
      let incidentCategoryList = res.data || [];
      incidentCategoryList = incidentCategoryList.map(v => ({...v, parentId: v.parent ? v.parent.id : undefined, title: v.category, key: v.id}));
      this.incidentCategoryList = this.tool.tranListToTreeDataLeaf(incidentCategoryList, undefined, "parentId");
      console.log(this.incidentCategoryList);
    })
  }

  // 获取处理人
  getUsers(e?, type?) {
    let that = this;
    let postData = {
      user: {
        name: e || "",
        hospital: { id: this.searchDTO.maintainDepartment?this.searchDTO.maintainDepartment:that.tool.getCurrentHospital().id },
        engineer: 1,
        simpleQuery: true,
      },
      idx: 0,
      sum: 20,
    };
    that.isLoading = true;
    that.mainService
      .getFetchDataList("data", "user", postData)
      .subscribe((data) => {
        that.isLoading = false;
        if(type === 'handle'){
          that.handleUserList = data.list;
        }else if(type === 'acceptUser'){
          that.acceptUserList = data.list;
        }
      });
  }
	
	// 获取报修人
	repairsUserList:any = [];
	getRepairsUser(e?) {
	  let that = this;
	  let postData = {
	    user: {
	      name: e || "",
	      hospital: { id: that.tool.getCurrentHospital().id },
	    },
	    idx: 0,
	    sum: 20,
	  };
	  that.isLoading = true;
	  that.mainService
	    .getFetchDataList("data", "user", postData)
	    .subscribe((data) => {
	      that.isLoading = false;
	      that.repairsUserList = data.list;
	    });
	}
	
  onCalendarChangeDate(dateArr){
    console.log(dateArr)
    if(dateArr.length == 2){
      let dateStart = new Date(dateArr[0]);
      let dateEnd = new Date(dateArr[1]);
      dateStart.setHours(0,0,0);
      dateEnd.setHours(23,59,59);
      this.searchDTO.dateRange = [dateStart,dateEnd];
    }
  }

  // 优先级颜色
  priorityColor(priorityId) {
    // 极低|低
    if(priorityId == 1 || priorityId == 2){
      return '';
    } else if(priorityId == 3){
      return 'yellow';
    } else if(priorityId == 4 || priorityId == 5){
      return 'red';
    }
  }
  // 处理人+协同人
  transferSynergetic(incidentData){
    let str = incidentData.groupORHandlerUser || "";
    if(incidentData.synergetic && incidentData.synergetic.length){
        str += '，' + incidentData.synergetic.map(v => v.name).join('，');
    }
    return str;
  }

  // 延期记录
  transferHandlerLog = function (currentLog) {
    if(!currentLog){
        return '无';
    }
    currentLog = cloneDeep(currentLog);
    if(currentLog.extra1DTO && currentLog.extra2 && currentLog.startTime){
        if(currentLog.extra2==0.5){
          currentLog.extra2 = 4;
          return currentLog.extra1DTO.name+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "MM月dd日")+"<br>"+ format(addHours(currentLog.startTime, +currentLog.extra2), "HH时mm分前完成");
        }else{
          return currentLog.extra1DTO.name+"<br>"+ format(addDays(currentLog.startTime, +currentLog.extra2), "MM月dd日前完成");
        }
    }else{
        return '无';
    }
  }

  // 判断当前人是否在工单组里
  isInGroup(data){
    return this.tool.getCurrentGroupList().some(v => data.currentLog && v.id == data.currentLog.groupId);
  }

  // 是否显示接单按钮
  computedReceive(data){
    let inUser = data.currentLog && data.currentLog.workerId == this.tool.getCurrentUserId();
    let inGroup = false;
    let groupList = this.tool.getCurrentGroupList();
    groupList.forEach(item => {
        if(data.currentLog){
            if (item.id == data.currentLog.groupId) {
                inGroup = true;
            }
        }
    })
    return data.state.value === 'pending' && (inUser || inGroup) && this.coopBtns.receive && data.deleteFlag !== 1;
  }

  // 是否显示处理按钮
  computedHandle(data){
    return this.coopBtns.handle && data.state.value === 'handler' && data.handlingPersonnelUser && data.handlingPersonnelUser.id == this.tool.getCurrentUserId() && data.deleteFlag !== 1;
  }

  // 是否显示换人处理按钮
  computedSubstitution(data){
    return (data.state.value === 'pending' || data.state.value === 'handler' || (data.state.value === 'reassign' && this.coopBtns.assign)) && data.deleteFlag !== 1;
  }

  // 是否显示延期处理按钮
  computedPostpone(data){
    return data.state.value == 'handler' && data.handlingPersonnelUser && data.handlingPersonnelUser.id == this.tool.getCurrentUserId() && data.deleteFlag !== 1;
  }

  // 是否显示设置责任部门按钮
  computedSetDuty(data){
    return this.coopBtns.settings && (data.state.value == 'resolved' || data.state.value == 'close') && data.deleteFlag !== 1;
  }

  // 是否显示回访按钮
  computedVisit(data){
    return this.coopBtns.visit && data.state.value == 'close' && data.deleteFlag !== 1;
  }

  // 是否显示编辑按钮
  computedEdit(data){
    return (data.state.value === 'pending' || data.state.value === 'reassign' || data.state.value === 'handler' || data.state.value === 'close') && this.coopBtns.edit && data.deleteFlag !== 1;
  }

  // 表格数据
  loading1 = false;
  getList(isInit = false) {
    let postData: any = {
      idx: isInit ? 0 : (this.pageIndex - 1),
      sum: this.pageSize,
      incident: {
        assignee: this.tool.getCurrentUserId(),
        acceptDate: (this.searchDTO.dateRange && this.searchDTO.dateRange[0]) ? format(this.searchDTO.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        acceptDateEnd: (this.searchDTO.dateRange && this.searchDTO.dateRange[1]) ? format(this.searchDTO.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
        incidentsign: this.searchDTO.incidentsign,
        department: this.searchDTO.department ? { id: this.searchDTO.department } : undefined,
        statusId: this.searchDTO.statusId || undefined,
				wxdegree:{
					id:this.searchDTO.score || undefined,
				},
        todoingUser: this.searchDTO.todoingUser ? { id: this.searchDTO.todoingUser } : undefined,
        levelCategory: this.validateSearchForm.value.levelCategory ? { id: this.validateSearchForm.value.levelCategory } : undefined,
        acceptUser: this.validateSearchForm.value.acceptUser ? { id: this.validateSearchForm.value.acceptUser } : undefined,
        selectType: this.validateSearchForm.value.selectType || undefined,
        source: this.validateSearchForm.value.sourceValue ? { value: this.validateSearchForm.value.sourceValue } : undefined,
        deleteFlag: this.validateSearchForm.value.deleteFlag,
				busiParent: this.validateSearchForm.value.busiParent,
				requester: this.validateSearchForm.value.repairsUser ? { id: this.validateSearchForm.value.repairsUser } : undefined,
				candidateGroupId: null,
				incomingPhone: this.validateSearchForm.value.incomingPhone || undefined
      },
    };

    if(this.queryTask === 'all' || this.queryTask === 'callback' || this.queryTask === 'badEvaluate'){
      let { hospital, type } = this.tool.getHospitalOrDuty();
      if(type === 'duty'){
        // 当前的所属责任部门
        postData.incident.duty = hospital;
      }else{
        // 当前的所属院区
        postData.incident.hosId = hospital.id;
      }
    }else{
        delete postData.incident.duty;
        delete postData.incident.hosId;
    }

		if(this.queryTask!='todo' && this.queryTask!='doing' && this.queryTask!='storage'){
			if(this.searchDTO.maintainDepartment){
				let itemDept = this.maintainDept.find(i=>i.id == this.searchDTO.maintainDepartment)
				postData.incident.duty = itemDept;
				delete postData.incident.hosId;
			}
		}
		if(this.queryTask!='todo' && this.queryTask!='owns' && this.queryTask!='storage' && this.queryTask!='doing' && this.queryTask!='reassign'){
			postData.incident.candidateGroupId = this.searchDTO.maintainGroup
		}else{
			delete postData.incident.candidateGroupId;
		}

    postData.incident.queryTask = this.queryTask;

    if(this.queryTask === 'todo' || this.queryTask === 'owns'){
      postData.incident.candidateGroups = this.tool.getCurrentGroupList().map(v => v.id).toString();
    }else{
      delete postData.incident.candidateGroups;
    }

    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "incident", postData)
      .subscribe((result) => {
        this.loading1 = false;
        let list = result.list || [];
        list.forEach((item) => {
          item.endDeptsName = item.endDepts ? item.endDepts.map(v => v.dept).toString() : '';
          item.computedEditFlag = this.computedEdit(item);
          item.computedVisitFlag = this.computedVisit(item);
          item.computedReceiveFlag = this.computedReceive(item);
          item.computedHandleFlag = this.computedHandle(item);
          item.computedSubstitutionFlag = this.computedSubstitution(item);
          item.computedPostponeFlag = this.computedPostpone(item);
          item.computedSetDutyFlag = this.computedSetDuty(item);
        });
        this.listOfData = list;
        this.listLength = result.totalNum;
      });

    // 获取数量
    this.getCount(postData.incident);
  }

  // 调用接口-查数量
  getCount = function (incident = {}){
    let postData = {
        incidentList: [],
    }
    this.tabs.forEach(v => {
        postData.incidentList.push({...incident, ...{queryTask: v.key}});
    })
    postData.incidentList.forEach(incident => {
        // 请求参数调整
        if(!incident){
            incident = {};
        }
        if(incident.queryTask === 'all' || incident.queryTask === 'callback' || incident.queryTask === 'badEvaluate'){
          let { hospital, type } = this.tool.getHospitalOrDuty();
          if(type === 'duty'){
            // 当前的所属责任部门
            incident.duty = hospital;
          }else{
            // 当前的所属院区
            incident.hosId = hospital.id;
          }
        }else{
            delete incident.duty;
            delete incident.hosId;
        }

				if(incident.queryTask!='todo' && incident.queryTask!='doing' && incident.queryTask!='storage'){
					if(this.searchDTO.maintainDepartment){
						let itemDept = this.maintainDept.find(i=>i.id == this.searchDTO.maintainDepartment)
						incident.duty = itemDept;
						delete incident.hosId;
					}
				}

        incident.assignee = this.tool.getCurrentUserId();

        if(incident.queryTask === 'todo' || incident.queryTask === 'owns'){
          incident.candidateGroups = this.tool.getCurrentGroupList().map(v => v.id).toString();
        }else{
          delete incident.candidateGroups;
        }
				if(incident.queryTask!='todo' && incident.queryTask!='owns' && incident.queryTask!='storage' && incident.queryTask!='doing' && incident.queryTask!='reassign'){
					incident.candidateGroupId = this.searchDTO.maintainGroup
				}else{
					delete incident.candidateGroupId;
				}
    })
    this.mainService
      .getCount(postData)
      .subscribe((result) => {
        let myData = result.data || {};
        this.tabs.forEach(v => {
            v.num = myData[v.key];
        })
      });
}

  // 获取所有科室
  getDeparts(dept?) {
    let data = {
      department: {
        searchType: 1,// 简单查询
        cascadeHosId: this.searchDTO.maintainDepartment?this.searchDTO.maintainDepartment:this.tool.getCurrentHospital().id,
        dept: dept,
      },
      idx: 0,
      sum: 20,
    };
    this.isLoading = true;
    this.mainService
      .getFetchDataList("data", "department", data)
      .subscribe((data) => {
        this.alldepart = data.list;
        this.isLoading = false;
      });
  }

  // 获取工单状态
	scoreData:any;
  getGdStates() {
    this.mainService.getDictionary("list", "incident_status").subscribe((data) => {
      this.gdStates = data || [];
    });
		this.mainService.getDictionary("list", "incident_degree").subscribe((data) => {
		  this.scoreData = data || [];
		});
		
  }

  // 获取逾期查询
  getOverdueStates() {
    this.mainService.getDictionary("list", "overdue_state").subscribe((data) => {
      this.overdueStates = data || [];
    });
  }

  // 获取报修来源
  getSourceList() {
    this.mainService.getDictionary("list", "incident_source").subscribe((data) => {
      this.sourceList = data || [];
    });
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.loading1 = true;
    this.debounceSubject.next(false);
  }

  // 设置责任部门-弹窗
  setdutyModalShow = false; //弹窗开关
  setDuty(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.setdutyModalShow = true;
  }
  // 关闭弹窗
  closeSetdutyModelOrder(e) {
    this.setdutyModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmSetdutyModelOrder(e){
    console.log(e);
    this.setdutyModalShow = false;
    this.getList(true);
  }

  // 编辑-弹窗
  editModalShow = false; //弹窗开关
  edit(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.editModalShow = true;
  }
  // 关闭弹窗
  closeEditModelOrder(e) {
    this.editModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmEditModelOrder(e){
    console.log(e);
    this.editModalShow = false;
    this.getList(true);
  }

  // 回访-弹窗
  visitModalShow = false; //弹窗开关
  visit(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.visitModalShow = true;
  }
  // 关闭弹窗
  closeVisitModelOrder(e) {
    this.visitModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmVisitModelOrder(e){
    console.log(e);
    this.visitModalShow = false;
    this.getList(true);
  }

  // 详情-弹窗
  detailModalShow = false; //弹窗开关
  detail(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.detailModalShow = true;
  }
  // 关闭弹窗
  closeDetailModelOrder(e) {
    this.detailModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmDetailModelOrder(e){
    console.log(e);
    this.detailModalShow = false;
    this.getList(true);
  }

  // 查看巡检
  viewInspectionDetail(e, id) {
    e.stopPropagation();
    this.router.navigateByUrl("/main/incidentManagement/inspectionExecuteDetail/" + id);
  }

  // 延期处理-弹窗
  postponeModalShow = false; //弹窗开关
  postpone(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.postponeModalShow = true;
  }
  // 关闭弹窗
  closePostponeModelOrder(e) {
    this.postponeModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmPostponeModelOrder(e){
    console.log(e);
    this.postponeModalShow = false;
    this.getList(true);
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    e,
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    e.stopPropagation();
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "incident", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }else if (this.confirmDelType === "receive") {
      //接单
      this.mainService
        .flowPost("incident/task/receive", { incident: this.coopData })
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.state == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

  // 导出
  loading2 = false;
  export() {
    let postData: any = {
      idx: 0,
      sum: 99999,
      incident: {
        assignee: this.tool.getCurrentUserId(),
        acceptDate: (this.searchDTO.dateRange && this.searchDTO.dateRange[0]) ? format(this.searchDTO.dateRange[0], 'yyyy-MM-dd HH:mm:ss') : undefined,
        acceptDateEnd: (this.searchDTO.dateRange && this.searchDTO.dateRange[1]) ? format(this.searchDTO.dateRange[1], 'yyyy-MM-dd HH:mm:ss') : undefined,
        incidentsign: this.searchDTO.incidentsign,
        department: this.searchDTO.department ? { id: this.searchDTO.department } : undefined,
        statusId: this.searchDTO.statusId || undefined,
				wxdegree:{
					id:this.searchDTO.score || undefined,
				},
        todoingUser: this.searchDTO.todoingUser ? { id: this.searchDTO.todoingUser } : undefined,
        levelCategory: this.validateSearchForm.value.levelCategory ? { id: this.validateSearchForm.value.levelCategory } : undefined,
        acceptUser: this.validateSearchForm.value.acceptUser ? { id: this.validateSearchForm.value.acceptUser } : undefined,
        selectType: this.validateSearchForm.value.selectType || undefined,
        source: this.validateSearchForm.value.sourceValue ? { value: this.validateSearchForm.value.sourceValue } : undefined,
        deleteFlag: this.validateSearchForm.value.deleteFlag,
				busiParent: this.validateSearchForm.value.busiParent,
				requester: this.validateSearchForm.value.repairsUser ? { id: this.validateSearchForm.value.repairsUser } : undefined,
				candidateGroupId: undefined,
				incomingPhone: this.validateSearchForm.value.incomingPhone || undefined
      },
    };

    if(this.queryTask === 'all' || this.queryTask === 'callback' || this.queryTask === 'badEvaluate'){
      let { hospital, type } = this.tool.getHospitalOrDuty();
      if(type === 'duty'){
        // 当前的所属责任部门
        postData.incident.duty = hospital;
      }else{
        // 当前的所属院区
        postData.incident.hosId = hospital.id;
      }
    }else{
        delete postData.incident.duty;
        delete postData.incident.hosId;
    }

		if(this.queryTask!='todo' && this.queryTask!='doing' && this.queryTask!='storage'){
			if(this.searchDTO.maintainDepartment){
				let itemDept = this.maintainDept.find(i=>i.id == this.searchDTO.maintainDepartment)
				postData.incident.duty = itemDept;
				delete postData.incident.hosId;
			}
		}

		if(this.queryTask!='todo' && this.queryTask!='owns' && this.queryTask!='storage'){
			postData.incident.candidateGroupId = this.searchDTO.maintainGroup
		}else{
			delete postData.incident.candidateGroupId;
		}

    postData.incident.queryTask = this.queryTask;

    if(this.queryTask === 'todo' || this.queryTask === 'owns'){
      postData.incident.candidateGroups = this.tool.getCurrentGroupList().map(v => v.id).toString();
    }else{
      delete postData.incident.candidateGroups;
    }
    this.loading2 = true;
    this.mainService.downDataModel(postData).subscribe(
      (data) => {
        this.loading2 = false;
        this.showPromptModal("导出", true, "");
        var file = new Blob([data], {
          type: "application/vnd.ms-excel",
        });
        //trick to download store a file having its URL
        var fileURL = URL.createObjectURL(file);
        var a = document.createElement("a");
        a.href = fileURL;
        a.target = "_blank";
        a.download = "故障工单.xls";
        document.body.appendChild(a);
        a.click();
      },
      (err) => {
        this.loading2 = false;
        this.showPromptModal("导出", false, "");
      }
    );
  }

  // 科室边输边搜节流阀
  isLoading = false;
  changeInp(e) {
    this.searchTimer(this.getDeparts, e);
  }

  // 人员边输边搜节流阀
  changeUser(e, type) {
    this.searchTimer(this.getUsers, e, type);
  }
	
	// 人员边输边搜节流阀
	changeRepairsUser(e, type) {
	  this.searchTimer(this.getRepairsUser, e, type);
	}
	
  // 边输入边搜索节流阀
  searchTimer(fun, e, type?) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e, type]);
  }
	
	changeDeptInp(e) {
	  this.isLoading = true;
	  this.searchParentDeptSubject.next(e);
	}
	
	//获取所有的父级科室列表
	getAllParentdepart(keyWord = "") {
	  let postData: any = {
	    idx: 0,
	    sum: 10,
	    department: {
	      hospital: { id: this.tool.getCurrentHospital().id },
	      keyWord: keyWord,
	    },
	  };
	  return this.mainService.getFetchDataList("data", "department", postData);
	}
	
	// 打开父级科室下拉框baba
	allParentdepart:any = [];
	openDeptSelect(flag) {
	  if (flag) {
	    this.isLoading = true;
	    this.getAllParentdepart().subscribe((result) => {
	      this.isLoading = false;
	      if (result.status == 200) {
	        this.allParentdepart = result.list;
	      }
	    });
	  }
	}
	
  // 详细搜索
  searchModal: boolean = false; //新增/编辑模态框
  modelName = ""; //模态框名称
  validateSearchForm: FormGroup; //新增/编辑表单
  coopData: any = {}; //当前操作列
  // 显示弹框
  showSearchModal() {
    this.modelName = "详细搜索";
		let item = this.repairsUserList.find(i=>i.id == this.validateSearchForm.value.repairsUser)
    if(!item && this.validateSearchForm.value.repairsUser){
			this.mainService
			  .getFetchData("data", "user", this.validateSearchForm.value.repairsUser)
			  .subscribe((result) => {
			    this.repairsUserList.push({
			    	id: result.data.id,
			    	name: result.data.name
			    })
			  });

		}
		this.searchModal = true;
  }
  //关闭新增/编辑弹框
  hideSearchModal() {
    this.searchModal = false;
  }

  // 详细搜索-提交
  submitSearchModal(){
    this.searchModal = false;
    this.getList(true);
  }

  // 初始化新增form表单
  initSearchForm() {
    this.validateSearchForm = this.fb.group({
      levelCategory: [null],
      acceptUser: [null],
      selectType: [null],
      deleteFlag: [0],
      sourceValue: [null],
			busiParent: [null],
			incomingPhone: [null],
			repairsUser: [null],
    });
  }

  // 详细搜索提交
  submitForm(): void {
    for (const i in this.validateSearchForm.controls) {
      this.validateSearchForm.controls[i].markAsDirty();
      this.validateSearchForm.controls[i].updateValueAndValidity();
    }
    if (this.validateSearchForm.invalid) {
      return;
    }

    console.log(this.validateSearchForm.value)
    this.loading1 = true;
    this.debounceSubject.next(true);
  }

  // 处理-弹窗
  handleModalShow = false; //弹窗开关
  handle(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.handleModalShow = true;
  }
  // 关闭弹窗
  closeHandleModelOrder(e) {
    this.handleModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmHandleModelOrder(e){
    console.log(e);
    this.handleModalShow = false;
    this.getList(true);
  }

  // 换人处理-弹窗
  substitutionModalShow = false; //弹窗开关
  substitution(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.substitutionModalShow = true;
  }
  // 关闭弹窗
  closeSubstitutionModelOrder(e) {
    this.substitutionModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmSubstitutionModelOrder(e){
    console.log(e);
    this.substitutionModalShow = false;
    this.getList(true);
  }
}
