import React from "react";
import { TableAddon } from "../../TableProps";
import { FilterableConfig } from "./FilterableTypes";
import { MultipleFilterButton } from "./MultiFilterButton";
import { SingleFilterButton } from "./SingleFilterButton";

export function filterable(config: FilterableConfig): TableAddon {
  return {
    getInfo: () => ({ name: "filterable" }),
    onInjectColumn: renderColumn => (
      record,
      rowKey,
      recordIndex,
      column,
      columnIndex
    ) => {
      const columnResult = renderColumn(
        record,
        rowKey,
        recordIndex,
        column,
        columnIndex
      );

      // recordIndex > -1 是记录行，我们只注入表头
      if (recordIndex > -1) {
        return columnResult;
      }

      // 不是目标列
      if (column.key !== config.column) {
        return columnResult;
      }

      let { children } = columnResult;
      if (config.type === "single") {
        children = (
          <SingleFilterButton {...config}>{children}</SingleFilterButton>
        );
      } else if (config.type === "multiple") {
        children = (
          <MultipleFilterButton {...config}>{children}</MultipleFilterButton>
        );
      }

      return { ...columnResult, children };
    },
  };
}
