import React from 'react';
import './index.less';
import { Link } from 'react-router-dom';
import Page from '@src/containers/Page';
import { asyncConfirm } from '@src/services/AsyncTools';
import Tabs from '../../../components/Tabs';
import Module from '../../../components/Module';
import Input from '../../../components/Input';
import Button from '../../../components/Button';
import Division from '../../../components/Division';
import Card from '../../../components/Card';
import ListTable from '../../../components/ListTable';
import ProgressText from '../../../components/ProgressText';
import IconButton from '../../../components/IconButton';
import { Main } from '../../../stores/main';
import { Question } from '../../../stores/question';

const HARD = 'HARD';
const PREVIEW = 'PREVIEW';
const PREVIEW_CLASS = 'PREVIEW_CLASS';
const PREVIEW_TASK = 'PREVIEW_TASK';

const columns = [
  {
    title: '练习册',
    width: 250,
    align: 'left',
    render: item => {
      return (
        <div className="table-row">
          <div className="night f-s-16">{item.title}</div>
          <div>
            <ProgressText
              progress={item.report.id ? item.repport.userNumber / item.report.questionNumber : 0}
              size="small"
            />
          </div>
        </div>
      );
    },
  },
  {
    title: '正确率',
    width: 150,
    align: 'left',
    render: item => {
      return (
        <div className="table-row">
          <div className="night f-s-16 f-w-b">--</div>
          <div className="f-s-12">{item.stat.totalCorrect / item.stat.totalNumber}</div>
        </div>
      );
    },
  },
  {
    title: '全站用时',
    width: 150,
    align: 'left',
    render: item => {
      return (
        <div className="table-row">
          <div className="night f-s-16 f-w-b">--</div>
          <div className="f-s-12">全站{item.stat.totalTime / item.stat.totalNumber}s</div>
        </div>
      );
    },
  },
  {
    title: '最近做题',
    width: 150,
    align: 'left',
    render: () => {
      return (
        <div className="table-row">
          <div>2019-04-28</div>
          <div>07:30</div>
        </div>
      );
    },
  },
  {
    title: '操作',
    width: 180,
    align: 'left',
    render: item => {
      return (
        <div className="table-row p-t-1">
          {!item.repport.id && (
            <IconButton type="start" tip="Start" onClick={() => this.previewAction('start', item)} />
          )}
          {item.repport.id && (
            <IconButton
              className="m-r-2"
              type="continue"
              tip="Continue"
              onClick={() => this.previewAction('continue', item)}
            />
          )}
          {item.repport.id && (
            <IconButton type="restart" tip="Restart" onClick={() => this.previewAction('restart', item)} />
          )}
        </div>
      );
    },
  },
  {
    title: '报告',
    width: 30,
    align: 'right',
    render: item => {
      return (
        <div className="table-row p-t-1">
          {item.report.userNumber === item.report.questionNumber && <IconButton type="report" tip="Report" />}
        </div>
      );
    },
  },
];

export default class extends Page {
  initState() {
    this.columns = columns;
    return {
      level1Tab: PREVIEW,
      level2Tab: '',
      previewType: PREVIEW_CLASS,
      tabs: [],
      allClass: [],
      classProcess: {},
    };
  }

  initData() {
    Main.getExercise().then(result => {
      const list = result;
      const map = {};
      for (let i = 0; i < result.length; i += 1) {
        const item = result[i];
        if (!map[item.parentId]) map[item.parentId] = [];
        map[item.parentId].push(item);
      }
      const tabs = [];
      let allClass = [];
      tabs.push({ key: HARD, name: '长难句' });
      if (map[0]) {
        for (let i = 0; i < map[0].length; i += 1) {
          const item = map[0][i];
          tabs.push({ key: item.id, name: `${item.titleZh} ${item.titleEn}` });
          if (map[item.id]) {
            allClass = allClass.concat(map[item.id]);
          }
        }
      }
      tabs.push({ key: PREVIEW, name: '预习作业' });
      this.setState({ tabs, allClass, list, map });
    });
    this.refreshClassProcess();
  }

  refreshPreview() {
    const { previewType } = this.state;
    if (previewType === PREVIEW_CLASS) {
      this.refreshClassProcess();
    }
    if (previewType === PREVIEW_TASK) {
      this.refreshListPreview();
    }
  }

