import React from "react";
import { TableAddon } from "../TableProps";
import { CheckTreeRelation } from "../../checktree";

/**
 * `indentable` 插件用于支持表格缩进样式。
 */
export interface IndentableOptions {
  /**
   * 子级相对父级缩进量
   * @default 20
   */
  indent?: number;

  /**
   * 行的层级关系
   */
  relations?: CheckTreeRelation;

  /**
   * 提供一个列的 `key`，将选择组件插入到一个目标列
   */
  targetColumnKey: string;
}

export function indentable(options: IndentableOptions): TableAddon {
  const { indent = 20, relations, targetColumnKey } = options;

  return {
    getInfo: () => ({ name: "indentable" }),
    onInjectColumn: previous => (
      record,
      rowKey,
      recordIndex,
      column,
      columnIndex
    ) => {
      // 不是目标列
      if (!targetColumnKey || column.key !== targetColumnKey) {
        return previous(record, rowKey, recordIndex, column, columnIndex);
      }

      const { children: preChildren, props, ...result } = previous(
        record,
        rowKey,
        recordIndex,
        column,
        columnIndex
      );

      let children = preChildren;
      // 非表头
      if (recordIndex !== -1) {
        let paddingLeft = 0;
        let depth = 0;
        if (indent > 0) {
          let node = rowKey;
          while (relations && relations[node]) {
            depth += 1;
            node = relations[node];
          }
          paddingLeft = indent * depth;
        }
        children = <div style={{ paddingLeft }}>{children}</div>;
      }
      return { ...result, props, children };
    },
  };
}
