import GraphBase from "../../../Common/GraphBase";
import ReactECharts from "echarts-for-react";
// import getOptions from "../../../../hooks/getChartOption";
import { useSelector } from "react-redux";
import { useState } from "react";
import * as echarts from "echarts";
import { lunarYear } from "../../../../utils/energeChartOption";
import dayjs from "dayjs";

function NatGas(props) {
  const natGasTrend = useSelector((state) => state.energy.trend.natGas1);
  const gasTrend = useSelector((state) => state.energy.trend.natGas2);
  const [period, setPeriod] = useState("周");
  const [timestr, setTimestr] = useState(
    dayjs().subtract(7, "day").format("YYYY.MM.DD") +
      " - " +
      dayjs().subtract(1, "day").format("YYYY.MM.DD")
  );

  const options = getOptions(
    { 周: "week", 月: "month", 年: "year" }[period],
    [natGasTrend, gasTrend] ?? { week: [], month: [], year: [] }
  );

  function handleSwitch(v) {
    // console.log('switched ', v);
  }

  function handleDateChange(value) {
    setPeriod(value);
    setTimestr(
      {
        年:
          dayjs().subtract(1, "year").endOf("year").format("YYYY.MM.") +
          "29 - " +
          dayjs().endOf("year").format("YYYY.MM.") +
          "28",
        周:
          dayjs().subtract(7, "day").format("YYYY.MM.DD") +
          " - " +
          dayjs().subtract(1, "day").format("YYYY.MM.DD"),
        月:
          dayjs().subtract(1, "month").format("YYYY.MM.") +
          "29 - " +
          dayjs().format("YYYY.MM.") +
          "28",
      }[value]
    );
  }

  return (
    <GraphBase
      icon="battery"
      title="天然气"
      desc={`能耗趋势图  ${timestr}`}
      switchOptions={false}
      onSwitch={handleSwitch}
      defaultSelect={period}
      dateOptions={["周", "月", "年"]}
      //   legend={["总量"]}
      onDateChange={handleDateChange}
      size={["long", "middle"]}
    >
      <div
        className="nat-gas-legend"
        style={{
          position: "absolute",
          top: 28,
          right: 144,
          display: "flex",
          gap: "24px",
        }}
      >
        <div className="legend-item">
          <div
            className="legend-color"
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              marginRight: "8px",
              backgroundColor: "#FFD160",
            }}
          />
          <span style={{ color: "#fff" }}>天然气I</span>
        </div>
        <div className="legend-item">
          <div
            className="legend-color"
            style={{
              display: "inline-block",
              width: "12px",
              height: "12px",
              borderRadius: "2px",
              marginRight: "8px",
              backgroundColor: "#12FFF5",
            }}
          />
          <span style={{ color: "#fff" }}>天然气II</span>
        </div>
      </div>
      {/* real echarts here */}
      {options && (
        <ReactECharts
          key={Math.random()}
          option={options}
          // option={getOptions([[91, 69, 5, 10, 21, 46, 24]], "氧气")}
          style={{ height: "100%" }}
        />
      )}
      {!options && (
        <p
          style={{
            color: "#cccf",
            fontSize: "24px",
            userSelect: "none",
            textAlign: "center",
            paddingTop: "88px",
          }}
        >
          暂无数据
        </p>
      )}
      {/* real table data here  */}
    </GraphBase>
  );
}

export default NatGas;

function getOptions(period, trendArr) {
  if (trendArr[0][period].length === 0 || trendArr[1][period].length === 0)
    return null;
  // export default function getOptions(seriesData, name) {
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1;
  let days = 30;
  if (period == "month") {
    if (currentMonth in [1, 3, 5, 7, 8, 10, 12]) {
      days = 31;
    } else if (currentMonth == 2) {
      days = lunarYear(currentYear) ? 29 : 28;
    }
  }
  const colors = [
    "#FFD160",
    "#12FFF5",
    "#2760FF",
    "#E80091",
    "#8064ff",
    "#ff8a3b",
    "#8cd26d",
    "#2aa1ff",
  ];
  return {
    color: colors,
    grid: { top: 40, right: 12, bottom: 20, left: 80 },
    legend: {
      show: false,
      icon: "roundRect",
      top: 10,
      right: 10,
      padding: 0,
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 3,
      height: 8,
      textStyle: {
        color: "#DFF1FE",
        fontSize: 12,
      },
    },
    xAxis: {
      type: "category",
      data: Array(period == "week" ? 7 : period == "year" ? 12 : days)
        .fill(1)
        .map((_, index) => {
          if (period == "week") {
            const dtimestamp = today - (index + 1) * 24 * 60 * 60 * 1000;
            return `${new Date(dtimestamp).getMonth() + 1}.${new Date(
              dtimestamp
            ).getDate()}`;
          } else if (period == "month") {
            return `${currentMonth}.${days - index}`;
          } else {
            return `${currentYear}.${12 - index}`;
          }
        })
        .reverse(),
      axisLabel: {
        color: "#fff",
        fontSize: 14,
      },
      axisTick: { show: false },
      axisLine: {
        lineStyle: {
          width: 1,
          color: "#213259",
        },
      },
    },
    yAxis: {
      name: "单位/Nm³",
      nameTextStyle: {
        color: "#fff",
        fontSize: 16,
        align: "right",
      },
      type: "value",
      axisLabel: {
        color: "#fff",
        fontSize: 14,
        formatter: "{value}",
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: "#213259",
        },
      },
      splitLine: {
        lineStyle: {
          color: "#213259a0",
        },
      },
    },
    series: [
      {
        data: trendArr[0][period].map((item) =>
          item != null ? (+item).toFixed(2) : null
        ),
        type: "line",
        symbol: "circle",
        symbolSize: 6,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colors[0] + "40" },
            { offset: 0.5, color: colors[0] + "20" },
            { offset: 1, color: colors[0] + "00" },
          ]),
        },
      },
      {
        data: trendArr[1][period].map((item) =>
          item != null ? (+item).toFixed(2) : null
        ),
        type: "line",
        symbol: "circle",
        symbolSize: 6,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: colors[1] + "40" },
            { offset: 0.5, color: colors[1] + "20" },
            { offset: 1, color: colors[1] + "00" },
          ]),
        },
      },
    ],
    // series: seriesData.map((arr, index) => ({
    // 	name: index + 1 + '#' + name,
    // 	data: arr,
    // 	type: 'line',
    // 	areaStyle: {
    // 		color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    // 			{ offset: 0, color: colors[index] + '40' },
    // 			{ offset: 0.5, color: colors[index] + '20' },
    // 			{ offset: 1, color: colors[index] + '00' },
    // 		]),
    // 	},
    // })),
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      className: "xc-chart-tooltip",
      // backgroundColor: ''
    },
  };
}