  onChangePreviewType(type) {
    this.setState({ previewType: type });
    this.refreshPreview();
  }

  refreshClassProcess() {
    Question.getClassProcess().then(result => {
      const classProcess = {};
      for (let i = 0; i < result.length; i += 1) {
        const item = result[i];
        classProcess[item.category].push(item);
      }
      this.setState({ classProcess });
    });
  }

  refreshListPreview() {
    Question.listPreview().then(result => {
      this.setState({ previews: result });
    });
  }

  onChangeTab(level, tab) {
    const state = {};
    state[`level${level}Tab`] = tab;
    this.setState(state);
  }

  previewAction(type, item) {
    switch (type) {
      case 'start':
        this.startPreview(item);
        break;
      case 'restart':
        this.restartPreview(item);
        break;
      case 'continue':
        this.continuePreview(item);
        break;
      default:
        break;
    }
  }

  startPreview(item) {
    linkTo(`/start/${item.id}?type=preview`);
  }

  restartPreview(item) {
    asyncConfirm('提示', '是否重置', () => {
      Question.restart(item.report.id).then(() => {
        this.refreshPreview();
      });
    });
  }

  continuePreview(item) {
    linkTo(`/start/${item.id}?type=preview&r=${item.report.id}`);
  }

  renderView() {
    const { level1Tab, level2Tab, tabs, map } = this.state;
    return (
      <div>
        <div className="content">
          <Module className="m-t-2">
            <Tabs type="card" active={level1Tab} tabs={tabs} onChange={key => this.onChangeTab(1, key)} />
            {level1Tab !== HARD && level1Tab !== PREVIEW && (
              <Tabs active={level2Tab} tabs={map[level2Tab]} onChange={key => this.onChangeTab(2, key)} />
            )}
          </Module>
          {level1Tab !== HARD && level1Tab !== PREVIEW && this.renderType()}
          {level1Tab === HARD && this.renderHard()}
          {level1Tab === PREVIEW && this.renderWork()}
        </div>
      </div>
    );
  }

  renderWork() {
    const { previewType } = this.state;
    switch (previewType) {
      case PREVIEW_CLASS:
        return this.renderAllClass();
      case PREVIEW_TASK:
        return this.renderAllTask();
      default:
        return <div />;
    }
  }

  renderAllClass() {
    const { allClass, classProcess } = this.state;
    return (
      <div className="work-body">
        <div className="work-nav">
          <div className="left">完成情况</div>
          <div className="right theme c-p" onClick={() => this.onChangePreviewType(PREVIEW_TASK)}>
            全部作业 >
          </div>
        </div>
        <Division col="3">
          {allClass.map(item => {
            return <Card data={item} process={classProcess[item.id]} previewAction={this.previewAction} />;
          })}
        </Division>
      </div>
    );
  }

  renderAllTask() {
    const { previews } = this.state;
    return (
      <div className="work-body">
        <div className="work-nav">
          <div className="left">全部作业</div>
          <div className="right theme c-p" onClick={() => this.onChangePreviewType(PREVIEW_CLASS)}>
            我的课程 >
          </div>
        </div>
        <ListTable
          filters={[
            {
              type: 'radio',
              checked: 'today',
              list: [{ key: 'today', title: '今日需完成' }, { key: 'tomorrow', title: '明日需完成' }],
            },
            {
              type: 'radio',
              checked: 'unfinish',
              list: [{ key: 'unfinish', title: '未完成' }, { key: 'finish', title: '已完成' }],
            },
            { type: 'select', checked: 'all', list: [{ key: 'all', title: '全部' }] },
          ]}
          data={previews}
          columns={this.columns}
        />
      </div>
    );
  }

  renderHard() {
    return this.renderInputCode();
  }

  renderType() {
    return <div />;
  }

  renderInputCode() {
    return (
      <Module className="code-module">
        <div className="title">输入《千行GMAT长难句》专属 Code，解锁在线练习功能。</div>
        <div className="input-block">
          <Input size="lager" placeholder="请输入CODE" />
          <Button size="lager">解锁</Button>
        </div>
        <div className="tip">
          <Link to="/" className="left link">
            什么是CODE？
          </Link>
          <span>没有 CODE？</span>
          <Link to="/" className="link">
            去获取 >>
          </Link>
          <Link to="/" className="right link">
            试用 >>
          </Link>
        </div>
      </Module>
    );
  }
}
