<template>
  <div
    ref="radarChart"
    style="width: 100%; height: 400px; min-width: 400px"
  ></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    chartData: {
      type: Object,
      default: {},
    },
    itemCsvData: {
      type: Array,
      default: [],
    },
    machineTypeCode: {
      type: String,
      default: "",
    },
  },
  watch: {
    chartData: {
      deep: true,
      // immediate: true,
      handler() {
        if (this.chartData && this.itemCsvData.length > 0) {
          this.calculateValues();
          this.drawRadarChart();
        }
      },
    },
    itemCsvData: {
      handler() {
        if (this.chartData && this.itemCsvData.length > 0) {
          this.calculateValues();
          this.drawRadarChart();
        }
      },
      deep: true,
      // immediate: true,
    },
  },
  data() {
    return {
      maxValues: [],
      minValues: [],
      medianValues: [],
    };
  },
  mounted() {
    this.$nextTick(() => {
      if (this.chartData && this.itemCsvData.length > 0) {
        this.calculateValues();
        this.drawRadarChart();
      }
    });

    // 监听窗口大小变化，手动调用 resize 方法
    window.addEventListener("resize", this.resizeChart);
  },
  beforeDestroy() {
    // 清除事件监听
    window.removeEventListener("resize", this.resizeChart);
  },
  methods: {
    // 计算最大值、最小值和中位值
    calculateValues() {
      const data = this.itemCsvData.map((item) => [
        item.TurbinePowerRate,
        item.TurbineRunRate,
        item.WindSpeedAvr,
        item.Thi,
        item.Ws,
      ]);

      // 计算最大值
      this.maxValues = data[0].map((_, colIndex) =>
        Math.max(...data.map((row) => row[colIndex]))
      );

      // 计算最小值
      this.minValues = data[0].map((_, colIndex) =>
        Math.min(...data.map((row) => row[colIndex]))
      );

      // 计算中位值
      this.medianValues = this.calculateMedian(data);
    },
    // 计算每列的中位值
    calculateMedian(data) {
      return data[0].map((_, colIndex) => {
        const columnData = data
          .map((row) => parseFloat(row[colIndex])) // 将字符串转换为数字
          .sort((a, b) => a - b); // 数字排序
        const mid = Math.floor(columnData.length / 2);
        return columnData.length % 2 === 0
          ? (columnData[mid - 1] + columnData[mid]) / 2
          : columnData[mid];
      });
    },
    // 渲染雷达图
    drawRadarChart() {
      // 获取数据
      const values = [
        this.chartData.TurbinePowerRate,
        this.chartData.TurbineRunRate,
        this.chartData.WindSpeedAvr,
        this.chartData.Thi,
        this.chartData.Ws,
      ];
      // 将中位值存入 window，确保 tooltip 访问
      window.medianValues = this.medianValues;
      // 雷达图的指示器，使用最大值、最小值和中位值来动态设置
      const indicators = [
        {
          name: "风机能量利用率",
          max: this.maxValues[0],
          min: this.minValues[0],
        },
        {
          name: "风机可利用率",
          max: this.maxValues[1],
          min: this.minValues[1],
        },
        { name: "平均风速", max: this.maxValues[2], min: this.minValues[2] },
        {
          name: "等效利用小时",
          max: this.maxValues[3],
          min: this.minValues[3],
        },
        {
          name: "功率曲线一致性系数",
          max: this.maxValues[4],
          min: this.minValues[4],
        },
      ];

      // 构建 ECharts 配置项
      console.log(this.machineTypeCode, " this.machineTypeCode");
      const option = {
        // backgroundColor: 'rgba(240, 240, 240, 0.5)', // 整体背景颜色
        title: {
          text:
            this.machineTypeCode +
            "机型" +
            this.chartData.wind_turbine_name +
            "机组指标",
          left: "center",
          textStyle: {
            fontSize: 16, // 设置字体大小为 16px
          },
        },
        tooltip: {
          trigger: "item",
          z: 999999999999,
          appendToBody: true, // 强制添加到 body
          formatter: (params) => {
            const indicators = [
              { label: "风机能量利用率", unit: " %" },
              { label: "风机可利用率", unit: " %" },
              { label: "平均风速", unit: " m/s" },
              { label: "利用小时", unit: " h" },
              { label: "功率曲线一致性系数", unit: " %" },
            ];
            const values = params.value;
            const medianValues = window.medianValues || [];
            let content = `<strong>${params.seriesName}</strong><br/>`;
            for (let i = 0; i < indicators.length; i++) {
              content += `${indicators[i].label}: ${values[i]}${
                indicators[i].unit
              }<br/>中位值: ${parseFloat(medianValues[i].toFixed(3))}${
                indicators[i].unit
              }<br/><br/>`;
            }
            return content;
          },
        },
        radar: {
          indicator: indicators,
          center: ["45%", "45%"],
          radius: "50%",
          splitNumber: 5,
          splitArea: {
            show: true,
            areaStyle: {
              color: [
                "rgba(200, 200, 200, 0.1)",
                "rgba(rgba(200, 200, 200, 0.1)",
              ], // 交替背景色
            },
          },
        },
        toolbox: {
          feature: {
            saveAsImage: { show: true },
          },
        },
        series: [
          {
            name: this.chartData.wind_turbine_name + "机组指标",
            type: "radar",
            data: [
              {
                value: values,
                name: this.chartData.wind_turbine_name + "机组指标",
                lineStyle: {
                  width: 2,
                  color: "#636efc",
                },
                areaStyle: {
                  color: "rgba(99, 110, 252, 0.3)",
                },
              },
            ],
          },
          {
            name: "中位值",
            type: "radar",
            data: [
              {
                value: this.medianValues,
                name: "中位值",
                lineStyle: {
                  width: 2,
                  color: "#f39c12",
                  type: "dashed",
                },
              },
            ],
          },
        ],
      };

      // 使用 ECharts 渲染雷达图
      const chart = echarts.init(this.$refs.radarChart);
      chart.setOption(option);
    },
    // 图表调整大小
    resizeChart() {
      const chart = echarts.getInstanceByDom(this.$refs.radarChart);
      if (chart) {
        chart.resize();
      }
    },
  },
};
</script>
