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

import { MainService } from "../../services/main.service";
import { DateService } from "../../services/date.service";
import { MyServiceService } from "../../services/my-service.service";
import { ToolService } from "../../services/tool.service";

@Component({
  selector: "app-task-type-statistics",
  templateUrl: "./task-type-statistics.component.html",
  styleUrls: ["./task-type-statistics.component.less"],
})
export class TaskTypeStatisticsComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private dateService: DateService,
    private myService: MyServiceService,
    private tool: ToolService
  ) {}

  ngOnInit() {
    this.getSearchData();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHos();
  }

  defRange = "1"; //默认上周
  defRanges = [
    {
      label: "上周",
      id: 1,
    },
    {
      label: "上月",
      id: 2,
    },
    {
      label: "上年",
      id: 3,
    },
  ]; //时间默认区间

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  alldepart: any = []; //当前院区所属科室
  dateRange: any = []; //发起时间区间 天

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

  // 初始化增删改按钮
  coopBtns: any = {};
  searchData: any = {}; // 综合统计页面带过来的参数
  getSearchData() {
    let that = this;
    let sub = that.myService.getMsg().subscribe((msg) => {
      // 从综合报表跳转过来
      that.searchData = msg;
      console.log(that.searchData);
      console.log(66);
      sub.unsubscribe(); //取消订阅，否则订阅函数会累加执行
      that.hospital = that.searchData["hosId"];
      that.changeDate(that.searchData["range"]);
      that.defRange = that.searchData["defRange"];
      that.search();
    });
    // 不是从综合报表页面跳转过来的
    setTimeout(() => {
      if (!sub["isStopped"]) {
        that.changeDateRange(that.defRange);
        that.search();
      }
    }, 100);
  }
  // 搜索
  search(num?: number) {
    if (this.hospital) {
      this.searchData["hosId"] = this.hospital;
    }
    if (this.startDate) {
      this.searchData["dateRange"] = {
        start: this.startDate + " " + "00:00:00",
        end: this.endDate + " " + "23:59:59",
      };
    }
    if (num !== undefined) {
      this.getList(num);
    } else {
      this.getList();
    }
  }
  // 导出
  loading2 = false;
  export() {
    let that = this;
    let postData = {
      hosId: that.hospital,
      startTime: this.startDate + " " + "00:00:00",
      endTime: this.endDate + " " + "23:59:59",
    };
    this.loading2 = true;
    that.mainService.exportReport("taskType", 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, "");
      }
    );
  }
  // 重置
  reset() {
    this.changeDateRange("1");
    this.search();
  }
  // 表格数据
  loading1 = false;
  getList(num?: number) {
    if (num !== undefined) {
      this.pageIndex = num;
    }
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      startTime: this.searchData.dateRange.start,
      endTime: this.searchData.dateRange.end,
      hosId: this.searchData.hosId,
    };
    this.loading1 = true;
    this.mainService
      .postCustom("report", "taskType", postData)
      .subscribe((result) => {
        this.loading1 = false;
        this.listOfData = result.list || [];
        this.listLength = result.totalNum;
      });
  }
  // 获取院区
  hospital: string; //选中院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id + "";
  }

  // 日期选择 日
  startDate: string; //发起时间开始
  endDate: string; //发起时间结束
  changeDate(result?): void {
    console.log(this.dateRange);
    console.log(result);
    this.dateRange = result;
    if (!this.quick) {
      // 不是快捷选择
      this.defRange = null;
    }
    if (!result || !result.length) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate =
      result[0].getFullYear() +
      "-" +
      (result[0].getMonth() + 1) +
      "-" +
      result[0].getDate();
    this.endDate =
      result[1].getFullYear() +
      "-" +
      (result[1].getMonth() + 1) +
      "-" +
      result[1].getDate();
  }

  // 日期选择 快速修改时间区间
  nowdate = new Date();
  quick: boolean = false;
  changeDateRange(res) {
    this.defRange = res;
    console.log(res);
    this.quick = true;
    switch (res) {
      case "1":
        // 上周
        let lastweekstartdate = this.dateService.date().lastWeekStartDate;
        let lastweekenddate = this.dateService.date().lastWeekEndDate;
        console.log(lastweekstartdate, lastweekenddate);
        this.changeDate([lastweekstartdate, lastweekenddate]);
        break;
      case "2":
        // 上月
        let lastmonthstartdate = this.dateService.date().lastMonthStartDate;
        let lastmonthenddate = this.dateService.date().lastMonthEndDate;
        console.log(lastmonthstartdate, lastmonthenddate);
        this.changeDate([lastmonthstartdate, lastmonthenddate]);
        break;
      case "3":
        // 上年
        let lastyearstartdate = this.dateService.date().lastYearStartDate;
        let lastyearenddate = this.dateService.date().lastYearEndDate;
        console.log(lastyearstartdate, lastyearenddate);
        this.changeDate([lastyearstartdate, lastyearenddate]);
        break;
    }
    this.quick = false;
  }

  // 更多
  toMore(type) {
    let sendData = this.searchData;
    console.log(sendData);
    this.myService.sendMsg(sendData);
    this.router.navigateByUrl("/main/" + type);
  }

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

  // 边输入边搜索节流阀
  isLoading: boolean = false;
  searchTimer(fun, e, those) {
    let that = this;
    that.isLoading = true;
    fun(e, those);
  }

  // 截取意见内容(ie内核截取)
  spliceContent(con) {
    if (con.length >= 41 && navigator.userAgent.indexOf("Trident") > -1) {
      return con.slice(0, 20) + "...";
    } else {
      return con;
    }
  }
}
