import React, { Component } from 'react';
import classnames from 'classnames';
import { http } from '@/utils';
import './nav.scss';

class TreasureNav extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isFixed: false,
      curIndex: 0,
      formatNavs: [],
      navs: [
        {
          id: 'year-live',
          name: '大咖直播'
        },
        {
          id: 'year-treasure',
          name: '组队开宝箱'
        },
        {
          id: 'year-course',
          name: '重磅好课'
        },
        {
          id: 'year-free',
          name: '免费学'
        },
        {
          id: 'year-group',
          name: '1分拼团'
        },
        {
          id: 'year-discount',
          name: '抄底专区'
        },
      ]
    };
  }

  componentDidMount() {
    window.addEventListener('scroll', this.calcNavActive)
  }

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

  componentWillReceiveProps(nextProps) {
    this.initNav(nextProps.treasure_stage,nextProps.activeStage);
  }

  initNav = (treasure_stage,activeStage) => {
    let {navs} = this.state;
    // treasure_stage，宝箱阶段，0-不在活动时间，1-活动时间内
    let data = this.state.navs
    if(treasure_stage === 0) {
      data = navs.filter(item => item.id !== 'year-treasure')
    }
    if(activeStage === 3) {
      data = data.filter(item => item.id !== 'year-free')
    }
    this.setState({
      formatNavs: data
    })
  }

  calcNavActive = () => {
    const { formatNavs } = this.state;
    const { id } = this.props;
    const bannerEl = document.querySelector(`#${id}`);
    setTimeout(() => {
      let y = window.scrollY,
        len = formatNavs.length - 1;
      this.setState({
        isFixed: y >= bannerEl.offsetHeight
      });
      for (; len > -1; len--) {
        let el = document.querySelector(`#${formatNavs[len].id}`);
        if (el && (y + 200) >= el.offsetTop) {
          this.setState({
            curIndex: len
          })
          break;
        }
      }
    }, 100);
  }

  selectToNav = (i) => {
    const { formatNavs } = this.state;
    const id = `#${formatNavs[i]['id']}`;
    let el = document.querySelector(id);
    if(el) {
      this.setState({
        curIndex: i
      });
      window.scrollTo({
        top: el.offsetTop,
        left: 0
      });
    }
  }

  render() {
    const { isFixed, curIndex, formatNavs } = this.state;
    return (
      <div className={classnames("treasure-nav", {'fixed': isFixed})} data-skip="nav">
        {
          formatNavs.map((item, index) => (
            <a
              href={`#${item.id}`}
              className={classnames("treasure-nav__item", {'active': index === curIndex})}
              key={item.id}
              onClick={() => this.selectToNav(index)}
            >{item.name}</a>
          ))
        }
      </div>
    )
  }
}

export default TreasureNav;