import React, { forwardRef, useMemo } from 'react';
import ECharts from './ECharts';
import propTypes from 'prop-types';
import _ from 'lodash';

// 基础柱状图
const isCategory = (category) => category !== undefined;
const isArea = (lineType) => lineType === 'area';
const LineChart = forwardRef(({ category, lineType, smooth, dataSource }, ref) => {
  const option = useMemo(() => {
    const xAxis = isCategory(category)
      ? {
          type: 'category',
          data: category,
        }
      : {
          type: 'time',
        };
    const hasUnitItem = dataSource.find((item) => item.unit);
    const yAxis = !!hasUnitItem ? { name: `(${hasUnitItem.unit})` } : {};
    const series = dataSource.map((item, index) => {
      const config = _.omit(item, ['type']);
      const itemStyle = isArea(lineType)
        ? {
            areaStyle: {},
          }
        : {};
      return {
        type: 'line',
        smooth,
        ...itemStyle,
        ...config,
      };
    });
    return { xAxis, yAxis, series };
  }, [category, smooth, lineType, dataSource]);

  return <ECharts ref={ref} option={option} />;
});

LineChart.PropTypes = {
  smooth: propTypes.boolean,
  lineType: propTypes.oneOf(['line', 'area']),
  category: propTypes.array,
  dataSource: propTypes.objectOf({
    name: propTypes.string,
    data: propTypes.array,
    unit: propTypes.unit,
  }),
};
LineChart.defaultProps = {
  smooth: true,
  lineType: 'line',
};

export default LineChart;