import { useEffect, useRef, useState, useImperativeHandle, forwardRef,memo } from "react";
import { Button, Modal, Image, Space, Empty,Tag } from "antd";
import Flex from "@/components/Flex";
import * as echarts from "echarts";
import "./index.less";

let chartInstance = null;

const Echart = ({
  data = {},
  type = "line",
  hasExport = true,
  hasTable = true,
  limitNum = 0,
  lengButton = [],
  isShow = true,
  onTableClick = () => { },
  text='',
  isNoneTag = false,
  isShowTag = true,
}, ref) => {



  const chartRef = useRef(null);
  const chartInstanceRef = useRef(null); // 新增用于存储图表实例的 ref
  const [selectButton, setSelectButton] = useState(lengButton);
  const [activeButtons, setActiveButtons] = useState([]); // 添加新的状态来跟踪选中的按钮
  const [dataCopy, setDataCopy] = useState(); // 添加新的状态来跟踪选中的按钮
  const [option, setOption] = useState({}); //用于渲染图表的
  const [echartImg, setEchartImg] = useState(); //用于导出图表 图片的



  useImperativeHandle(ref, () => ({
    exportChart,
  }));

  useEffect(() => {

    if (!lengButton?.length) {
      return;
    }
    setSelectButton(lengButton);
    if(isNoneTag){
      setActiveButtons(lengButton);
    }else{
      setActiveButtons([lengButton[0]]);
    }
    
  }, [lengButton,isNoneTag]);


  //控制筛选按钮
  const toggleButton = (data) => {
    setActiveButtons((prev) => {
      if (prev.includes(data)) {
        // 如果只剩一个按钮，不允许取消选中
        if (prev.length === 1) {
          return prev;
        }
        return prev.filter((i) => i !== data);
      } else {
        // 检查是否达到最大限制
        if (limitNum > 0 && prev.length >= limitNum) {
          // 如果已达到限制，返回原数组
          return prev;
        }
        // 未达到限制，添加新按钮
        return [...prev, data];
      }
    });
  };

  // 处理二维折线和柱状图和饼图
  const createOption = () => {
    let option = {};
    const colors = [
      "#91cc75",
      "#fac858",
      "#ee6666",
      "#73c0de",
      "#3ba272",
      "#fc8452",
      "#9a60b4",
    ];

    if (type === "radar") {
      

      option = {
        color: colors,
        title: {
          // 添加标题配置
          text,
          left: 'center',
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        legend: {
          type: "scroll",
          data: dataCopy?.radarText.yChartData?.map((item) => item.name),
          right: 10,
          top: 16,
          selectedMode: false,
        },
        tooltip: {
          trigger: "item",
        },
        radar: {
          indicator: dataCopy.radarText.indicator,
          shape: "polygon",
          splitNumber: 5,
          axisName: {
            color: "#666",
            fontSize: 10,
          },
          splitLine: {
            lineStyle: {
              color: "rgba(238, 238, 238, 0.8)",
              opacity: 0.2
            },
          },
          splitArea: {
            show: false, // 关闭区域填充
          },
        },
        series: [
          {
            type: "radar",
            data: dataCopy?.radarText?.yChartData?.map((item, index) => ({
              name: item.name,
              value: item.data,
              itemStyle: {
                color: colors[index % colors.length],
              },
              lineStyle: {
                width: 2,
                color: colors[index % colors.length], // 设置线条颜色
              },
              // 移除 areaStyle 配置
              emphasis: {
                lineStyle: {
                  width: 4,
                },
              },
            })),
          },
        ],
      };
    } else if (type == "pie") {
      // 计算总数
      const totalSum = dataCopy?.yChartData?.reduce((sum, item) => {
        return sum + item.data.reduce((a, b) => a + b, 0);
      }, 0);

      option = {
        title: {
          // 添加标题配置
          text,
          left: 'center',
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          // 简化图例数据处理
          data:
            dataCopy?.yChartData?.map((item) => ({
              name: item.name,
              icon: "circle", // 设置图例图标为圆形
            })) || [],
          right: "18%",
          top: 16,
          selectedMode: true,
          textStyle: {
            color: "#333",
            fontSize: 12,
          },
          formatter: (name) => {
            const data = dataCopy?.yChartData?.find(
              (item) => item.name === name
            );
            if (!data) return name;
            return `${name}${data?.data?.[0]}%`;
          },
        },
        tooltip: {
          trigger: "item",
          formatter: "{b}:{c}%",
        },
        series: [
          {
            radius: ["40%", "70%"],
            type: type,
            label: {
              show: true,
              formatter: (name) => {
                return `${name?.data?.name}${name?.data?.value}%`
              },
            },
            data:
              dataCopy?.yChartData?.map((key) => {
                return {
                  name: key.name,
                  value: key?.data?.[0],
                };
              }) || [],
          },
        ],
      };
    } else {
      option = {
        //图例 不用 纯展示
        legend: {
          type: "scroll",
          data: dataCopy?.yChartData?.map((item) => item.name),
          right: 10, // 设置右侧边距
          top: 24, // 设置顶部边距
          selectedMode: false,
          textStyle:{
            fontSize:12
          }
        },
        title: {
          // 添加标题配置
          text,
          left: 'center',
          top: 0,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        label:{
          show: true,
          position: 'top',
          distance: 12,
          align: 'center',
          verticalAlign: 'middle',
          formatter: (params) => {
              return `${params.value}`
          },
          fontSize: 10,
          rich: {
              name: {}
          }
      },
        // dataZoom: [
        //   {
        //     type: 'slider', // 滑动条型数据区域缩放组件
        //     show: true,
        //     start: 0, // 初始起点
        //     end: 30, // 初始终点
        //     handleSize: 8,
        //     xAxisIndex: [0],
        //     height: 24
        //   },
        // ],
        axisLabel: {
          rotate: 35,
          interval: 0,
          fontSize: 9,
          autoSkip: true,
        },
        barGap: '16%',
        barWidth: "8%",
        // 布局
        grid: {
          left: "16px", // 左边距
          right: "4%", // 右边距
          bottom: "48px", // 底部边距，留出空间显示 x 轴标签
          top: "88px", // 顶部边距
          containLabel: true, // 确保刻度标签在区域内
        },
        tooltip: {
          show: true,
        },
        ...dataCopy,
        xAxis: {
          ...dataCopy?.xAxis,
          axisLabel: {
            rotate: dataCopy?.xAxis?.data?.length > 6 ? 45 : 0,
            interval: 0,
            textStyle: {
              fontSize: 12,
            }
          },
          nameTextStyle: {
            fontSize: 16,
          }
        },
        yAxis:{
          ...dataCopy?.yAxis,
          axisLabel: {
            textStyle: {
              fontSize: 14,
            }
          },
          nameTextStyle: {
            fontSize:14,
          }
        },
        series: dataCopy?.yChartData?.map((item) => ({
          type,
          // barGap: 0,
          barWidth: '8%', // 控制柱子的宽度
          barGap: '10%'  ,  // 控制柱子之间的间距
          emphasis: {
            focus: "series",
          },
          name: item.name,
          data: item.data
        })),
      };
    }

    setOption(option);
  };

  //下载图片
  const downloadImg = () => {
    const link = document.createElement("a");
    link.download = `图表_${new Date().getTime()}.png`;
    link.href = echartImg;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setEchartImg("");
  };
  // 导出图片
  const exportChart = () => {
    const chartInstance = echarts.getInstanceByDom(chartRef.current);
    if (chartInstance) {
      const base64 = chartInstance.getDataURL({
        type: "png",
        pixelRatio: 2, // 导出的图片分辨率比例
        backgroundColor: "#fff", // 导出图片的背景色
      });

      setEchartImg(base64);
    }
  };

  useEffect(() => {
    if (dataCopy) {
      createOption();
    }
  }, [dataCopy, activeButtons]);

  // useEffect(() => {
  //   setSelectButton(lengButton);
  // }, [lengButton]);

  useEffect(() => {
    if (!activeButtons.length > 0) {
      return;
    }
    // 根据选中的按钮筛选数据
    let filteredData = [];
    if (type === "radar") {
      filteredData = data?.radarText?.yChartData?.filter((item) =>
        activeButtons.includes(item.name)
      );
      setDataCopy({
        ...data,
        radarText: {
          ...data.radarText,
          yChartData: filteredData,
        },
      });
    } else {
      if(type === 'pie'){
        setDataCopy({ ...data});
        return;
      }
      filteredData = data?.yChartData?.filter((item) =>
        activeButtons.includes(item.name)
      );

      setDataCopy({ ...data, yChartData: filteredData });
    }
  }, [activeButtons, data]);

  //图表初始化
  useEffect(() => {
    // 如果 DOM 元素存在，初始化图表
    if (chartRef.current) {
      // 如果已有实例，先销毁
      if (chartInstanceRef.current) {
        chartInstanceRef.current.dispose();
      }

      // 创建新实例
      chartInstanceRef.current = echarts.init(chartRef.current);

      if (Object.values(option)?.length) {
        chartInstanceRef.current?.setOption(option);
      }
    }
    // 响应式调整
    const resizeHandler = () => chartInstanceRef.current?.resize();
    window.addEventListener('resize', resizeHandler);


    // 组件卸载时清理
    return () => {
      if (chartInstanceRef.current) {
        window.removeEventListener('resize', resizeHandler);
        chartInstanceRef.current.dispose();
        chartInstanceRef.current = null;
      }
    };
  }, [option]);

  return (
    <div style={{ marginBottom: 20 }}>
      {isShowTag ? (
        <Space style={{marginBottom: 16}} wrap>
        {!!Array.isArray(selectButton) &&
          isShow &&
          !!selectButton.length > 0 &&
          selectButton.map((but, index) => {
            return (
              <Tag
                key={index}
                color={activeButtons.includes(but) ? "green" : "default"}
                onClick={() => toggleButton(but)}
                style={{cursor: 'pointer'}}
              >
                {but}
              </Tag>

            );
          })}
      </Space>
      ) : null}
      {/* 图表 */}
      {lengButton?.length > 0 ? (<div ref={chartRef} style={{ width: "100%", height: "446px" }} />) : <Empty description='暂无图表数据' />}
      {/* 导出和显示为表格 */}
      <div>
        {hasExport && (
          <Button
            type="primary"
            style={{ marginRight: 20 }}
            disabled={!lengButton?.length}
            onClick={exportChart}
          >
            导出图表
          </Button>
        )}
        {hasTable && (
          <Button
            type="primary"
            onClick={() => {
              //关闭图表
              onTableClick(false);
            }}
          >
            显示为表格
          </Button>
        )}
      </div>
      {/* 导出为图片 */}
      {echartImg && (
        <Modal
          title="导出图表"
          className="custom-modal"
          width={"80vw"}
          open={true}
          okText="下载"
          onCancel={() => {
            setEchartImg("");
          }}
          onOk={downloadImg}
        >
          <Flex style={{ height: "100%" }} alignItems="center" justify="center">
            <Image src={echartImg} width={"100%"} />
          </Flex>
        </Modal>
      )}
    </div>
  );
};

export default memo(forwardRef(Echart));
