import React from 'react';
import './index.less';
import { Anchor, Icon } from 'antd';
import Assets from '@src/components/Assets';
import Page from '@src/containers/Page';
import Select from '../../../components/Select';
import Button from '../../../components/Button';
import { SuppleModal, SuppleFinishModal } from '../../../components/OtherModal';
import { Main } from '../../../stores/main';
import { User } from '../../../stores/user';
import { getMap, formatTreeData } from '../../../../../src/services/Tools';

export default class extends Page {
  initState() {
    this.areaMap = {};
    this.categoryMap = {};
    this.loadArticleMap = {};
    this.dataList = null;
    return {
      // load: false,
      // list: [
      //   {
      //     key: '1',
      //     title: '了解GMAT',
      //     children: true,
      //   },
      //   { key: '2', title: '推荐阅读' },
      //   { key: '3', title: '考场查询' },
      //   { key: '4', title: '熟悉备考资料', children: true },
      // ],
      // current: '1',
      // scrollCurrent: '1-1',
      // result: [{}, {}, {}],
      // data: [
      //   { key: '1', id: 'data1', title: '官方', children: [{}, {}, {}] },
      //   { key: '2', id: 'data2', title: '非官方', children: [{}, {}, {}] },
      // ],
      // page: [
      //   {
      //     key: '1-1',
      //     title: '考试功能',
      //     id: '#test1',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-2',
      //     title: '出题原理',
      //     id: '#test2',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-3',
      //     title: '出题原理',
      //     id: '#test3',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-4',
      //     title: '出题原理',
      //     id: '#test4',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-5',
      //     title: '出题原理',
      //     id: '#test5',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-6',
      //     title: '出题原理',
      //     id: '#test6',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-7',
      //     title: '出题原理',
      //     id: '#test7',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-8',
      //     title: '出题原理',
      //     id: '#test8',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-9',
      //     title: '出题原理',
      //     id: '#test9',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-10',
      //     title: '出题原理',
      //     id: '#test10',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      //   {
      //     key: '1-11',
      //     title: '出题原理',
      //     id: '#test11',
      //     content:
      //       '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111',
      //   },
      // ],
    };
  }

  init() {
    Main.readyInfo()
      .then(result => {
        // read, category, area
        this.areaMap = getMap(result.area, 'id', 'title');
        result.category = result.category.map(row => {
          row.key = row.id;
          return row;
        });
        result.category.push({
          id: 'read',
          key: 'read',
          title: '推荐阅读',
          isRead: true,
        });
        result.category.push({
          id: 'faq',
          key: 'faq',
          title: 'FAQs',
          isFaq: true,
        });
        this.categoryMap = getMap(result.category, 'id');
        const list = formatTreeData(result.category, 'id', 'title', 'parentId');
        this.setState({ list });
        this.changePage(list[0].id);
      });
  }

  initData() {

  }

  refreshRoom() {
    const { isOverseas, keyword } = this.state;
    Main.listRoom({ page: 1, size: 10, keyword, isOverseas })
      .then(result => {
        result.list = result.list.map(row => {
          if (row.isOverseas) return row;
          row.area = this.areaMap[row.areaId];
          return row;
        });
        this.setState({ rooms: result.list });
      });
  }

  refreshData(item) {
    if (!this.dataList) {
      Main.allData()
        .then(result => {
          const official = result.filter(row => row.isOfficial);
          const unofficial = result.filter(row => !row.isOfficial);
          item.children.forEach(row => {
            if (row.isOfficial) {
              row.children = official;
            } else {
              row.children = unofficial;
            }
          });
          this.dataList = result;
          this.setState({ datas: item.children });
          this.initScroll(item.children);
        });
    } else {
      this.setState({ datas: item.children });
      this.initScroll(item.children);
    }
  }

  refreshList(item) {
    const { key } = item;
    if (!this.loadArticleMap[key]) {
      Main.listArticle(key)
        .then(result => {
          this.loadArticleMap[key] = result;
          this.setState({ articles: result });
          this.initScroll(item.children);
        });
    } else {
      const list = this.loadArticleMap[key];
      this.setState({ articles: list });
      this.initScroll(item.children);
    }
  }

  refreshRead() {
    if (!this.readList) {
      Main.listRead()
        .then(result => {
          this.readList = result.list;
          this.setState({ reads: this.readList });
        });
    } else {
      this.setState({ reads: this.readList });
    }
  }

  refreshFaq() {
    if (!this.faqList) {
      Main.listFaq({ page: 1, size: 1000, channel: 'getready' })
        .then(result => {
          this.faqList = result.list;
          this.setState({ faqs: this.faqList });
        });
    } else {
      this.setState({ faqs: this.faqList });
    }
  }

  initScroll(list) {
    this.load = false;
    try {
      list.forEach(item => {
        item.top = document.getElementById(item.id).offsetTop - 100;
        return item;
      });
      this.load = true;
    } catch (e) {
      setTimeout(() => {
        this.initScroll(list);
      }, 500);
    }
  }

  inPage() {
    document.getElementById('root').addEventListener('scroll', e => {
      if (!this.load) return;
      this.onScroll(e);
    });
  }

  outPage() {
    document.getElementById('root').removeEventListener('scroll');
  }

