import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { useMount } from "ahooks";
import { Spin } from "antd";
import * as echarts from "echarts";
import { useContext, useRef } from "react";
import { NS_BI_STATISTICS } from "~/enumerate/namespace";
import Panel from "~/pages/Container/Map/components/Content/port/Panel";
import { Context } from "~/pages/Container/Map/js/context";
import "./index.less";

/** 将接口的作业趋势记录转换为图表横轴、图例与序列数据。 */
function formatWorkTrendData(data) {
  const workDates = [...new Set(data.map(item => item.workDate))];
  const workTypes = [
    ...new Map(data.map(item => [item.workType, item.workTypeName])),
  ];
  return {
    xData: workDates,
    date: workTypes.map(([workType]) =>
      data
        .filter(item => item.workType === workType)
        .map(item => Number(item.count)),
    ),
    name: workTypes.map(([, workTypeName]) => workTypeName),
  };
}

/** 负责初始化安全作业趋势图表并在卸载时释放图表实例。 */
function WorkTrendPanel(props) {
  const { portArea } = useContext(Context);
  const chartRef = useRef(null);
  const chartInstance = useRef(null);

  const initEcharts = (mainRef, chartInstance, data) => {
    const colors = [
      "29,128,219",
      "1,245,255",
      "228,187,45",
      "45,118,228",
      "188,45,228",
      "228,72,45",
      "58,45,228",
      "221,44,67",
    ];
    const series = data.date.map((seriesData, index) => ({
      name: data.name[index],
      type: "line",
      symbol: "circle",
      showAllSymbol: true,
      symbolSize: 0,
      smooth: true,
      lineStyle: { width: 2, color: `rgba(${colors[index]},1)` },
      itemStyle: { color: `rgba(${colors[index]},1)` },
      tooltip: { show: true },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(
          0,
          0,
          0,
          1,
          [
            { offset: 0, color: `rgba(${colors[index]},0.3)` },
            { offset: 1, color: `rgba(${colors[index]},0)` },
          ],
          false,
        ),
        shadowColor: "rgba(25,163,223, 0.5)",
        shadowBlur: 20,
      },
      data: seriesData,
    }));
    chartInstance.current = echarts.init(mainRef.current);
    chartInstance.current.setOption({
      tooltip: { trigger: "axis" },
      legend: {
        top: "0",
        align: "left",
        type: "plain",
        data: data.name,
        textStyle: { color: "#fff", fontSize: 12 },
        itemWidth: 18,
      },
      grid: { top: "20%", left: "10%", right: "5%", bottom: "15%" },
      xAxis: [
        {
          type: "category",
          boundaryGap: false,
          axisLine: { show: true, lineStyle: { color: "#15578b" } },
          axisLabel: {
            color: "#fff",
            fontSize: 12,
            formatter(value) {
              return value.substring(5);
            },
          },
          splitLine: { show: false, lineStyle: { color: "#fff" } },
          axisTick: { show: false },
          data: data.xData,
        },
      ],
      yAxis: [
        {
          min: 0,
          splitLine: {
            show: true,
            lineStyle: { color: "rgba(221,221,221,0.1)" },
          },
          axisLine: { show: false, lineStyle: { color: "#fff" } },
          axisLabel: { show: true, color: "#fff", padding: 10 },
        },
      ],
      series,
    });
  };

  useMount(() => {
    const loadTrendData = async () => {
      const { data = [] } = await props.getEightWorkInfoScreenWorkTrend({
        portArea,
      });
      initEcharts(chartRef, chartInstance, formatWorkTrendData(data));
    };

    loadTrendData();
    return () => chartInstance.current?.dispose();
  });

  return (
    <Panel title="安全作业情况统计" className="port-danger-work__trend">
      <div className="port-danger-work-trend__content">
        <Spin spinning={props.biStatistics.getEightWorkInfoScreenWorkTrendLoading}>
          <div ref={chartRef} className="port-danger-work-trend__chart" />
        </Spin>
      </div>
    </Panel>
  );
}

export default Connect([NS_BI_STATISTICS], true)(WorkTrendPanel);
