import { observer } from 'mobx-react';
import { Line } from '@ant-design/plots';
import { merge, isEmpty } 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 { dataSource, ...config } = props;
  const kpiKey = dataFieldAlias[config.yField]?.nestkey?.v;
  const _data = dataSource.reduce((r, v) => {
    r.push(v);
    if ( ! isEmpty(v[kpiKey])) { // 有设目标才多显示一条虚线 颜色: #F4664A
      r.push({...v, [config.yField]: v[kpiKey], [config.seriesField]: dataFieldAlias[kpiKey].label, extraLine: true,});
    }
    return r;
  }, []);
  const mergeLineConfig = merge({
    color: ['#598cf3', '#F4664A', '#FAAD14'],
    lineStyle: (data) => {
      // console.log(data);
      if (data[config.seriesField].includes('目标')) {
        return {
          lineDash: [4, 4],
          opacity: 0.5,
        };
      }

      return {
        opacity: 1,
      };
    },
  }, config);
  return <Line {...mergeLineConfig} data={_data} />;
});
