import * as React from 'react';
import { ID, ICell, IRow, ICellNN } from '../index.data';
import styles from './index.less';
import RowIndicator from '../indicators/RowIndicator';
import Cell from '../Cell';
import { isTreeRow } from '../store/selectors';
import classnames from 'classnames';
import { shallowEqualsArray } from 'valor-app-utils';
import equals from 'fast-deep-equal';
import RuntimeContext from '../RuntimeContext';

interface Props {
  id: ID;
  i: number;
  hidden: boolean;
  // skip: boolean;
  cells: ICell[];
  row: IRow;
  setCellData: (data: Partial<ICellNN> & { id: ID }) => any;
  loadableColumnFlags: boolean[];
}

class Row extends React.Component<Props> {
  context!: React.ContextType<typeof RuntimeContext>;
  static contextType = RuntimeContext;

  constructor(props: Props) {
    super(props);
  }

  shouldComponentUpdate(nextProps: Props) {
    const props1 = nextProps;
    const props2 = this.props;
    const isEquals =
      shallowEqualsArray(props1.cells, props2.cells) &&
      (props1.row === props2.row || equals(props1.row, props2.row)) &&
      equals(props1.loadableColumnFlags, props2.loadableColumnFlags) &&
      props1.hidden === props2.hidden;
    return !isEquals;
  }

  render() {
    // console.log(`Row render`);
    const props = this.props;
    const { store } = this.context!;

    const { id, hidden, row, cells, i, loadableColumnFlags } = props;

    // if (props.skip) return null;
    const state = store.getState();

    const { treeContext } = state;
    // 同上
    const level = isTreeRow(row) ? treeContext[row.id].level : -1;

    return (
      <tr
        id={`row:${id}`}
        key={id}
        style={{ display: hidden ? 'none' : 'table-row' }}
        className={classnames({
          [styles['level1']]: level === 1 && row.type === 'body' && row.area === 'tree',
          [styles['level2']]: level === 2 && row.type === 'body' && row.area === 'tree',
        })}
      >
        <RowIndicator rowId={id} i={i} />
        {cells.map((cell, j) => (
          <Cell
            key={cell!.id}
            store={store}
            row={row}
            cell={cell}
            setCellData={props.setCellData}
            hidden={!loadableColumnFlags[j]}
          />
        ))}
      </tr>
    );
  }
}

export default Row;
