import React from 'react';
import './index.less';
import Page from '@src/containers/Page';
import { asyncConfirm, asyncSMessage } from '@src/services/AsyncTools';
import { formatTreeData, formatPercent, formatDate } from '@src/services/Tools';
import Panel, { WaitPanel, BuyPanel, SmallPanel, SmallWaitPanel, SmallBuyPanel } from '../../../components/Panel';
import Tabs from '../../../components/Tabs';
import Module from '../../../components/Module';
import Division from '../../../components/Division';
import { Main } from '../../../stores/main';
// import { My } from '../../../stores/my';
import { Question } from '../../../stores/question';
import { Textbook } from '../../../stores/textbook';
// import { User } from '../../../stores/user';
// import { CourseModuleShow, CourseModule } from '../../../../Constant';
import { Order } from '../../../stores/order';
import { User } from '../../../stores/user';

const TEXTBOOK = 'textbook';

export default class extends Page {
  initState() {
    this.examinationProgress = {};
    this.textbookProgress = {};
    this.inited = false;
    return {
      tab1: '',
      tab2: '',
      tabs: [],
    };
  }

  init() {
    Main.getExamination().then(result => {
      const list = result.filter(row => row.level === 1).map(row => {
        row.title = `${row.titleZh}${row.titleEn}`;
        row.key = row.extend;
        return row;
      });
      const tabs = formatTreeData(list, 'id', 'title', 'parentId');
      tabs.push({ key: TEXTBOOK, name: '数学机经' });
      this.setState({
        tabs,
      });
      this.inited = true;
      this.refreshData();
    });
  }

  initData() {
    const data = Object.assign(this.state, this.state.search);
    if (!data.tab1) {
      data.tab1 = 'cat';
    }
    this.setState(data);
    if (this.inited) this.refreshData();
  }

  refreshData(tab) {
    const { tab1 } = this.state;
    switch (tab || tab1) {
      case TEXTBOOK:
        this.refreshTextbook();
        break;
      default:
        this.refreshExamination(tab || tab1);
    }
  }

  refreshTextbook() {
    Textbook.progress().then(result => {
      // const exerciseProgress = getMap(r, 'id');
      result = result.map(row => {
        row.info = [
          {
            title: '已做',
            number: row.userNumber || '-',
            unit: '题',
          },
          {
            title: '剩余',
            number: row.userNumber ? row.questionNumber - row.userNumber : '-',
            unit: '题',
          },
          {
            title: '正确率',
            number: row.userNumber ? formatPercent(row.userStat.userCorrect, row.userStat.userNumber, false) : '-%',
            unit: '',
          },
          {
            title: '全站',
            number: row.userNumber ? formatPercent(row.stat.totalCorrect, row.stat.totalNumber, false) : '-%',
            unit: '题',
          },
        ];

        row.progress = formatPercent(row.questionNumber - row.userNumber || 0, row.questionNumber);
        row.totalCorrect = formatPercent(row.stat.totalCorrect, row.stat.totalNumber, false);

        row.children = row.children.map(r => {
          r.title = r.title || r.titleZh;
          r.progress = formatPercent(r.userNumber, r.questionNumber);
          return r;
        });

        row.pieValue = formatPercent(row.userNumber, row.questionNumber);
        row.pieText = formatPercent(row.userNumber, row.questionNumber, false);
        row.pieSubText = `共${row.questionNumber}`;

        if (row.isLatest) {
          const day = parseInt((new Date().getTime() - new Date(row.startDate).getTime()) / 86400000, 10);
          row.desc = [`最近换库:${formatDate(row.startDate, 'YYYY-MM-DD')} ,已换库${day}天`, `最后更新:${formatDate(row.updateTime)}`];
        }
        return row;
      });
      this.setState({ textbookProgress: result });
    });
  }

