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-compre-statistics",
  templateUrl: "./compre-statistics.component.html",
  styleUrls: ["./compre-statistics.component.less"],
})
export class CompreStatisticsComponent 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.getAllTaskType();
    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[] = []; //表格数据

  alldepart: any = []; //当前院区所属科室
  dateRange: any = []; //发起时间区间 天
  monthRangeStart: any; //发起时间 月 起
  monthRangeEnd: any; //发起时间 月 止
  yearRangeStart: any; //发起时间 年 起
  yearRangeEnd: any; //发起时间 年 止

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

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

  options;

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

  // 搜索
  searchData = {}; //搜索字段
  search() {
    this.searchData["hosId"] = this.hospital || "";
    if (this.startDate) {
      this.searchData["dateRange"] = {
        start: this.startDate + " " + "00:00:00",
        end: this.endDate + " " + "23:59:59",
      };
    }
    this.searchData["type"] = this.dateType;
    console.log(this.searchData);
    // 完成率
    this.getComp();
    // 工单量趋势
    this.getTrend();
    // 工单类型占比
    this.getTaskTypeCount();
    // 科室统计
    this.getDeptCount();
    // 用户统计
    this.getUserInfo();
  }
  // 重置
  reset() {
    this.changeDateType("day");
    this.changeDateRange("1");
    this.search();
  }

  // 获取院区
  hospital: string; //选中院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id + "";
  }

  // 获取任务类型
  allTaskType = [];
  taskType = "-1";
  getAllTaskType() {
    let that = this;
    that.mainService
      .getDictionary("list", "association_types")
      .subscribe((data) => {
        that.allTaskType = data;
      });
  }
  // 切换任务类型
  thisType = "全部工单类型"; //当前任务类型
  changeTaskType(e) {
    let that = this;
    if (e == -1) {
      that.thisType = "全部工单类型";
    } else {
      this.allTaskType.forEach((el) => {
        if (e == el.id) {
          that.thisType = el.name;
        }
      });
    }
    this.getTrend();
  }

  // 禁选日期
  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 < 10
        ? "0" + (result[0].getMonth() + 1)
        : result[0].getMonth() + 1) +
      "-" +
      (result[0].getDate() < 10
        ? "0" + result[0].getDate()
        : result[0].getDate());
    this.endDate =
      result[1].getFullYear() +
      "-" +
      (result[1].getMonth() + 1 < 10
        ? "0" + (result[1].getMonth() + 1)
        : result[1].getMonth() + 1) +
      "-" +
      (result[1].getDate() < 10
        ? "0" + result[1].getDate()
        : 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;
  }

  // 修改时间展示维度
  changeDateType(res) {
    console.log(res, this.dateType);
    this.dateType = res;
    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;
    }
  }

  // 各类型工单占比饼图
  taskTypeOptions;
  taskTypeChart(datas) {
    this.taskTypeOptions = {
      title: {
        text: "总工单数",
        subtext: this.taskTotal,
        textAlign: "center",
        left: "75",
        top: "40%",
        textStyle: {
          //标题内容的样式
          color: "#666",
          fontSize: 12,
        },
        subtextStyle: {
          //副标题内容的样式
          color: "#333",
          fontWeight: "bold",
          fontSize: 20,
        },
      },
      tooltip: {
        trigger: "item",
        formatter: "{b}: {c} ({d}%)",
      },
      legend: {
        data: datas,
        type: "scroll",
        orient: "vertical",
        right: 0,
        top: 20,
        bottom: 20,
        formatter: function (name) {
          var target;
          var percent;
          for (var i = 0, l = datas.length; i < l; i++) {
            if (datas[i].name == name) {
              target = datas[i].num;
              percent = datas[i].percent;
            }
          }
          console.log(datas)
          var arr = ["" + name + " | " + percent + "% " + target];
          return arr.join("\n");
        },
      },
      series: [
        {
          name: "",
          type: "pie",
          hoverOffset: 5,
          radius: ["50%", "70%"],
          center: ["80", "50%"],
          avoidLabelOverlap: false,
          label: {
            normal: {
              show: false,
            },
          },
          data: datas,
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                let colorList = [
                  "#48707f",
                  "#3bb196",
                  "#48b856",
                  "#00863c",
                  "#a4c4c1",
                  "#55bab6",
                  "#2f4554",
                  "#91c7ae",
                  "#6e7074",
                  "#546570",
                  "#c4ccd3",
                  "#4BABDE",
                  "#FFDE76",
                  "#E43C59",
                  "#37A2DA",
                ];
                return colorList[params.dataIndex];
              },
            },
          },
        },
      ],
    };
  }

  // 工单量趋势折线图
  orderOptions;
  orderChart(datas) {
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.name);
        nums.push(e.value - 0);
      });
    }
    this.orderOptions = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
          label: {
            backgroundColor: "#6a7985",
          },
        },
      },
      legend: {
        bottom: "0",
      },
      grid: {
        left: "30",
        right: "40",
        top: "35",
        bottom: "60",
        containLabel: true,
      },
      xAxis: [
        {
          name: "时间",
          type: "category",
          boundaryGap: false,
          data: labels,
        },
      ],
      yAxis: [
        {
          name: "工单总量（件）",
          type: "value",
          nameTextStyle: {
            align: "left",
          },
        },
      ],
      dataZoom: [
        {
          type: "inside",
          start: 0,
          end: 100,
        },
        {
          start: 0,
          end: 10,
          left: "88",
          right: "83",
          bottom: "25",
          handleSize: "80%",
          textStyle: {
            lineHeight: 40,
          },
          handleStyle: {},
        },
      ],
      series: [
        {
          name: this.thisType,
          type: "line",
          label: {
            normal: {
              show: true,
              position: "top",
            },
          },
          data: nums,
          itemStyle: {
            color: "#55bab6",
          },
        },
      ],
    };
  }

  // 各类型平均时间柱状图
  durationOption;
  durationChart(datas) {
    console.log(datas)
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.name);
        nums.push(e.count - 0);
      });
    }
    this.durationOption = {
      color: ["#3398DB"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
        },
      },
      grid: {
        left: "10",
        right: "4%",
        bottom: "10",
        top: "35",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: labels,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          name: "平均时间（ 分钟 ）",
          nameTextStyle: {
            align: "left",
          },
        },
      ],
      series: [
        {
          name: "平均时间",
          type: "bar",
          barWidth: "40",
          data: nums,
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                let colorList = [
                  "#49b856",
                  "#56bab6",
                  "#48717f",
                  "#39b199",
                  "#a4c4c1",
                  "#55bab6",
                  "#2f4554",
                  "#91c7ae",
                  "#6e7074",
                  "#546570",
                  "#c4ccd3",
                  "#4BABDE",
                  "#FFDE76",
                  "#E43C59",
                  "#37A2DA",
                ];
                return colorList[params.dataIndex];
              },
            },
          },
          // barWidth: '16'
        },
      ],
    };
  }

  // 科室统计柱状图
  deptOption;
  deptChart(datas) {
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.name);
        nums.push(e.num - 0);
      });
    }
    console.log(labels, nums);
    this.deptOption = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "10",
        right: "100",
        top: "0",
        bottom: "0",
        containLabel: true,
      },
      xAxis: {
        show: "",
        // type: 'value',
        // boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: "category",
        data: labels,
        inverse: true,
        axisLabel: {
          margin: 15,
          textStyle: {
            color: "#666",
          },
        },
        axisTick: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisLine: {
          lineStyle: {
            color: "#e5e9ed",
          },
        },
      },
      series: [
        {
          name: "建单总数",
          type: "bar",
          data: nums,
          label: {
            show: true,
            position: "right",
            formatter: "{c} 件 ",
          },
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                let colorList = [
                  "#49b856",
                  "#56bab6",
                  "#48717f",
                  "#39b199",
                  "#a4c4c1",
                  "#55bab6",
                  "#2f4554",
                  "#91c7ae",
                  "#6e7074",
                  "#546570",
                  "#c4ccd3",
                  "#4BABDE",
                  "#FFDE76",
                  "#E43C59",
                  "#37A2DA",
                ];
                return colorList[params.dataIndex];
              },
            },
          },
          barCategoryGap: "27",
          barWidth: "16",
        },
      ],
    };
  }

  // 人员统计
  userOption;
  userChart(datas) {
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.name);
        nums.push(e.num - 0);
      });
    }
    console.log(labels, nums);
    this.userOption = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      grid: {
        left: "10",
        right: "100",
        top: "0",
        bottom: "0",
        containLabel: true,
      },
      xAxis: {
        show: "",
        // type: 'value',
        // boundaryGap: [0, 0.01]
      },
      yAxis: {
        type: "category",
        data: labels,
        inverse: true,
        axisLabel: {
          margin: 15,
          textStyle: {
            color: "#666",
          },
        },
        axisTick: {
          lineStyle: {
            color: "#fff",
          },
        },
        axisLine: {
          lineStyle: {
            color: "#e5e9ed",
          },
        },
      },
      series: [
        {
          name: "完成工单总数",
          type: "bar",
          data: nums,
          label: {
            show: true,
            position: "right",
            formatter: "{c} 件 ",
          },
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                let colorList = [
                  "#49b856",
                  "#56bab6",
                  "#48717f",
                  "#39b199",
                  "#a4c4c1",
                  "#55bab6",
                  "#2f4554",
                  "#91c7ae",
                  "#6e7074",
                  "#546570",
                  "#c4ccd3",
                  "#4BABDE",
                  "#FFDE76",
                  "#E43C59",
                  "#37A2DA",
                ];
                return colorList[params.dataIndex];
              },
            },
          },
          barCategoryGap: "27",
          barWidth: "16",
        },
      ],
    };
  }

  // 按时完成率
  compInfo: any = {};
  getComp() {
    let that = this;
    let postData = {
      hosId: this.searchData["hosId"],
      startTime: this.searchData["dateRange"]["start"],
      endTime: this.searchData["dateRange"]["end"],
    };
    that.mainService
      .postReportCount("completion", postData)
      .subscribe((data) => {
        console.log(data);
        that.compInfo = data || {};
      });
  }

  // 各类型工单占比
  taskTypeInfo = [];
  taskTotal = 0;
  getTaskTypeCount() {
    let that = this;
    let postData = {
      hosId: this.searchData["hosId"],
      startTime: this.searchData["dateRange"]["start"],
      endTime: this.searchData["dateRange"]["end"],
    };
    that.mainService.postReportCount("taskType", postData).subscribe((data) => {
      console.log(data);
      that.taskTypeInfo = data.data || [];
      that.taskTotal = data.total;
      if (data.total - 0) {
        let numData = that.taskTypeInfo.map((e) => {
          return {
            ...e,
            value: e.num
          }
        });
        let countData = that.taskTypeInfo.map((e) => {
          return {
            ...e,
            value: e.count
          }
        });
        this.taskTypeChart(numData);
        this.durationChart(countData);
      } else {
        this.taskTypeChart([]);
        this.durationChart([]);
      }
    });
  }

  // 工单量趋势
  trendTotal: boolean = false;
  getTrend() {
    let that = this;
    let postData = {
      hosId: this.searchData["hosId"],
      startTime: this.searchData["dateRange"]["start"],
      endTime: this.searchData["dateRange"]["end"],
      type: this.searchData["type"],
      associationType: Number(this.taskType) == -1 ? "" : this.taskType,
    };

    that.mainService
      .postReportCount("orderTrend", postData)
      .subscribe((data) => {
        console.log(data);
        // that.taskTypeInfo = data || {}
        if (data.data && data.data.length) {
          that.trendTotal = true;
          data.data.forEach((e) => {
            e.value = e.num;
            e.name = e.name.replace(new RegExp("-", "g"), "/");
          });
          this.orderChart(data.data);
        } else {
          that.trendTotal = false;
          this.orderChart([]);
        }
      });
  }

  // 科室统计
  deptInfo;
  getDeptCount() {
    let that = this;
    let postData = {
      hosId: this.searchData["hosId"],
      startTime: this.searchData["dateRange"]["start"],
      endTime: this.searchData["dateRange"]["end"],
    };
    that.mainService.postReportCount("dept", postData).subscribe((data) => {
      console.log(data);
      that.deptInfo = data.data || [];
      if (data.data && data.data.length) {
        data.data.forEach((e) => {
          e.value = e.num;
        });
        this.deptChart(data.data);
      } else {
        this.deptChart([]);
      }
    });
  }

  // 人员统计
  userInfo;
  getUserInfo() {
    let that = this;
    let postData = {
      hosId: this.searchData["hosId"],
      startTime: this.searchData["dateRange"]["start"],
      endTime: this.searchData["dateRange"]["end"],
    };
    that.mainService.postReportCount("user", postData).subscribe((data) => {
      console.log(data);
      that.userInfo = data.data || [];
      if (data.data && data.data.length) {
        data.data.forEach((e) => {
          e.value = e.num;
        });
        this.userChart(data.data);
      } else {
        this.userChart([]);
      }
    });
  }

  // 更多
  toMore(type) {
    let sendData = this.searchData;
    sendData["range"] = this.dateRange;
    sendData["defRange"] = this.defRange;
    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;
  timer; //边输入边搜索的定时器
  searchTimer(fun, e, those) {
    let that = this;
    that.isLoading = true;
    clearTimeout(that.timer);
    that.timer = setTimeout(() => {
      fun(e, those);
    }, 1000);
  }

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