import React, { useMemo } from 'react';
import Filter from './button-row'

export interface IChartData {
  filter: string | number;
    filterName: string;
    percent?: boolean;
    type: string | number;
    [key: string]: any;
}
interface IProps {
  multiple: boolean;
  value: (string | number)[];
  data: IChartData[];
  onChangeValue: (value: (string | number)[]) => void;
}

export default ({ multiple, value, onChangeValue, ...rest}: IProps) => {
  // 从数据中拿出筛选选项和Map信息
  const filterInfo = useMemo(() => {
    const result = new Set();
    const map: any = {};
    const percentMap: any = {};
    if (rest.data) {
      rest.data.forEach(data => {
        result.add(data.filter);
        map[data.filter] = data.filterName;
        percentMap[data.filter] = Boolean(data.percent);
      });
    }
    const arr = [...result] as string[];
    // 设置默认选中的值
    if (arr?.[0]) {
      onChangeValue([arr[0]]);
    }
    return {
      options: arr,
      map,
      percentMap
    };
  }, [rest.data]);

  return (
    <Filter value={value} options={filterInfo.options} map={filterInfo.map} onClick={(selected) => {
      const activeIndex = value.findIndex(item => selected === item);
      if (activeIndex > -1) {
        value.splice(activeIndex, 1)
      } else {
        if (multiple) {
          value.push(selected)
        } else {
          value[0] = selected
        }
      }
      onChangeValue(value.slice(0));
    }} />
  );
};
