import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import Assets from '@src/components/Assets';
import { getMap, formatTreeData } from '@src/services/Tools';
import Footer from '../../../components/Footer';
import { FaqModal, FinishModal } from '../../../components/OtherModal';
import { CommentFalls, AnswerCarousel, Consultation, Contact } from '../../../components/Other';
import Tabs from '../../../components/Tabs';
import Filter from '../../../components/Filter';
import { SingleItem, PackageItem } from '../../../components/Item';
import UserPagination from '../../../components/UserPagination';
import { Main } from '../../../stores/main';
import { Course } from '../../../stores/course';

export default class extends Page {
  initState() {
    return {
      list: [],
      tab: 'single',
    };
  }

  init() {
    Main.getPromote()
      .then(result => {
        this.setState({ promote: result });
      });
    Main.getBase()
      .then(result => {
        this.setState({ base: result });
      });

    Main.courseStruct().then(result => {
      const courseStruct = result.map(row => {
        return {
          level: row.level,
          title: `${row.titleZh}${row.titleEn}`,
          key: `${row.id}`,
          parentId: row.parentId,
          isExamination: row.isExamination,
        };
      });
      const courseStructSelect = courseStruct.filter(row => row.level === 1);
      const packageStructSelect = courseStructSelect.filter(row => row.isExamination);
      courseStructSelect.unshift({
        title: '全部',
        key: '',
      });
      packageStructSelect.unshift({
        title: '全部',
        key: '',
      });

      const courseStructTree = formatTreeData(courseStruct, 'key', 'title', 'parentId');
      const courseStructTreeMap = getMap(courseStructTree, 'key', 'children');
      this.setState({ courseStructSelect, courseStructTreeMap, packageStructSelect });
    });
  }

  initData() {
    const data = Object.assign(this.state, this.state.search);
    if (data.order) {
      data.sortMap = { [data.order]: data.direction };
    }
    data.filterMap = this.state.search;
    this.setState(data);

    const { tab } = this.state;
    switch (tab) {
      case 'single':
        this.refreshSingle();
        break;
      case 'package':
        this.refreshPackage();
        break;
      default:
        break;
    }
  }

  refreshSingle() {
    Main.listFaq({ page: 1, size: 100, channel: 'course-video_index' }).then(result => {
      this.setState({ faqs: result.list });
    });
    Main.listComment({ page: 1, size: 100, channel: 'course-video_index' }).then(result => {
      this.setState({ comments: result.list });
    });
    Course.listVideo(Object.assign({ structId: this.state.search.parentStructId }, this.state.search))
      .then(result => {
        this.setState({ list: result.list, total: result.total });
      });
  }

  refreshPackage() {
    Main.listFaq({ page: 1, size: 100, channel: 'course-package_index' }).then(result => {
      this.setState({ faqs: result.list });
    });
    Main.listComment({ page: 1, size: 100, channel: 'course-package_index' }).then(result => {
      this.setState({ comments: result.list });
    });
    Course.listPackage(Object.assign({}, this.state.search))
      .then(result => {
        this.setState({ list: result.list, total: result.total });
      });
  }

  onTabChange(tab) {
    const data = { tab };
    this.refreshQuery(data);
  }

  onFilter(key, value) {
    const { filterMap } = this.state;
    filterMap[key] = value;
    this.search(filterMap, false);
    this.initData();
  }

  onChangePage(page) {
    this.search({ page }, false);
    this.initData();
  }

  renderView() {
    const { number } = this.props.order;
    const { tab, promote = {}, base = {}, comments, faqs, showFaq, faq, showFinish } = this.state;
    return (
      <div>
        <div className="top content">
          <Tabs type="text" active={'online'} tabs={[{ title: '在线课程', key: 'online', path: '/course/online' }, { title: '1v1私教', key: 'vs', path: '/course/vs' }]} />
          <div className="f-r">
            <span className="t-2 m-r-1">{(promote.video || {}).text ? `优惠活动:${promote.video.text}` : ''}</span>
            <Assets name="cart" onClick={() => linkTo('/cart')} />
            <span className="t-2">( {number || 0} )</span>
          </div>
        </div>
        <div className="center">
          <div className="content">
            <Tabs
              type="division"
              theme="theme"
              size="small"
              space={2.5}
              width={100}
              border
              active={tab}
              tabs={[{ title: '单项购买', key: 'single' }, { title: '套餐购买', key: 'package' }]}
              onChange={key => this.onTabChange(key)}
            />
            {this[`renderTab${tab}`]()}
          </div>
        </div>
        <Consultation data={base.contact} />
        <CommentFalls list={comments} />
        <AnswerCarousel list={faqs} onFaq={() => this.setState({ showFaq: true, faq: { channel: tab === 'single' ? 'course-video_index' : 'course-package_index' } })} />
        <Contact data={base.contact} />
        <Footer />
        <FaqModal show={showFaq} defaultData={faq} onCancel={() => this.setState({ showFaq: false, faq: {} })} onConfirm={() => this.setState({ showFaq: false, faq: {}, showFinish: true })} />
        <FinishModal
          show={showFinish}
          onConfirm={() => this.setState({ showFinish: false })}
        />
      </div>
    );
  }

  renderTabsingle() {
    const { filterMap, list = [], courseStructSelect, courseStructTreeMap = {}, total, page } = this.state;
    const child = (courseStructTreeMap[filterMap.parentStructId] || []).map(row => {
      return {
        title: row.title,
        key: row.key,
      };
    });
    child.unshift({
      title: '全部',
      key: '',
    });
    return [
      <Filter
        filter={filterMap}
        list={[
          {
            key: 'parentStructId',
            children: courseStructSelect,
          },
          {
            key: 'structId',
            children: child,
          },
        ]}
        onFilter={(key, value) => this.onFilter(key, value)}
      />,
      <div className="tab-1-list">
        {list.map((data) => {
          return <SingleItem data={data} />;
        })}
      </div>,
      total > 0 && list.length > 0 && (
        <UserPagination total={total} current={page} pageSize={this.state.search.size} onChange={p => this.onChangePage(p)} />
      ),
    ];
  }

  renderTabpackage() {
    const { filterMap, list = [], packageStructSelect, total, page } = this.state;
    return [
      <Filter
        filter={filterMap}
        list={[
          {
            key: 'structId',
            children: packageStructSelect,
          },
        ]}
        onFilter={(key, value) => this.onFilter(key, value)}
      />,
      <div className="tab-2-list">
        {list.map((data) => {
          return <PackageItem data={data} />;
        })}
      </div>,
      total > 0 && list.length > 0 && (
        <UserPagination total={total} current={page} pageSize={this.state.search.size} onChange={p => this.onChangePage(p)} />
      ),
    ];
  }
}