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

import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { format, startOfDay, endOfDay, startOfWeek, endOfWeek, add } from 'date-fns';
import { BuildingInspectionStatisticsService } from './building-inspection-statistics.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-building-inspection-statistics",
  templateUrl: "./building-inspection-statistics.component.html",
  styleUrls: ["./building-inspection-statistics.component.less"],
})
export class BuildingInspectionStatisticsComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tool: ToolService,
    private buildingInspectionStatisticsService: BuildingInspectionStatisticsService,
  ) {}

  listOfData: any[] = []; //表格数据
  searchDto: any = {
    dateRange: [startOfWeek(add(new Date(), { weeks: -1}), { weekStartsOn: 1 }), endOfWeek(add(new Date(), { weeks: -1}), { weekStartsOn: 1 })],
    department: [],
    buildingList: null,
  }

  hosId: any; //院区（搜索）
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  // 初始化增删改按钮
  coopBtns: any = {};

  searchTimerSubject = new Subject();

  ngOnInit() {
    this.searchTimerSubject.pipe(debounceTime(500)).subscribe((v) => {
      let fun = v[0];
      fun.call(this, v[1]);
    });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(true);
    this.getDeparts();
    this.getBuildingList();
  }

  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }

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

  // 获取科室
  alldepart: any = []; //科室
  getDeparts(dept?) {
    let data = {
      department: {
        cascadeHosId: this.hosId,
        dept: dept,
        configRoom: 1,
      },
      idx: 0,
      sum: 20,
    };
    this.isLoading = true;
    this.buildingInspectionStatisticsService
      .getDeparts(data)
      .subscribe((data) => {
        this.alldepart = data.list;
        this.isLoading = false;
      });
  }

  // 获取楼栋
  buildingList: any = []; //楼栋
  getBuildingList() {
    let data = {
      building: {
        cascadeHosId: this.hosId,
      },
      idx: 0,
      sum: 9999,
    };
    this.isLoading = true;
    this.buildingInspectionStatisticsService
      .getBuildingList(data)
      .subscribe((data) => {
        this.buildingList = data.list;
        this.isLoading = false;
      });
  }

  // 搜索
  search() {
    this.getList(true);
  }
  // 重置
  reset() {
    this.searchDto = {
      dateRange: [startOfWeek(add(new Date(), { weeks: -1}), { weekStartsOn: 1 }), endOfWeek(add(new Date(), { weeks: -1}), { weekStartsOn: 1 })],
      department: [],
      buildingList: null,
    }
    this.search();
  }
  // 表格数据
  loading1 = false;
  statisticsObj:any = [];
  getList(isResetPageIndex = false) {
    isResetPageIndex && (this.pageIndex = 1);
    let postData:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      hosId: this.hosId,
      startTime: this.searchDto.dateRange[0] ? format(startOfDay(this.searchDto.dateRange[0]), 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: this.searchDto.dateRange[1] ? format(endOfDay(this.searchDto.dateRange[1]), 'yyyy-MM-dd HH:mm:ss') : undefined,
      deptIds: this.searchDto.department.length ? this.searchDto.department.toString() : undefined,
      buildingId: this.searchDto.building|| undefined,
    };
    this.loading1 = true;
    this.buildingInspectionStatisticsService
      .query(postData)
      .subscribe((result) => {
        this.loading1 = false;
        result.data = result.data || [];
        this.listOfData = result.data;
        this.listLength = result.totalNum;
        let summary = result.summary || [];
        this.statisticsObj = summary.length ? summary[0] : [];
      });
  }

  // 查看业务数据
  businessDataModalShow = false; //业务数据弹窗开关
  businessDataModalType = ''; //业务数据类型
  dataInfo = null; //查看业务数据携带
  viewDetail(data, type) {
    this.dataInfo = data;
    this.businessDataModalType = type;
    this.businessDataModalShow = true;
  }
  // 关闭业务数据弹窗
  closeModelBlood(e) {
    this.businessDataModalShow = JSON.parse(e).show;
  }

  // 导出
  loading2 = false;
  export() {
    let postData:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      hosId: this.hosId,
      startTime: this.searchDto.dateRange[0] ? format(startOfDay(this.searchDto.dateRange[0]), 'yyyy-MM-dd HH:mm:ss') : undefined,
      endTime: this.searchDto.dateRange[1] ? format(endOfDay(this.searchDto.dateRange[1]), 'yyyy-MM-dd HH:mm:ss') : undefined,
      deptIds: this.searchDto.department.length ? this.searchDto.department.toString() : undefined,
      buildingId: this.searchDto.building|| undefined,
    };
    this.loading2 = true;
    this.buildingInspectionStatisticsService.exportReport(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, "");
      }
    );
  }

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

  personDetail(dataInfo){
    console.log(dataInfo);
    let startDate = dataInfo.searchDto.dateRange[0] ? format(startOfDay(dataInfo.searchDto.dateRange[0]), 'yyyy-MM-dd HH:mm:ss') : 'null';
    let endDate = dataInfo.searchDto.dateRange[1] ? format(endOfDay(dataInfo.searchDto.dateRange[1]), 'yyyy-MM-dd HH:mm:ss') : 'null';
    let deptId = dataInfo.data[10] || 'null';
    let countRemark = dataInfo.countRemark || 'null';
    this.router.navigateByUrl(
      `/main/buildingInspectionStatistics/workerStatisticsDetail/null/${startDate}/${endDate}/null/buildingInspectionStatistics/${deptId}/${countRemark}`
    );
  }
}

