import * as React from 'react';
import { connect } from 'unistore/react';
import { IStoreState, IRow, ID, ICell, ICellNN } from '../index.data';
import { Store } from 'unistore';
import Row from '../Row';
import * as R from 'rambda';
import { shallowEqualsArray } from 'valor-app-utils';
import shallowEqual from 'shallowequal';
import equals from 'fast-deep-equal';
import RuntimeContext from '../RuntimeContext';

/*
interface Props {}
interface MappedProps {
  rows: IRow[];
  loadableRowFlags: boolean[];
  cells: Record<ID, ICell>;
}
*/
interface Props {
  rows: IRow[];
  loadableRowFlags: boolean[];
  loadableColumnFlags: boolean[];
  cells: Record<ID, ICell>;
}

interface MappedActions {}

type AllProps = Props & MappedActions;

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

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

  shouldComponentUpdate(nextProps: AllProps) {
    const props1 = nextProps;
    const props2 = this.props;
    const isEquals =
      shallowEqualsArray(props1.rows, props2.rows) &&
      shallowEqual(props1.cells, props2.cells) &&
      equals(props1.loadableRowFlags, props2.loadableRowFlags) &&
      equals(props1.loadableColumnFlags, props2.loadableColumnFlags);
    return !isEquals;
  }

  setCellData = (data: Partial<ICellNN> & { id: ID }) => {
    const { commands } = this.context!;
    commands.setCellData(data);
  };

  render() {
    // console.log('rowGroup render');
    const props = this.props;
    const { rows, loadableRowFlags, loadableColumnFlags, cells } = props;

    const rowsView = R.filter(Boolean, rows).map((row, i) => {
      const cellIds: ID[] = row ? (row.cellIds!.filter(Boolean) as any) : [];
      cellIds.forEach(cellId => {
        if (!cells[cellId]) console.error('cellId不存在: ', cellId);
      });
      return (
        <Row
          key={row.id}
          id={row.id}
          i={i}
          hidden={!loadableRowFlags[i]}
          cells={cellIds.map(it => cells[it])}
          loadableColumnFlags={loadableColumnFlags}
          row={row}
          setCellData={this.setCellData}
        />
      );
    });
    return <>{rowsView}</>;
  }
}

const mapState = (state: IStoreState, props: Props) => ({});

const actions = (store: Store<IStoreState>) => ({});
export default connect<Props, any, IStoreState, any>(
  mapState,
  actions,
)(RowGroup);
