import React from 'react'
import classnames from 'classnames'
import Article from '../Article'
import './index.css'

export default class ArticleGrid extends React.PureComponent {
  static defaultProps = {
    searchKey: ''
  }
  constructor(props) {
    super(props)
    const { articleList, en } = this.props

    const articles = articleList.filter((a) =>
      { 
        if(a.hide) return false
        return en === null ? '' : en ? a.abstractEN : a.abstract
      }
    )
    const showMoreBtn = articles.length > 6
    this.state = {
      num: showMoreBtn ? 6 : articles.length,
      showMoreBtn,
      articles
    }
    this.loadMore = this.loadMore.bind(this)
  }
  // getLength(en, articleList) {
  //   return articleList
  //     .filter((a) => (en === null ? '' :  en ? a.abstractEN : ab.abstract))
  //     .reduce((sum, _) => sum + 1)
  // }
  componentWillReceiveProps(nextProps) {
    if (
      nextProps.articleList.length !== this.props.articleList.length ||
      nextProps.en !== this.props.en
    ) {
      const articles = nextProps.articleList.filter((a) =>
      { 
        if(a.hide) return false
        return nextProps.en === null ? '' : nextProps.en ? a.abstractEN : a.abstract
      }
      )
      const showMoreBtn = articles.length > 6
      this.setState({
        num: showMoreBtn ? 6 : articles.length,
        showMoreBtn,
        articles
      })
    }
  }
  loadMore() {
    const nextNum = this.state.num + 6
    this.setState({
      num: nextNum,
      showMoreBtn: nextNum < this.state.articles.length
    })
  }
  render() {
    const { en, type, className, searchKey } = this.props
    const { num, showMoreBtn, articles } = this.state
    return (
      <React.Fragment>
        <div
          className={classnames({
            'article-grid-wrapper': true,
            [className]: !!className
          })}
        >
          {articles.slice(0, num).map((n) => {
            const key = n.createDate.replace(/[^\d]/g, '')
            return (
              <Article key={key + searchKey} en={en} article={n} type={type} />
            )
          })}
        </div>
        {showMoreBtn && (
          <div className="article-grid-load-more" onClick={this.loadMore}>
            {en === null ? '' : en ? 'Load More' : '加载更多'}
          </div>
        )}
      </React.Fragment>
    )
  }
}
