/**
 * 原版报表功能，支持报表展示；
 * 当前功能，配置了图表，则暂时报表+图表；否则只展示报表
 * @Steps
 * 1. 获取图表配置
 * */
import React, { useEffect, useRef, useState } from 'react';
import ChartComponent from '../ReportWithChart/ChartComponent';
import LayOutComponent from '../ReportWithChart/ChartComponent';
import ReportsManage from '../../ReportsManage/ReportsManage';
import { reportService } from '../../api';
import { isString } from 'lodash';

const ReportWithChart = (props) => {
  const { reportName, config } = props.params;
  const [layoutOptions, setLayoutOptions] = useState(null);
  const [chartOptions, setChartOptions] = useState(null);
  const [reportData, setReportData] = useState(null);
  const reportRef = useRef(null);
  const getChartConfig = () => {
    return reportService.getChartConfig({
      reportName,
    });
  };
  const trigger = (str) => {
    let _data = reportRef?.current?.getData();
    setReportData(_data);
  };
  useEffect(() => {
    async function _getData() {
      let _layoutOptions = null;
      let _chartOptions = null;
      if (config && isString(config)) {
        let _str = JSON.parse(config);
        _layoutOptions = _str.layoutOptions;
        _chartOptions = _str.chartOptions;
      } else {
        let _config = await getChartConfig();
        let _str = JSON.parse(_config.data.configInfo);
        _layoutOptions = _str.layoutOptions;
        _chartOptions = _str.chartOptions;
      }
      setLayoutOptions(_layoutOptions);
      setChartOptions(_chartOptions);
    }
    _getData();
  }, [config]);
  return <>{layoutOptions && chartOptions ? <LayOutComponent layoutOptions={layoutOptions}>
    <ReportsManage key={'table'} {...props} ref={reportRef} trigger={trigger}/>
    <ChartComponent key={'chart'} reportName={reportName} chartOptions={chartOptions} reportData={reportData}/>
  </LayOutComponent> : <ReportsManage {...props} ref={reportRef} trigger={trigger}/>
  }</>;
};
export default ReportWithChart;
