import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { differenceInCalendarDays, endOfMonth, endOfYear, format, startOfMonth, startOfYear } from "date-fns";

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-tasktype-order-source-statistics",
  templateUrl: "./tasktype-order-source-statistics.component.html",
  styleUrls: ["./tasktype-order-source-statistics.component.less"],
})
export class TasktypeOrderSourceStatisticsComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private dateService: DateService,
    private myService: MyServiceService,
    private tool: ToolService
  ) {}

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHos();
    this.changeDateRange(this.defRange);
    this.search();
  }

  dateType: string = "day"; //选中时间维度
  dateTypes: any = [
    {
      label: "按天统计",
      value: "day",
    },
    {
      label: "按月统计",
      value: "month",
    },
    {
      label: "按年统计",
      value: "year",
    },
  ]; //时间维度
  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 = []; //发起时间区间 天
  monthRangeStart: any; //发起时间 月 起
  monthRangeEnd: any; //发起时间 月 止
  yearRangeStart: any; //发起时间 年 起
  yearRangeEnd: 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();
    });
    that.changeDateRange(that.defRange);
    that.search();
  }
  // 搜索
  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, this.sortCurrentKey, this.sortCurrentValue);
    } else {
      this.getList(this.pageIndex, this.sortCurrentKey, this.sortCurrentValue);
    }
  }
  // 导出
  loading2 = false;
  export() {
    let that = this;
    let postData: any = {
      startTime: this.startDate + " " + "00:00:00",
      endTime: this.endDate + " " + "23:59:59",
      hosId: that.hospital,
      type: this.dateType,
      sourceType: "taskType",
    };
    if (this.sortCurrentKey && this.sortCurrentValue) {
      postData.sort =
        this.sortCurrentValue === "ascend"
          ? this.sortCurrentKey
          : `${this.sortCurrentKey} desc`;
    }
    this.loading2 = true;
    that.mainService.exportReport("workOrderSource", 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.changeDateType("day");
    this.changeDateRange("1");
    this.sortCurrentKey = "";
    this.sortCurrentValue = "";
    this.sortCurrent = {
      source1: null,
      source2: null,
      source3: null,
      source4: null,
    };
    this.search();
  }
  // 表格数据
  loading1 = false;
  getList(num?: number, field?: string, sort?: string) {
    this.pageIndex = num;
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      startTime: this.searchData.dateRange.start,
      endTime: this.searchData.dateRange.end,
      hosId: this.searchData.hosId,
      type: this.dateType,
      sourceType: "taskType",
    };
    if (field && sort) {
      postData.sort = sort === "ascend" ? field : `${field} desc`;
    }
    this.loading1 = true;
    this.mainService
      .postCustom("report", "workOrderSourceReport", postData)
      .subscribe((result) => {
        this.loading1 = false;
        this.listOfData = result.list || [];
        this.listLength = result.totalNum;
      });
  }
  // 获取院区
  hospital: string; //选中院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id + "";
  }

  // 修改时间展示维度
  changeDateType(res) {
    console.log(res, this.dateType);
    this.dateType = res;
    this.searchData["type"] = res;
    console.log(this.searchData);
    switch (res) {
      case "day":
        this.defRanges = [
          {
            label: "上周",
            id: 1,
          },
          {
            label: "上月",
            id: 2,
          },
          {
            label: "上年",
            id: 3,
          },
        ]; //时间默认区间
        this.defRange = "1"; //默认上周
        this.changeDateRange("1");
        break;
      case "month":
        this.defRanges = [
          {
            label: "上月",
            id: 2,
          },
          {
            label: "上年",
            id: 3,
          },
        ]; //时间默认区间
        this.defRange = "2"; //上月
        this.changeDateRange("2");
        break;
      case "year":
        this.defRanges = [
          {
            label: "上年",
            id: 3,
          },
        ]; //时间默认区间
        this.defRange = "3"; //默认上周
        this.changeDateRange("3");
        break;
    }
  }

  // 禁选日期
  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) > 0;
  };

  // 禁选月份开始
  disabledMonthStart = (current: Date): boolean => {
    // Can not select days before today and today
    let cur = differenceInCalendarDays(current, endOfMonth(this.today)) > 0;
    let staEnd = differenceInCalendarDays(current, this.monthRangeEnd) > 0;
    return cur || staEnd;
  };
  // 禁选月份结束
  disabledMonthEnd = (current: Date): boolean => {
    // Can not select days before today and today
    let cur = differenceInCalendarDays(current, endOfMonth(this.today)) > 0;
    let staEnd = differenceInCalendarDays(this.monthRangeStart, current) > 0;
    return cur || staEnd;
  };

  // 禁选年份开始
  disabledYearStart = (current: Date): boolean => {
    // Can not select days before today and today
    let cur = differenceInCalendarDays(current, endOfYear(this.today)) > 0;
    let staEnd = differenceInCalendarDays(current, this.yearRangeEnd) > 0;
    return cur || staEnd;
  };

  // 禁选年份结束
  disabledYearEnd = (current: Date): boolean => {
    // Can not select days before today and today
    let cur = differenceInCalendarDays(current, endOfYear(this.today)) > 0;
    let staEnd = differenceInCalendarDays(this.yearRangeStart, current) > 0;
    return cur || staEnd;
  };

  // 日期选择 日
  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();
  }

  // 月份选择
  changeMonthStart(result?) {
    console.log(result);
    this.monthRangeStart = result;
    if (!this.quick) {
      // 不是快捷选择
      this.defRange = null;
    }
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate = format(startOfMonth(result), 'yyyy-MM-dd');
    // this.endDate = result.getFullYear() + '-' + (result.getMonth() + 1) + '-01';
  }
  changeMonthEnd(result?) {
    console.log(result);
    this.monthRangeEnd = result;
    if (!this.quick) {
      // 不是快捷选择
      this.defRange = null;
    }
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    // this.startDate = result.getFullYear() + '-' + (result.getMonth() + 1) + '-01';
    this.endDate = format(endOfMonth(result), 'yyyy-MM-dd');
  }
  // 年份选择
  changeYearStart(result?) {
    console.log(result);
    this.yearRangeStart = result;
    if (!this.quick) {
      // 不是快捷选择
      this.defRange = null;
    }
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate = format(startOfYear(result), 'yyyy-MM-dd');
    // this.endDate = result.getFullYear() + '-01-01';
  }
  changeYearEnd(result?) {
    console.log(result);
    this.yearRangeEnd = result;
    if (!this.quick) {
      // 不是快捷选择
      this.defRange = null;
    }
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.endDate = format(endOfYear(result), 'yyyy-MM-dd');
  }

  // 日期选择 快速修改时间区间
  today = new Date();
  quick: boolean = false;
  changeDateRange(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]);
        this.changeMonthStart(lastmonthstartdate);
        this.changeMonthEnd(lastmonthenddate);
        break;
      case "3":
        // 上年
        let lastyearstartdate = this.dateService.date().lastYearStartDate;
        let lastyearenddate = this.dateService.date().lastYearEndDate;
        console.log(lastyearstartdate, lastyearenddate);
        this.changeDate([lastyearstartdate, lastyearenddate]);
        this.changeMonthStart(lastyearstartdate);
        this.changeMonthEnd(lastyearenddate);
        this.changeYearStart(lastyearstartdate);
        this.changeYearEnd(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);
  }
  // 列表排序
  sortCurrent = {
    source1: null,
    source2: null,
    source3: null,
    source4: null,
  };
  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);
  }
}
