import React from "react";
import { TableAddon, TableColumn } from "../TableProps";

/**
 * `mergeable` 插件用于合并单元格。
 */
export interface MergeableOptions<Record = any> {
  headColSpan?: (
    columnIndex: number,
    context: { column: TableColumn<Record> }
  ) => number;

  colSpan?: (
    columnIndex: number,
    recordIndex: number,
    context: {
      column: TableColumn<Record>;
      record: Record;
      rowKey: string;
    }
  ) => number;

  rowSpan?: (
    columnIndex: number,
    recordIndex: number,
    context: {
      column: TableColumn<Record>;
      record: Record;
      rowKey: string;
    }
  ) => number;
}

export function mergeable({
  headColSpan = () => undefined,
  colSpan: bodyColSpan = () => undefined,
  rowSpan: bodyRowSpan = () => undefined,
}: MergeableOptions): TableAddon {
  return {
    getInfo: () => ({ name: "mergeable" }),
    onInjectColumn: previous => (
      record,
      rowKey,
      recordIndex,
      column,
      columnIndex
    ) => {
      const { props: prevProps, ...result } = previous(
        record,
        rowKey,
        recordIndex,
        column,
        columnIndex
      );

      let colSpan;
      let rowSpan;
      if (recordIndex === -1) {
        const col = headColSpan(columnIndex, { column });
        colSpan = typeof col === "number" ? col : undefined;
      } else {
        const col = bodyColSpan(columnIndex, recordIndex, {
          record,
          rowKey,
          column,
        });
        const row = bodyRowSpan(columnIndex, recordIndex, {
          record,
          rowKey,
          column,
        });
        colSpan = typeof col === "number" ? col : undefined;
        rowSpan = typeof row === "number" ? row : undefined;
      }

      const props = {
        ...prevProps,
        colSpan,
        rowSpan,
      };

      return { ...result, props };
    },
  };
}
