import React from 'react';
import { AutoSizer, List } from 'react-virtualized';
import { debounce } from 'lodash';
import './index.less';

export default class ListView extends React.Component {
  constructor(props) {
    super(props);
    this.listRef = React.createRef();
    this.debounced = null;
  }
  componentWillUnmount() {
    this.debounced && this.debounced.cancel();
    this.listRef = null;
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data && nextProps.data.length === this.props.data.length) {
      this.forceUpdateGrid();
    }
  }
  forceUpdateGrid = () => {
    this.debounced && this.debounced.cancel();
    this.debounced = debounce(() => this.listRef.current.forceUpdateGrid(), 200);
    this.debounced();
  };

  // 渲染列表项
  rowRender = ({ key, index, style }) => {
    const { data, renderItem } = this.props;
    const item = data[index];
    return (
      <div key={key} style={style}>
        {renderItem(item, index)}
      </div>
    );
  };

  render() {
    const { data = [], rowHeight = 30, className = '', rowRenderer } = this.props;
    return (
      <AutoSizer className={`lm-c-simple-list-layout ${className}`}>
        {({ width, height }) => <List width={width} height={height} rowCount={data.length} rowHeight={rowHeight} rowRenderer={rowRenderer ? rowRenderer : this.rowRender} ref={this.listRef} />}
      </AutoSizer>
    );
  }
}
