<template>
  <el-card
      shadow="always"
      class="common-card-container common-card-container-body-no-padding"
  >
    <div slot="header">
      <span class="card-title">PCS有功功率/PCS无功功率</span>
    </div>
    <div ref="chartRef" style="height: 360px" />
  </el-card>
</template>

<style scoped lang="scss"></style>
<script>
import * as echarts from "echarts";
import resize from "@/mixins/ems/resize";
import { getPointConfigCurve } from "@/api/ems/site";

export default {
  mixins: [resize],
  props: {
    displayData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chartRef);
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    init(siteId, timeRange) {
      const [startTime = "", endTime = ""] = timeRange;
      const query = {
        rangeType: "custom",
        startTime: this.normalizeDateTime(startTime, false),
        endTime: this.normalizeDateTime(endTime, true),
        siteId
      };
      const rows = (this.displayData || []).filter(
        (item) =>
          item &&
          item.useFixedDisplay !== 1 &&
          [
            "SBJK_SSYX__curvePcsActivePower",
            "SBJK_SSYX__curvePcsReactivePower"
          ].includes(item.fieldCode) &&
          item.dataPoint
      );
      const tasks = rows.map((row) => {
        const pointId = String(row.dataPoint || "").trim();
        if (!pointId) return Promise.resolve(null);
        return getPointConfigCurve({
          ...query,
          pointId
        })
          .then((response) => {
            const list = response?.data || [];
            return {
              name: row.fieldName || row.fieldCode || pointId,
              data: list
                .map((item) => [
                  this.parseToTimestamp(item.dataTime),
                  Number(item.pointValue)
                ])
                .filter((item) => item[0] && !Number.isNaN(item[1]))
            };
          })
          .catch(() => null);
      });
      Promise.all(tasks)
        .then((series) => {
          this.setOption((series || []).filter(Boolean));
        });
    },
    normalizeDateTime(value, endOfDay) {
      const raw = String(value || "").trim();
      if (!raw) return "";
      if (raw.includes(" ")) return raw;
      return `${raw} ${endOfDay ? "23:59:59" : "00:00:00"}`;
    },
    parseToTimestamp(value) {
      if (!value) return null;
      const t = new Date(value).getTime();
      return Number.isNaN(t) ? null : t;
    },
    setOption(seriesData = []) {
      this.chart && this.chart.setOption({
        legend: {
          left: "center",
          top: "5",
          itemWidth: 10,
          itemHeight: 5,
          textStyle: {
            fontSize: 9,
          },
        },
        grid: {
          containLabel: true,
        },
        tooltip: {
          show: true,
          trigger: "axis",
          axisPointer: {
            type: "cross",
          }
        },
        textStyle: {
          color: "#333333",
        },
        xAxis: { type: "time" },
        yAxis: {
          type: "value",
        },
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
          {
            start: 0,
            end: 100,
          },
        ],
        series: seriesData.map((item) => ({
          type: "line",
          name: item.name,
          showSymbol: false,
          smooth: true,
          areaStyle: {
            opacity: 0.35
          },
          data: item.data
        })),
      }, true);
    },
  },
};
</script>
