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";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

@Component({
  selector: "app-quilt-washing-trend-analysis",
  templateUrl: "./quilt-washing-trend-analysis.component.html",
  styleUrls: ["./quilt-washing-trend-analysis.component.less"],
})
export class QuiltWashingTrendAnalysisComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private dateService: DateService,
    private myService: MyServiceService,
    private tool: ToolService
  ) {}
  allClothesType: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.getAllHos();
    this.getAllClothesType();
    this.changeDateType();
  }

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

  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
  deptPriceOption;
  deptPriceChart(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.priceRate,
          label: {
            position: e.priceRate >= 0 ? 'bottom' : 'top',
          }
        });
      });
    }
    this.deptPriceOption = {
      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';    // 负数颜色
                }
              },
            },
          },
        },
      ],
    };
  }
  // 科室数量差异率TOP10
  deptCountOption;
  deptCountChart(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.countRate,
          label: {
            position: e.countRate >= 0 ? 'bottom' : 'top',
          }
        });
      });
    }
    this.deptCountOption = {
      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();
  }
  // 用户输入搜索被服
  isLoading = false;
  changeClothesTypeId(e) {
    this.searchTimer(this.getAllClothesType, e);
  }
  // 边输入边搜索节流阀
  searchTimer(fun, e) {
    this.isLoading = true;
    this.searchTimerSubject.next([fun, e]);
  }
  // 获取被服
  getAllClothesType(e?, those?) {
    let that = those || this;
    let postData: any = {
      idx: 0,
      sum: 10,
      dictionaryTree: {
        name: e || "",
        hosId: that.hospital,
        level: 2,
        key: 'clothes_type',
        deleted: 0,
      },
    };
    that.isLoading = true;
    that.mainService
      .getFetchDataList("simple/data", "dictionaryTree", postData)
      .subscribe((data) => {
        that.allClothesType = data.list;
        that.isLoading = false;
      });
  }
  // 重置
  reset() {
    this.searchDto = {
      dateType: "day", //选中日期维度
      dateStr: new Date(), //选中日期--天、月、年
      year: +format(new Date(), "yyyy"),//季度-年
      quarter: getQuarter(new Date()),//季度
      tabType: 'YoY',//YoY/同比，MoM/环比
      clothesTypeId: undefined, //选择被服
    }
    this.search();
  }
  // 数据
  loading = false;
  headerDate: any = {};
  headerData: any = {};
  priceDeptListTop10: any = [];
  priceCompareDeptListTop10: any = [];
  countDeptListTop10: any = [];
  countCompareDeptListTop10: any = [];
  priceBarTop10: any = [];
  countBarTop10: any = [];
  getData() {
    let postData: any = {
      tabType: this.searchDto.tabType,
      hosId: this.hospital,
      type: this.searchDto.dateType,
      clothesTypeId: this.searchDto.clothesTypeId || undefined,
    };
    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", "clothes", 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.priceDeptListTop10 = bodyData.priceDeptListTop10 || [];
          this.priceCompareDeptListTop10 = bodyData.priceCompareDeptListTop10 || [];
          this.countDeptListTop10 = bodyData.countDeptListTop10 || [];
          this.countCompareDeptListTop10 = bodyData.countCompareDeptListTop10 || [];
          this.priceBarTop10 = bodyData.priceBarTop10 || [];
          this.deptPriceChart(this.priceBarTop10);
          this.countBarTop10 = bodyData.countBarTop10 || [];
          this.deptCountChart(this.countBarTop10);
        }
      });
  }
  // 获取院区
  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);
  }
}
