import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { differenceInCalendarDays, endOfMonth, endOfYear, format, startOfMonth, startOfYear, getQuarter } 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-medical-waste-trend-analysis",
  templateUrl: "./medical-waste-trend-analysis.component.html",
  styleUrls: ["./medical-waste-trend-analysis.component.less"],
})
export class MedicalWasteTrendAnalysisComponent 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.changeDateType();
  }

  searchDto = {
    dateType: "day", //选中日期维度
    dateStr: new Date(), //选中日期--天、月、年
    year: +format(new Date(), "yyyy"),//季度-年
    quarter: getQuarter(new Date()),//季度
    tabType: 'YoY',//YoY/同比，MoM/环比
  }

  tabTypes = [
    {
      name: "同比",
      value: "YoY",
    },
    {
      name: "环比",
      value: "MoM",
    },
  ]

  quarterList = [
    { name: '第一季度', value: 1, },
    { name: '第二季度', value: 2, },
    { name: '第三季度', value: 3, },
    { name: '第四季度', value: 4, },
  ]

  yearList = this.generaterYears();

  dateTypes: any = [
    {
      label: "按天统计",
      value: "day",
    },
    {
      label: "按月统计",
      value: "month",
    },
    {
      label: "按季度统计",
      value: "quarter",
    },
    {
      label: "按年统计",
      value: "year",
    },
  ]; //时间维度

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

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

  // 切换同比/环比
  changeTabType(value){
    this.searchDto.tabType = value;
    this.search();
  }

  // 生成前5年的年份
  generaterYears(){
    const currentYear = new Date().getFullYear();
    const years = [];

    for (let i = currentYear - 4; i <= currentYear; i++) {
      years.push(i);
    }

    return years.map(v => ({
      name: v + '年',
      value: v,
    }));
  }
  // 科室重量差异率TOP10
  deptWeightOption;
  deptWeightChart(datas) {
    console.log(datas)
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.deptName);
        nums.push({
          name: e.deptName,
          value: e.weightRate,
          label: {
            position: e.weightRate >= 0 ? 'bottom' : 'top',
          }
        });
      });
    }
    this.deptWeightOption = {
      color: ["#3398DB"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
        },
        formatter: '{b}: {c}%'
      },
      grid: {
        left: "9px",
        right: "9px",
        bottom: "20px",
        top: "20px",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: labels,
          // axisLine: {
          //   show: true,
          //   onZero: false,
          // },
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          interval: 20,
          max: 100,
          min: -100,
          splitLine: {
            // show: false,
          },
          axisLabel: {
            formatter: "{value}%",
          },
          nameTextStyle: {
            align: "left",
          },
        },
      ],
      series: [
        {
          name: "差异率",
          type: "bar",
          barWidth: "35",
          data: nums,
          label: {
            show: true,
            color: '#000',
            formatter: '{c}%'
          },
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                if (params.value > 0) {
                  return '#92DCE9';  // 正数颜色
                } else {
                  return '#7E8CEB';    // 负数颜色
                }
              },
            },
          },
        },
      ],
    };
  }
  // 医废类型重量差异率排名
  typeWeightOption;
  typeWeightChart(datas) {
    console.log(datas)
    let labels = [];
    let nums = [];
    if (datas.length) {
      datas.forEach((e) => {
        labels.push(e.clinicalWasteTypeName);
        nums.push({
          name: e.clinicalWasteTypeName,
          value: e.weightRate,
          label: {
            position: e.weightRate >= 0 ? 'bottom' : 'top',
          }
        });
      });
    }
    this.typeWeightOption = {
      color: ["#3398DB"],
      tooltip: {
        trigger: "axis",
        axisPointer: {
          // 坐标轴指示器，坐标轴触发有效
          type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
        },
        formatter: '{b}: {c}%'
      },
      grid: {
        left: "9px",
        right: "9px",
        bottom: "20px",
        top: "20px",
        containLabel: true,
      },
      xAxis: [
        {
          type: "category",
          data: labels,
          // axisLine: {
          //   show: true,
          //   onZero: false,
          // },
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          type: "value",
          interval: 20,
          max: 100,
          min: -100,
          splitLine: {
            // show: false,
          },
          axisLabel: {
            formatter: "{value}%",
          },
          nameTextStyle: {
            align: "left",
          },
        },
      ],
      series: [
        {
          name: "差异率",
          type: "bar",
          barWidth: "35",
          data: nums,
          label: {
            show: true,
            color: '#000',
            formatter: '{c}%'
          },
          itemStyle: {
            normal: {
              //每根柱子颜色设置
              color: function (params) {
                if (params.value > 0) {
                  return '#89C9BD';  // 正数颜色
                } else {
                  return '#0694B6';    // 负数颜色
                }
              },
            },
          },
        },
      ],
    };
  }
  // 搜索
  search() {
    this.getData();
  }
  // 重置
  reset() {
    this.searchDto = {
      dateType: "day", //选中日期维度
      dateStr: new Date(), //选中日期--天、月、年
      year: +format(new Date(), "yyyy"),//季度-年
      quarter: getQuarter(new Date()),//季度
      tabType: 'YoY',//YoY/同比，MoM/环比
    }
    this.search();
  }
  // 数据
  loading = false;
  headerDate: any = {};
  headerData: any = {};
  deptListTop10: any = [];
  deptCompareListTop10: any = [];
  wasteTypeListTop10: any = [];
  wasteTypeCompareListTop10: any = [];
  deptBarTop10: any = [];
  wasteTypeBarTop10: any = [];
  getData() {
    let postData: any = {
      tabType: this.searchDto.tabType,
      hosId: this.hospital,
      type: this.searchDto.dateType,
    };
    switch (postData.type) {
      case "day":
        postData.dateStr = this.searchDto.dateStr ? format(this.searchDto.dateStr, "yyyy-MM-dd") : format(new Date(), "yyyy-MM-dd");
        break;
      case "month":
        postData.dateStr = this.searchDto.dateStr ? format(this.searchDto.dateStr, "yyyy-MM") : format(new Date(), "yyyy-MM");
        break;
      case "quarter":
        postData.year = this.searchDto.year || +format(new Date(), "yyyy");
        postData.quarter = this.searchDto.quarter || getQuarter(new Date());
        break;
      case "year":
        postData.dateStr = format(this.searchDto.dateStr, "yyyy");
        break;
    }
    this.loading = true;
    this.mainService
      .postCustom("report/trend/analysis", "medicalWaste", postData)
      .subscribe((result) => {
        this.loading = false;
        if(result.status == 200){
          this.headerDate = result.list[0] || {};
          this.headerData = result.list[1] || {};
          let bodyData = result.list[2] || {};
          this.deptListTop10 = bodyData.deptListTop10 || [];
          this.deptCompareListTop10 = bodyData.deptCompareListTop10 || [];
          this.wasteTypeListTop10 = bodyData.wasteTypeListTop10 || [];
          this.wasteTypeCompareListTop10 = bodyData.wasteTypeCompareListTop10 || [];
          this.deptBarTop10 = bodyData.deptBarTop10 || [];
          this.deptWeightChart(this.deptBarTop10);
          this.wasteTypeBarTop10 = bodyData.wasteTypeBarTop10 || [];
          this.typeWeightChart(this.wasteTypeBarTop10);
        }
      });
  }
  // 获取院区
  hospital: string; //选中院区
  getAllHos() {
    this.hospital = this.tool.getCurrentHospital().id;
  }

  // 修改时间展示维度
  changeDateType(e?) {
    if(this.searchDto.dateType == 'year' && this.searchDto.tabType == 'MoM'){
      this.searchDto.tabType = 'YoY';
    }
    this.getData();
  }

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