import React, { useEffect, useMemo, useState,useRef } from 'react';
import { BasicChart } from '@wisdom-components/basicchart';
import { reportService } from '../../../api';
import styles from './index.less';
import { returnFields, returnOptionsArr } from '../../utils/handleOption';

const ChartComponent = (props) => {
  const [columnsData, setColumnsData] = useState([]);
  const [options, setOptions] = useState([]);
  const { reportName, chartOptions, reportData } = props;
  const chartRef = useRef();

  const getData = () => {
    let columns = returnFields(JSON.stringify(chartOptions));
    if (!columns.length) return ''; //
    reportService.getChartConfigDataByColumn({
      reportName,
      columns,
    }).then(res => {
      let _data = [];
      if (res.code === 0) _data = res.data.data;
      setColumnsData(_data);
    });
  };
  useEffect(() => {
    getData();
  }, []);
  useEffect(() => {
    let _options = returnOptionsArr(chartOptions, columnsData, reportData.selectedRows);
    setOptions(_options);
  }, [columnsData, reportData.selectedRows.length]);
  const resizeChart = () => {
    chartRef.current.resize();
  };
  useEffect(() => {
    window.addEventListener('resize', resizeChart);
    return () => window.removeEventListener('resize', resizeChart);
  }, []);
  return <div className={styles.chartWrapper}>
    {
      options.map((option, index) => <div className={styles.chart} style={{ ...option.custom_style }}>
        <BasicChart ref={chartRef} style={{ width: '100%', height: '100%' }} key={`${index}_${option.series.length}`}
                    option={option}/>
      </div>)
    }
  </div>;
};

export default ChartComponent;
