import { TabService } from './../../services/tab.service';
import { debounceTime, filter } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Component, OnInit, HostListener, AfterViewInit, ViewChild, OnDestroy } from "@angular/core";
import { MainService } from 'src/app/services/main.service';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import cloneDeep from 'lodash-es/cloneDeep'
import { CustomChangeDateComponent } from '../../components/custom-change-date/custom-change-date.component';
@Component({
  selector: "app-incident-list",
  templateUrl: "./incident-list.component.html",
  styleUrls: ["./incident-list.component.less"],
})
export class IncidentListComponent implements OnInit, AfterViewInit, OnDestroy {
  @ViewChild('customChangeDate', { static: false }) customChangeDateComponent!: CustomChangeDateComponent;
  constructor(
    private mainService: MainService,
    private message: NzMessageService,
    public route: ActivatedRoute,
    private router: Router,
    private tabService: TabService,
  ) {}

  listOfData: any[] = []; //表格数据
  listOfDataEnd: any[] = []; //表格合计
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 0; //表格总数据量

  repairDeptId;//报修科室id

  searchTimerSubject = new Subject();
	
  ngOnInit() {
		// 数据下钻搜索
		this.getRouteQuery()
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
  }
	
	ngOnDestroy(){
		console.log(12122121)
		this.fieldConfig.fields = {}
		sessionStorage.removeItem('distributionData')
	}
	
  ngAfterViewInit(){
    this.initSessionData();
    this.onResize(0);
  }

