import React from 'react'
import marked from 'marked'
import newsPage from '../content/newsPage.md'
import newsList from '../content/newsList.md'
import ronghuiPage from '../content/ronghuiPage.md'
/* eslint-disable no-unused-vars */
import Link from 'next/link'
import Head from 'next/head'
import QRCode from 'qrcode.react'
import { ThemeContext } from './_app.js'
import Header from '../components/Header'
import Footer from '../components/Footer'
import { Title } from '../components/Title'
import ArticleLine from '../components/ArticleLine'
/* eslint-enable no-unused-vars */
import { yymmdd } from '../utils/date'

import './post.css'

export default class PostPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      type: null,
      article: [],
      articleRecommendList: [],
      mounted: false
    }
    this.renderBack = this.renderBack.bind(this)
  }

  componentDidMount() {
    let date = document.location.href.match(/d=[^=&]*/)
    let type = document.location.href.match(/t=[^=&]*/)
    if (!date || date.length === 0 || !type || type.length === 0) {
      return null
    }
    date = date[0].slice(2)
    type = type[0].slice(2)
    const {
      attributes: { news }
    } = newsList

    let ReadArticleList = window.localStorage.getItem('read') || ''
    ReadArticleList = ReadArticleList.split(' ')
    const {
      attributes: { article: articles }
    } = ronghuiPage
    let article = []
    let articleRecommendList = []
    let articleRecommendListBackup = []
    let origin = type === 'news' ? news : articles
    origin.map((n) => {
      const curDate = n.createDate.replace(/[^\d]/g, '')
      if (curDate === date) {
        article.push(n)
        if (ReadArticleList.indexOf(curDate) === -1) {
          this.recordReadTimer = setTimeout(() => {
            window.localStorage.setItem(
              'read',
              ReadArticleList.concat(curDate).join(' ')
            )
          }, 2000)
        }
      } else {
        if (ReadArticleList.indexOf(curDate) === -1) {
          articleRecommendList.push(n)
        }
        articleRecommendListBackup.push(n)
      }
    })
    if (articleRecommendList.length < 2) {
      articleRecommendList = articleRecommendListBackup
    }

    this.setState({
      article,
      articleRecommendList,
      type,
      mounted: true
    })
  }
  componentWillUnmount() {
    clearTimeout(this.recordReadTimer)
  }
  renderBack(en) {
    const { type } = this.state
    let text
    if (type === 'news') {
      const {
        attributes: { allNews, allNewsEN }
      } = newsPage
      text = en === null ? '' : en ? allNewsEN : allNews
    } else if (type === 'article') {
      const {
        attributes: { allArticles, allArticlesEN }
      } = ronghuiPage
      text = en === null ? '' : en ? allArticlesEN : allArticles
    }
    return (
      <Link
        prefetch={false}
        href={{ pathname: type === 'news' ? '/news.html' : '/ronghui.html' }}
      >
        <a className="linka post-back">
          <span className="post-back-img"></span>
          {text}
        </a>
      </Link>
    )
  }
  render() {
    const { article, type, articleRecommendList, mounted } = this.state
    if (!article || !mounted) return null
    if (article.length === 0) {
      return <div>not found</div>
    }
    const post = article[0]
    // console.log(post.content)
    return (
      <ThemeContext.Consumer>
        {(val) => {
          const { en } = val
          return (
            <div className="post-page">
              <Head>
                <title>
                  {en === null ? '' : en ? post.titleEN : post.title}
                </title>
              </Head>
              <Header en={en} curPage="post"></Header>
              <div className="post-outline-wrapper">
                <div className="bg"></div>
                {this.renderBack(en)}
                <div className="post-wrapper">
                  {post.type && (
                    <div className="post-source">
                      {en === null ? '' : en ? post.typeEN : post.type}
                    </div>
                  )}
                  <Title en={en}>
                    {en === null ? '' : en ? post.titleEN : post.title}
                  </Title>
                  <div className="post-dateshare-wrapper">
                    <div className="post-date">
                      {yymmdd(new Date(post.createDate)).join('/')}
                    </div>
                    <div className="post-share-wrapper">
                      <a
                        href={`mailto:?body=${encodeURIComponent(
                          document.location.href
                        )}`}
                      >
                        <div className="post-share-icon post-share-mail"></div>
                      </a>
                      <a
                        target="_blank"
                        href={`http://service.weibo.com/share/share.php?url=${encodeURIComponent(
                          document.location.href
                        )}&title=${
                          en === null ? '' : en ? post.titleEN : post.title
                        }&pic=${encodeURIComponent(
                          `${document.location.host}${post.pic}`
                        )}&searchPic=false&appkey=2421796710`}
                      >
                        <div className="post-share-icon post-share-weibo"></div>
                      </a>
                      <div className="post-share-icon post-share-wechat">
                        <div className="post-share-qrcode">
                          <QRCode value={document.location.href} />
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    className="post-content"
                    dangerouslySetInnerHTML={(() => {
                      switch (en) {
                        case null:
                          return { __html: '' }
                        case true:
                          if (post.contentEN) {
                            return { __html: marked(post.contentEN) }
                          } else {
                            return {
                              __html:
                                'Sorry, English version is not available now.'
                            }
                          }
                        case false:
                          if (post.content) {
                            return { __html: marked(post.content) }
                          } else {
                            return { __html: '暂无内容' }
                          }
                        default:
                          return { __html: '' }
                      }
                    })()}
                  ></div>
                  <div className="post-end">
                    <img src="/static/img/logo-yellow.svg" />
                  </div>
                </div>
                <ArticleLine
                  articleList={articleRecommendList}
                  en={en}
                  type={type}
                />
              </div>
              <Footer />
            </div>
          )
        }}
      </ThemeContext.Consumer>
    )
  }
}