  refreshExamination(tab) {
    const { tabs, tab1 } = this.state;
    if (!tabs) {
      // 等待数据加载
      return;
    }
    const [subject] = tabs.filter(row => row.key === tab || row.key === tab1);
    Question.getExaminationProgress(subject.id).then(result => {
      // const exerciseProgress = getMap(r, 'id');
      result = result.map(row => {
        row.title = `${row.titleZh}${row.titleEn}`;
        row.info = [
          {
            title: '已做',
            number: row.userNumber || '-',
            unit: '套',
          },
          {
            title: '剩余',
            number: row.userNumber ? row.questionNumber - row.userNumber : '-',
            unit: '套',
          },
        ];
        row.pieValue = formatPercent(row.userNumber, row.questionNumber);
        row.pieText = formatPercent(row.userNumber, row.questionNumber, false);
        row.pieSubText = `共${row.questionNumber}套`;

        return row;
      });
      this.setState({ examinationProgress: result });
    });
  }

  onChangeTab(level, tab) {
    const { tab1 } = this.state;
    const data = {};
    if (level > 1) {
      data.tab1 = tab1;
      data.tab2 = tab;
    } else {
      data.tab1 = tab;
    }
    // this.refreshData(tab);
    this.refreshQuery(data);
  }

  onTextbook() {
    const { tab1, tab2, struct } = this.state;
    const data = {
      tab1, tab2, struct,
    };
    this.refreshQuery(data);
  }

  // 开通模考或者机经
  open(recordId) {
    Order.useRecord(recordId).then(() => {
      asyncSMessage('开通成功');
      this.refresh();
    });
  }

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

  examinationList(item) {
    User.needLogin().then(() => {
      linkTo(`/examination/list/${item.id}`);
    });
  }

  textbookList(item, isLatest) {
    User.needLogin().then(() => {
      linkTo(`/textbook/list?logic=${encodeURIComponent(item.logic)}&latest=${isLatest ? 1 : 0}`);
    });
  }

  renderView() {
    const { tab1, tab2, tabs } = this.state;
    const [subject] = tabs.filter(row => row.key === tab1);
    const children = (subject && subject.children) ? subject.children : [];
    return (
      <div>
        <div className="content">
          <Module className="m-t-2">
            <Tabs
              type="card"
              active={tab1}
              tabs={tabs}
              onChange={key => {
                this.onChangeTab(1, key);
              }}
            />
            {children && children.length > 1 && (
              <Tabs active={tab2} tabs={children} onChange={key => this.onChangeTab(2, key)} />
            )}
          </Module>
          {tab1 !== TEXTBOOK && this.renderExamination()}
          {tab1 === TEXTBOOK && this.renderTextbook()}
        </div>
      </div>
    );
  }

  renderTextbook() {
    const { textbookProgress = [] } = this.state;
    return (
      <div>
        <Division col={2}>
          {(textbookProgress || []).map(struct => {
            if (struct.needService && !struct.hasService) {
              if (struct.unUseRecord) {
                return <WaitPanel
                  title={struct.isLatest ? '最新' : '往期'}
                  col="3"
                  data={struct}
                  onOpen={() => {
                    this.open(struct.unUseRecord.id);
                  }}
                />;
              }
              return <BuyPanel
                title={struct.isLatest ? '最新' : '往期'}
                onBuy={() => {
                  this.buyTextbook();
                }}
              />;
            }
            return <Panel
              title={struct.isLatest ? '最新' : '往期'}
              col="3"
              data={struct}
              onClick={(item) => {
                this.textbookList(item, struct.isLatest);
              }}
            />;
          })}
        </Division>
      </div>
    );
  }

  renderExamination() {
    const { examinationProgress = [] } = this.state;
    return (
      <div>
        <Division col={3} type="compact">
          {(examinationProgress || []).map(struct => {
            if (struct.hasService) {
              return <SmallPanel
                title={struct.title}
                data={struct}
                onClick={() => {
                  this.examinationList(struct);
                }}
              />;
            } if (struct.unUseRecord) {
              return <SmallWaitPanel
                title={struct.title}
                data={struct}
                onOpen={() => {
                  this.open(struct.unUseRecord.id);
                }}
              />;
            }
            return <SmallBuyPanel
              title={struct.title}
              data={struct}
              onBuy={() => {
                this.buyQxCat();
              }}
            />;
          })}
        </Division>
      </div>
    );
  }
}