<template>
  <div>
    <div v-loading="loading" :id="`plotDiv-${inds}`" style="width: 100%; height: 550px">
      <el-empty v-if="isError" description="请求失败"></el-empty>
    </div>
  </div>
</template>

<script>
import Plotly from "plotly.js-dist";
import axios from "axios";
import { myMixin } from "@/mixins/chartRequestMixin";

export default {
  props: {
    fileAddr: {
      default: "",
      type: String,
    },

    inds: {
      type: [Number, String],
      default: 1,
    },
  },
  mixins: [myMixin],
  data() {
    return {
      // 数据结构
      chartData: {},
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(v) {
        if (v) {
          this.renderChart();
        }
      },
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    async getData() {
      if (this.fileAddr !== "") {
        try {
          this.loading = true
          this.cancelToken = axios.CancelToken.source();
          console.log(this.cancelToken)
          const resultChartsData = await axios.get(this.fileAddr, {
            cancelToken: this.cancelToken.token
          });
          console.log(resultChartsData)
          this.chartData = resultChartsData.data;
          this.renderChart();
          this.isError = false
          this.loading = false
        } catch (error) {
          this.isError = true
          this.loading = false
        }
      }
    },
    renderChart() {
      const { axes, data, analysisTypeCode } = this.chartData;
      // 从数据中提取 windSpeedRange 和动态生成 speedLabels 和 colorscale
      const windSpeedRanges = new Set();
      data.forEach((engine) => {
        engine.windRoseData.forEach((item) => {
          windSpeedRanges.add(item.windSpeedRange);
        });
      });
      const speedLabels = Array.from(windSpeedRanges).sort(); // 动态范围值
      const colors = [
        "#FBFDD4",
        "#C0E2BA",
        "#57A3BF",
        "#1A2971",
        "#FF6F61",
        "#FFC300",
        "#6A0572",
      ]; // 可扩展颜色列表
      const colorscale = {};
      speedLabels.forEach((label, index) => {
        colorscale[label] = colors[index % colors.length];
      });

      // 定义风向的 16 等分
      const windDirections = Array.from({ length: 16 }, (_, i) => i * 22.5);

      // 数据聚合
      const counts = {};
      speedLabels.forEach((speedLabel) => {
        counts[speedLabel] = Array(windDirections.length).fill(0);
      });

      data.forEach((engine) => {
        engine.windRoseData.forEach((item) => {
          const { windDirection, windSpeedRange } = item;
          const index = windDirections.findIndex(
            (dir, i) =>
              windDirection >= dir && windDirection < windDirections[i + 1]
          );

          if (index !== -1 && counts[windSpeedRange]) {
            counts[windSpeedRange][index] += item.frequency;
          }
        });
      });

      // 构建 traces
      const traces = speedLabels.map((speedLabel) => {
        const percentage = counts[speedLabel];
        return {
          r: percentage,
          theta: windDirections,
          name: speedLabel,
          type: "barpolar",
          marker: {
            color: colorscale[speedLabel],
            line: {
              color: "white",
              width: 1,
            },
          },
        };
      });

      // 图表布局
      const layout = {
        title: `${analysisTypeCode} - ${data[0]?.enginName} `,
        plot_bgcolor: "#e5ecf6",
        polar: {
          bgcolor: "#e5ecf6",
          radialaxis: {
            title: { text: axes.radial },
            gridcolor: "rgb(255,255,255)",
            showgrid: true,
            linecolor: "rgb(255,255,255)",
          },
          angularaxis: {
            title: { text: axes.angular },
            tickvals: windDirections,
            gridcolor: "rgb(255,255,255)",
            tickcolor: "rgb(255,255,255)",
            linecolor: "rgb(255,255,255)",
          },
        },
        showlegend: true,
        legend: { title: { text: axes.levelname } },
      };

      Plotly.newPlot(`plotDiv-${this.inds}`, traces, layout);
    },
  },
};
</script>

<style scoped></style>
