import { observer } from 'mobx-react';
import { DualAxes } from '@ant-design/plots';
import { merge, pick, cloneDeep } from '../utils/commons';
import { dataFieldAlias } from '../libs/ht';

const uniqueByKey = (array, key, pickLast) => {
  const seen = new Map();
  const isPickLast = pickLast === true;

  return array.filter(item => {
    const k = item[key];
    const storedItem = seen.get(k);

    if(storedItem) {
      if(isPickLast) {
        seen.set(k, item); // update with last item
      }
      return false;
    }

    seen.set(k, item);
    return true;
  });
};

export default observer((props) => {
  const { config, dataSource, ...extProps } = props;
  const kpiKey = dataFieldAlias[config.yField]?.nestkey?.v;
  const _data = uniqueByKey(dataSource, config.xField, true); // debug:
  const mergeConfig = merge(
    //   color: ['#1979C9', '#F4664A', '#FAAD14'],

    // padding: 'auto',
    // xField: 'groupDateVal',
    // yField: 'SumML',
    // seriesField: 'groupsLabel',
    {
      ...pick(config, ['padding', 'xField', 'seriesField']),
      yField: [config.yField, kpiKey],
      legend: false,
      xAxis: {
        type: 'cat',
      },
      meta: { ...cloneDeep(dataFieldAlias) },
      geometryOptions: [
        {
          geometry: 'line',
          smooth: true,
          point: {
            size: 4,
            shape: 'cicle',
          },
        },
        {
          geometry: 'line',
          smooth: true,
          point: {
            size: 4,
            shape: 'cicle',
          },
          lineStyle: {
            lineWidth: 1,
            lineDash: [5, 5],
          },
          color: '#F4664A',
        },
      ],
    }
  );
  return <DualAxes {...mergeConfig} data={[_data, _data]} />;
});
