import React, { Component } from 'react'
import classnames from 'classnames'
import Link from 'next/link'
import OverflowBox from 'overflowbox'
import newsPage from '../content/newsPage.md'
import newsList from '../content/newsList.md'
import { ThemeContext } from './_app.js'
import Header from '../components/Header'
import Footer from '../components/Footer'
import { Title } from '../components/Title'
import ArticleGrid from '../components/ArticleGrid'

import { yymmdd } from '../utils/date'

import './news.css'

const getHighLight = (news) => {
  let newsNew = []
  let highLight = null
  let hasHighLight = false
  news.map((v) => {
    if (!hasHighLight && v.highLight) {
      hasHighLight = true
      highLight = v
      return
    }
    newsNew.push(v)
  })
  if (!highLight) {
    highLight = newsNew.shift()
  }
  return [highLight, newsNew]
}
export default class NewsPage extends Component {
  constructor(props) {
    super(props)
    this.renderHighLight = this.renderHighLight.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.handleWindowResize = this.handleWindowResize.bind(this)
    this.key = 0
    const {
      attributes: { news }
    } = newsList
    const [highLight, newsNew] = getHighLight(news)
    this.state = {
      isSearch: false,
      searchRes: [],
      mounted: false,
      mobile: true,
      highLight,
      newsNew
    }
  }
  componentDidMount() {
    this.handleWindowResize()
    window.addEventListener('resize', this.handleWindowResize)
    this.setState({
      mounted: true
    })
  }
  componentWillUnmount() {
    window.removeEventListener('resize', this.handleWindowResize)
  }
  handleWindowResize() {
    this.setState({
      mobile: document.body.offsetWidth < 780
    })
  }

  renderHighLight(en) {
    const { mounted, highLight, mobile } = this.state
    const key = highLight.createDate.replace(/[^\d]/g, '')
    return (
      <Link prefetch={false} href={`/post.html?t=news&d=${key}`}>
        <a className="linka">
          <div className="high-light">
            <div
              className="high-light-pic"
              style={{
                backgroundImage: mounted ? `url("${highLight.pic}")` : 'none'
              }}
            ></div>
            <div className="high-light-text">
              <div className="high-light-title">
                {en === null ? '' : en ? highLight.titleEN : highLight.title}
              </div>
              <div className="high-light-abstract">
                <OverflowBox
                  str={(en === null
                    ? ''
                    : en
                    ? highLight.abstractEN
                    : highLight.abstract
                  ).replace(/\n/g, '')}
                />
              </div>
              <div className="high-light-footer">
                {!en && highLight.source && (
                  <span className="high-light-source">{highLight.source}</span>
                )}
                {en && highLight.sourceEN && (
                  <span className="high-light-source">
                    {highLight.sourceEN}
                  </span>
                )}
                {!mobile && (
                  <span className="high-light-date">
                    {yymmdd(new Date(highLight.createDate)).join('/')}
                  </span>
                )}
              </div>
            </div>
          </div>
        </a>
      </Link>
    )
  }

  handleSearch(e, en) {
    const {
      attributes: { news }
    } = newsList
    clearTimeout(this.searchTimer)
    const s = this.input.value.toLowerCase()
    this.searchTimer = setTimeout(() => {
      this.setState({
        searchRes: news.filter((n) => {
          if (en) {
            if (!n.titleEN) {
              return false
            }
            return (
              n.titleEN.toLowerCase().indexOf(s) !== -1 ||
              n.contentEN.toLowerCase().indexOf(s) !== -1
            )
          }
          return (
            n.title.toLowerCase().indexOf(s) !== -1 ||
            n.content.toLowerCase().indexOf(s) !== -1
          )
        }),
        isSearch: this.input.value !== ''
      })
    }, 200)
  }
  render() {
    const {
      attributes: { title, titleEN, searchPlaceholder, searchPlaceholderEN }
    } = newsPage
    const { isSearch, newsNew, searchRes } = this.state
    return (
      <ThemeContext.Consumer>
        {(val) => {
          const { en } = val
          return (
            <div
              className={classnames({
                en,
                zh: !en
              })}
            >
              <Header en={en} curPage="news"></Header>
              <div className="news-top two-column limitw">
                <Title en={en}>{en === null ? '' : en ? titleEN : title}</Title>
                <div className="news-search-wrapper">
                  <div className="news-search-img"></div>
                  <input
                    ref={(input) => (this.input = input)}
                    onChange={(e) => this.handleSearch(e, en)}
                    placeholder={
                      en === null
                        ? ''
                        : en
                        ? searchPlaceholderEN
                        : searchPlaceholder
                    }
                  ></input>
                </div>
              </div>
              <div className="news-list-grid">
                <div className="left-bg"></div>
                {isSearch ? (
                  <div className="limitw">
                    <div className="news-search-count">
                      搜索
                      <span className="news-search-content">
                        {this.input.value}
                      </span>
                      {searchRes.length > 0 ? (
                        <span>
                          找到
                          <span className="news-search-num">
                            {searchRes.length}
                          </span>
                          个结果
                        </span>
                      ) : (
                        '没有找到结果'
                      )}
                    </div>
                    <ArticleGrid
                      en={en}
                      searchKey={this.input.value.toLowerCase()}
                      articleList={searchRes}
                      type="news"
                    />
                  </div>
                ) : (
                  <div className="limitw">
                    {this.renderHighLight(en)}
                    <ArticleGrid en={en} articleList={newsNew} type="news" />
                  </div>
                )}
              </div>
              <Footer />
            </div>
          )
        }}
      </ThemeContext.Consumer>
    )
  }
}