  tableHeight:number = 0;
  @HostListener('window:resize')
  onResize(height): void {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - (document.querySelector('.searchDataWrap') as HTMLElement).offsetHeight - 64 - 36 - 48 - 8 - (document.querySelector('.ant-table-header') as HTMLElement).offsetHeight - height - this.getMoreFilter + 14;

    }, 0)
  }
	
	goingType:boolean = false;
	gdStateId:any = null;
	getRouteQuery(){
		let data = sessionStorage.getItem('distributionData')
		let query = null
		if(data){
			query = JSON.parse(data)
			console.log('query==========',query)
			setTimeout(_=>{
				// 统计分类
				if(query.statisticsTypeId){
					this.getStatisticsTypeList();
					this.statisticsTypeId = query.statisticsTypeId
				}else{
					this.statisticsTypeId = undefined
				}
				if(query.searchQuery){
					this.goingType = true
					this.fieldConfig.fields = query.searchQuery
				}else{
					this.goingType = false
					this.fieldConfig.fields = {}
				}
				if(!query.isGdId){
					this.gdStateId = '73,74'
				}else{
					this.gdStateId = undefined;
				}
				this.getQueryParams(query);
			},50)
		}else{
			this.gdStateId = undefined;
			setTimeout(_=>{
				this.getQueryParams('');
			},50)
		}
	}
	
  getQueryParams(query){
    let queryParams = this.tabService.getQueryParams();
		console.log(43434343,queryParams)
    if(queryParams.dateRange){
			console.log(555555)
      this.dateRange = queryParams.dateRange;
      this.customChangeDateComponent.initByDate(this.dateRange, queryParams.defRange);
		}else{
			this.tabService.clearQueryParams();
			console.log(666666)
			if(query){
				this.dateRange = [query.startDate, query.endDate];
				this.customChangeDateComponent.initByDate(this.dateRange, queryParams.defRange);
			}
		}
		setTimeout(_=>{
			this.search();
			this.onResize(37);
		},100)
  }

  get getMoreFilter(){
    let flag = this.fieldConfig.fields.groupDTO || this.fieldConfig.fields.userDTO || 
		this.fieldConfig.fields.category1DTO || this.fieldConfig.fields.category2DTO || 
		this.fieldConfig.fields.category3DTO || this.fieldConfig.fields.sourceDTO  || 
		this.fieldConfig.fields.buildingDTO || this.fieldConfig.fields.floorDTO || 
		this.fieldConfig.fields.companyDTO || this.fieldConfig.fields.repairDeptDTO;
    return flag ? 37 : 0;
  }

  // 初始化缓存数据
  queryType:any;
  hosId:any;
  dutyId:any;
  parentDutyId:any;
  initSessionData(){
    let newStatistics = JSON.parse(sessionStorage.getItem('newStatistics'));
    let queryType:any = newStatistics.queryType;
    let hosId:any = newStatistics.hospitalId;
    let dutyId:any = newStatistics.dutyId;

    queryType = queryType ? +queryType : undefined;
    hosId = hosId ? +hosId : undefined;
    dutyId = dutyId ? +dutyId : undefined;

    this.queryType = queryType;
    if(queryType == 1){
      this.hosId = undefined;
      this.dutyId = undefined;
      this.parentDutyId = undefined;
    }else if(queryType == 2){
      this.hosId = hosId;
      this.dutyId = undefined;
      this.parentDutyId = undefined;
    }else if(queryType == 3){
      this.hosId = undefined;
      this.dutyId = dutyId;
      this.parentDutyId = undefined;
    }else if(queryType == 4){
      this.hosId = undefined;
      this.dutyId = undefined;
      this.parentDutyId = dutyId;
    }
  }

  get getHosId(){
    return this.parentDutyId || this.dutyId || this.hosId;
  }

  // 表格数据
  loading1 = false;
	statisticsTypeId:any;//统计分类id
  getList(num?: number, field?: string, sort?: string) {
    if (num !== undefined) {
      this.pageIndex = num;
    }
    let postData:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      statisticsTypeId: this.statisticsTypeId || undefined,
      startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
      hosId: this.getHosId,
      deptId: this.fieldConfig.fields.deptId || undefined,
			groupId: this.fieldConfig.fields.userId ? undefined : (this.fieldConfig.fields.groupId || undefined),
			userId: this.fieldConfig.fields.userId || undefined,
			taskTypeId: this.fieldConfig.fields.taskTypeId || undefined,
			buildingId: this.fieldConfig.fields.buildingId || undefined,
			sourceId: this.fieldConfig.fields.sourceId || undefined,
			minutesClose: this.fieldConfig.fields.minuteClose || undefined,
			specialCloseFlag: this.fieldConfig.fields.specialId,
			// timeout: this.fieldConfig.fields.overtimeId,
			// abnormityType: this.fieldConfig.fields.abnormalId,
			workOrderEvaluationId: this.fieldConfig.fields.evaluateId || undefined,
			hour: this.fieldConfig.fields.timeFrameId != null ? this.fieldConfig.fields.timeFrameId : undefined,
			gdCode: this.fieldConfig.fields.codeNum || undefined,
			gdStateId: this.gdStateId
    };

    this.loading1 = true;
    this.mainService
      .postCustom("itsm/report", "workOrderList", postData)
      .subscribe((result) => {
        this.loading1 = false;
        this.listOfData = result.dataList;
        this.listLength = result.totalCount;
      });
  }

  // 列表排序
  sortCurrent:any = {};
  sortCurrentKey: string = "";
  sortCurrentValue: string | null = "";
  sort(e) {
    const { key, value } = e;
    this.sortCurrentKey = key;
    this.sortCurrentValue = value;
    this.getList(this.pageIndex, this.sortCurrentKey, this.sortCurrentValue);
  }

  // 搜索
  search() {
    this.getList(1, this.sortCurrentKey, this.sortCurrentValue);
  }

  // 日期选择
  dateRange: any = [];

  // 导出
  excelExportLoading:any = false;
  excelExport(){
    this.excelExportLoading = this.message.loading("导出中..", {
      nzDuration: 0,
    }).messageId;
    let postData:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      statisticsTypeId: this.statisticsTypeId || undefined,
      startDate: this.customChangeDateComponent.startDate || undefined,
      endDate: this.customChangeDateComponent.endDate || undefined,
      hosId: this.getHosId,
      deptId: this.fieldConfig.fields.deptId || undefined,
			groupId: this.fieldConfig.fields.userId ? undefined : (this.fieldConfig.fields.groupId || undefined),
			userId: this.fieldConfig.fields.userId || undefined,
			taskTypeId: this.fieldConfig.fields.taskTypeId || undefined,
			buildingId: this.fieldConfig.fields.buildingId || undefined,
    	sourceId: this.fieldConfig.fields.sourceId || undefined,
    	minutesClose: this.fieldConfig.fields.minuteClose || undefined,
    	specialCloseFlag: this.fieldConfig.fields.specialId,
    	// timeout: this.fieldConfig.fields.overtimeId,
    	// abnormityType: this.fieldConfig.fields.abnormalId,
    	workOrderEvaluationId: this.fieldConfig.fields.evaluateId || undefined,
    	hour: this.fieldConfig.fields.timeFrameId != null ? this.fieldConfig.fields.timeFrameId : undefined,
    	gdCode: this.fieldConfig.fields.codeNum || undefined,
			gdStateId: this.gdStateId
    };
    this.mainService
      .postExportCustom("itsm/export", "workOrderList", postData)
      .subscribe((data) => {
        this.message.remove(this.excelExportLoading);
        this.excelExportLoading = false;
        this.message.success('导出成功');
        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 = `${this.route.parent.routeConfig.data.title}.xls`;
        document.body.appendChild(a);
        a.click();
      },(err) => {
        this.message.remove(this.excelExportLoading);
        this.excelExportLoading = false;
        this.message.error('导出失败');
      });
  }
  // 重置
  reset(){
    this.sortCurrentKey = "";
		this.sortCurrentValue = "";
		this.sortCurrent = {};
    this.dateRange = []
    this.statisticsTypeId = undefined;
		this.gdStateId = undefined;
    this.fieldConfig.fields = {groupId: undefined, userId: undefined, categoryId: undefined, sourceId: undefined, hierarchy: undefined};
    this.customChangeDateComponent.resetByDate();
		sessionStorage.removeItem('distributionData');
		setTimeout(_=>{
			this.search();
			this.onResize(0);
		})
  }

  // 防抖
  isLoading = false;
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
	
	// 查看工单详情
	coopData:any;
	detailModalShow = false; //弹窗开关
	viewDetail(data) {
	  this.router.navigateByUrl("/newStatistics/distributionInspectionStatistics/incidentList/orderDetail/" + data.id);
	}
	// 关闭弹窗
	closeDetailModelOrder(e) {
	  this.detailModalShow = JSON.parse(e).show;
	}
	// 弹窗确定
	confirmDetailModelOrder(e){
	  this.detailModalShow = false;
	  this.getList();
	}

  openChangeStatisticsType(){
    this.getStatisticsTypeList();
  }

  // 获取统计分类列表
  statisticsTypeList:any[] = [];
  getStatisticsTypeList() {
    this.isLoading = true;
    this.mainService
      .getDictionary("list", "statistics_date_type")
      .subscribe((data) => {
				this.statisticsTypeList = []
        this.isLoading = false;
				if(!data.find(i=> i.id == -1)){
					data.push({
						name:'未知',
						id:-1
					})
				}
        this.statisticsTypeList = data;
      });
  }

  // 详细搜索
  fieldConfig:any = {
		fields: { deptId: undefined, taskTypeId: undefined, sourceId: undefined, minuteId: undefined, specialId: undefined, overtimeId: undefined, abnormalId: undefined, evaluateId: undefined, codeNum: undefined, timeFrameId: undefined, groupId: undefined, userId: undefined, buildingId: undefined},
		config: { dept: true, taskType: true, source: true, minute: true, special: true, overtime: true, abnormal: true, evaluate: true, code: true, timeFrame: true, groupAndUser: true, building: true},
  }
  showSearchMore:boolean = false;
  showMore(){
    this.showSearchMore = true;
  }

  cancelEvent(){
    this.showSearchMore = false;
  }

  submitEvent(fields){
    this.showSearchMore = false;
    this.fieldConfig.fields = fields;
    console.log('this.fieldConfig.fields:', this.fieldConfig.fields)
    this.search();
    this.onResize(37);
  }
}
