/* eslint babel/new-cap: 0 */
import React, { Component } from 'react';
import { withRouter, Link } from 'react-router';
import { getReactMaterials, getVueMaterials } from '../../service/database';
import IceLoading from '@ali/ice-loading';
import cx from 'classnames';
import { join } from 'path';
import List from './List';
import './BlockList.scss';

const appRoutePrefix = window.routePrefix;
const pageSize = 36;

@withRouter
export default class BlockContainer extends Component {
  static displayName = 'BlockContainer';

  state = {
    categories: [],
    loading: true,
    currentPage: 0,
    hasMore: true,
    loadMore: false,
  };

  updateType(props = this.props) {
    const { location } = props;
    this.type = location.query.type || 'react';
  }

  /**
   * 抽取 blocks 列表中所有的 category 名
   * @param {Array} blocks
   */
  pluckCategories(blocks) {
    const unique = {};
    if (Array.isArray(blocks)) {
      for (let i = 0, l = blocks.length; i < l; i++) {
        const { categories } = blocks[i];
        categories &&
          categories.forEach &&
          categories.forEach((catName) => {
            if (!(catName in unique)) {
              unique[catName] = 1;
            } else {
              unique[catName]++;
            }
          });
      }
    }

    return unique;
  }

  /**
   * 从一堆 block 里面筛选
   */
  filterBlocks(blocks, { page, category }) {
    return blocks
      .filter(({ categories }) => {
        if (undefined === category || !Array.isArray(categories)) {
          return true;
        }
        return categories.includes(category);
      })
      .slice(page * pageSize, (page + 1) * pageSize);
  }

  async componentDidMount() {
    window.addEventListener('scroll', this.scrollListener);
    this.updateType();

    const { currentPage } = this.state;
    this.category = this.props.router.location.query.category;

    const materials = await (this.type === 'vue'
      ? getVueMaterials
      : getReactMaterials)();

    const categories = this.pluckCategories(materials.blocks);
    const blocks = this.filterBlocks(materials.blocks, {
      page: currentPage,
      category: this.category,
    });

    const hasMore = blocks.length === pageSize;

    // eslint-disable-next-line
    this.setState({
      totalBlocks: materials.blocks,
      categories,
      blocks,
      // currentPage: currentPage + 1,
      loading: false,
      hasMore,
    });
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.scrollListener);
  }

  scrollListener = (evt) => {
    const { loadMore, hasMore } = this.state;
    if (loadMore || !hasMore) {
      return;
    }
    if (
      window.pageYOffset + window.innerHeight >=
      document.documentElement.scrollHeight - 100
    ) {
      this.setState({ loadMore: true });
      // 为了展示加载中效果
      setTimeout(() => {
        Promise.resolve(this.loadMore());
      }, 500);
    }
  };

  loadMore = async () => {
    const { currentPage } = this.state;

    this.category = this.props.router.location.query.category;

    const materials = await (this.type === 'vue'
      ? getVueMaterials
      : getReactMaterials)();

    const categories = this.pluckCategories(materials.blocks);
    const blocks = this.filterBlocks(materials.blocks, {
      page: currentPage + 1,
      category: this.category,
    });
    console.log(blocks, currentPage);

    const hasMore = blocks.length === pageSize;

    // eslint-disable-next-line
    this.setState({
      currentPage: currentPage + 1,
      blocks: [...this.state.blocks, ...blocks],
      hasMore,
      loadMore: false,
    });
  };

  async componentWillReceiveProps(nextProps) {
    if (
      nextProps.router.location.query.category !== this.category ||
      nextProps.router.location.query.type !== this.type
    ) {
      this.category = nextProps.router.location.query.category;

      this.updateType(nextProps);

      const materials = await (this.type === 'vue'
        ? getVueMaterials
        : getReactMaterials)();

      const categories = this.pluckCategories(materials.blocks);
      const blocks = this.filterBlocks(materials.blocks, {
        page: 0,
        category: this.category,
      });

      const hasMore = blocks.length === pageSize;

      this.setState({
        currentPage: 0,
        blocks,
        categories,
        hasMore,
      });
    }
  }

  render() {
    const { router } = this.props;
    let {
      categories,
      blocks = [],
      totalBlocks,
      loading,
      loadMore,
    } = this.state;
    const currentCategory = router.location.query.category;

    if (loading) {
      return (
        <IceLoading
          type="ball-spin-fade-loader"
          color="#1B73FF"
          style={{
            margin: '0 auto',
          }}
        />
      );
    } else {
      return (
        <div className="blocks-content">
          {/* 上层导航 */}
          <ul className="block-categories">
            <li key={-1} className={cx({ active: !currentCategory })}>
              <Link to={join(appRoutePrefix, 'block' + '?type=' + this.type)}>
                全部 {totalBlocks.length}
              </Link>
            </li>
            {Object.keys(categories).map((catName, index) => {
              const item = {
                name: catName,
                total: categories[catName],
              };
              return (
                <li
                  key={index}
                  className={cx({ active: currentCategory === item.name })}
                >
                  <Link
                    to={join(
                      appRoutePrefix,
                      `block?category=${item.name}&type=${this.type}`
                    )}
                  >
                    {item.description || item.name} {item.total}
                  </Link>
                </li>
              );
            })}
          </ul>

          {/* 列表 */}
          <List dataSource={blocks} materialType={this.type} />

          <div
            style={{
              display: loadMore ? 'block' : 'none',
              textAlign: 'center',
              marginTop: '20px',
            }}
          >
            <div className="block-list-loadmore">
              <img
                src="https://gw.alicdn.com/tfs/TB1BKfiawmTBuNjy1XbXXaMrVXa-62-36.png"
                style={{ width: '31px', height: '18px' }}
              />
              <span style={{ marginLeft: '5px', color: '#333' }}>
                加载更多…
              </span>
            </div>
          </div>
        </div>
      );
    }
  }
}

const styles = {
  weeklyTag: {
    fontSize: '12px',
    padding: '3px 6px',
    backgroundColor: 'rgba(64, 150, 255, 0.85)',
    color: '#fff',
    borderRadius: '10px',
    marginRight: '5px',
  },
};