  onScroll(e) {
    const t = e.target.scrollTop;
    const { current, scrollCurrent } = this.state;
    const _list = this.categoryMap[current].children;
    let _current = null;
    for (let i = 0; i < _list.length; i += 1) {
      if (!_current) _current = _list[i].key;
      if (t < _list[i].top) break;
      _current = _list[i].key;
    }
    if (_current !== scrollCurrent) {
      this.setState({ scrollCurrent: _current });
    }
  }

  scrollTo(top) {
    document.getElementById('root').scrollTo({ top, behavior: 'smooth' });
  }

  changePage(key) {
    const item = this.categoryMap[key];
    if (item.isRoom) {
      this.refreshRoom();
    } else if (item.isData) {
      this.refreshData(item);
    } else if (item.isRead) {
      this.refreshRead();
    } else if (item.isFaq) {
      this.refreshFaq();
    } else {
      this.refreshList(item);
    }
    this.setState({ current: key });
  }

  renderView() {
    const { list, current, scrollCurrent } = this.state;
    let detail = {};
    return (
      <div>
        <div className="content">
          <div className="left">
            <Anchor offsetTop={90} getContainer={() => document.getElementById('root')}>
              {list.map(item => {
                if (item.key === current) detail = item;
                return (
                  <div
                    className={`page-item ${item.key === current ? 'active' : ''}`}
                    onClick={() => this.changePage(item.key)}
                  >
                    {item.children && item.children.length > 0 && <Assets name="dropdown_hover" className="up" />}
                    {item.children && item.children.length > 0 && <Assets name="dropdown_normal" className="down" />}
                    <div className="page-item-title">{item.title}</div>
                    {current === item.key &&
                      item.children &&
                      item.children.map(child => {
                        return (
                          <div
                            style={{ margin: 3 }}
                            className={`t-s-12 t-2 c-p ${child.key === scrollCurrent ? 't-4' : ''}`}
                            onClick={(e) => {
                              e.stopPropagation();
                              this.scrollTo(child.top);
                            }}
                            title={child.title}
                          >
                            {child.title}
                          </div>
                        );
                      })}
                  </div>
                );
              })}
            </Anchor>
          </div>
          <div className="center">
            <div className="t-1 t-s-24 m-b-2">{detail.title}</div>
            {!detail.isData && !detail.isRoom && !detail.isRead && !detail.isFaq && this.renderList()}
            {!!detail.isRoom && this.renderRoom()}
            {!!detail.isData && this.renderData()}
            {!!detail.isRead && this.renderRead()}
            {!!detail.isFaq && this.renderFaq()}
          </div>
        </div>
      </div >
    );
  }

  renderRoom() {
    const { rooms = [], isOverseas, keyword, showFinish, showSupple, supple, room } = this.state;
    return (
      <div className="query-layout">
        <div className="search-wrapper">
          <Select theme="white" value={isOverseas} list={[{ title: '中国', key: false }, { title: '海外', key: true }]} onChange={({ key }) => this.setState({ isOverseas: key })} />
          <input value={keyword} onChange={(e) => this.setState({ keyword: e.target.value })} />
          <Button width={150} onClick={() => this.refreshRoom()}>
            <Icon className="m-r-5" type="search" />
            搜索考场
          </Button>
        </div>
        {rooms.map((item, index) => {
          return (
            <div className="m-b-2">
              <div className="t-1 t-s-18">{index + 1}.{item.title}</div>
              <div className="t-1">{item.address}</div>
              <div className="t-1">
                温馨提示: {item.description} <span className="t-4" onClick={() => User.needLogin().then(() => this.setState({ showSupple: true, supple: { roomId: item.id }, room: item }))}>我要补充</span>
              </div>
            </div>
          );
        })}
        <SuppleModal show={showSupple} defaultData={supple} info={room} onConfirm={() => this.setState({ showSupple: false, showFinish: true })} onCancel={() => this.setState({ showSupple: false })} />
        <SuppleFinishModal show={showFinish} onConfirm={() => this.setState({ showFinish: false })} onCancel={() => this.setState({ showFinish: false })} />
      </div>
    );
  }

  renderData() {
    const { datas = [], dataId } = this.state;
    return datas.map(item => {
      return (
        <div className="p-t-1 m-b-2" id={item.id}>
          <div className="t-1 t-s-18 m-b-1">{item.title}</div>
          <div className="data-list">
            {item.children.map(child => {
              if (child.id === dataId) {
                return <div style={{ width: 240, height: 310, overflowY: 'auto', display: 'inline-block' }} className="ws-p data-item" onClick={() => this.setState({ dataId: null })}>{child.content}</div>;
              }
              return <Assets width={240} height={310} src={child.cover} className="data-item" onClick={() => this.setState({ dataId: child.id })} />;
            })}
          </div>
        </div>
      );
    });
  }

  renderList() {
    const { articles = [] } = this.state;
    return articles.map(item => {
      return (
        <div className="p-t-1 m-b-2" id={item.categoryId}>
          <div className="t-1 t-s-18 m-b-1">{item.title}</div>
          <div className="t-2" dangerouslySetInnerHTML={{ __html: item.content }} />
        </div>
      );
    });
  }

  renderRead() {
    return <div />;
  }

  renderFaq() {
    return <div />;
  }
}