import React from 'react';
import { Button } from 'antd';
import { Link } from 'react-router-dom';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import FilterLayout from '@src/layouts/FilterLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { getMap, formatTreeData, bindSearch, formatDate } from '@src/services/Tools';
import { asyncSMessage, asyncDelConfirm, asyncGet } from '@src/services/AsyncTools';
import { QuestionType, QuestionDifficult } from '../../../../Constant';
import { Exercise } from '../../../stores/exercise';
import { System } from '../../../stores/system';
import { Question } from '../../../stores/question';
import { Slient } from '../../../stores/slient';
// import Association from '../../../components/Association';

const QuestionTypeMap = getMap(QuestionType, 'value', 'label');

const filterForm = [
  {
    key: 'type',
    type: 'select',
    allowClear: true,
    name: '题型',
    select: QuestionType,
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'structId',
    type: 'tree',
    allowClear: true,
    name: '分册',
    select: [],
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'paperId',
    type: 'select',
    allowClear: true,
    name: '练习册',
    select: [],
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'place',
    type: 'select',
    allowClear: true,
    name: '考点',
    select: [],
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'difficult',
    type: 'select',
    allowClear: true,
    name: '难度',
    select: QuestionDifficult,
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'time',
    type: 'daterange',
    name: '修改时间',
  },
  {
    key: 'questionNoId',
    type: 'select',
    allowClear: true,
    name: '题目ID',
    select: [],
    number: true,
    placeholder: '请输入',
  },
];
export default class extends Page {
  constructor(props) {
    super(props);
    this.actionList = [{
      key: 'add',
      name: '新建',
      render: (item) => {
        return <Button onClick={() => {
          linkTo('/subject/question');
        }}>{item.name}</Button>;
      },
    }, {
      key: 'auto',
      name: '重新组卷',
    }, {
      key: 'delete',
      name: '批量删除',
      needSelect: 1,
    }];
    this.categoryMap = {};
    this.columns = [{
      title: '学科',
      dataIndex: 'first',
      render: (text, record) => {
        return this.categoryMap[record.questionNo.moduleStruct[0]] || text;
      },
    }, {
      title: '题型',
      dataIndex: 'type',
      render: (text, record) => {
        return QuestionTypeMap[record.question.type] || text;
      },
    }, {
      title: '练习册',
      dataIndex: 'paper',
      render: (text) => {
        return text.title;
      },
    }, {
      title: '考点',
      dataIndex: 'place',
      render: (text, record) => {
        return record.question.place;
      },
    }, {
      title: '难度',
      dataIndex: 'difficlut',
      render: (text, record) => {
        return record.question.difficult;
      },
    }, {
      title: '易错度',
      dataIndex: 'correct',
      render: (text, record) => {
        return `${record.questionNo.totalCorrect * 100 / record.questionNo.totalNumber}%`;
      },
    }, {
      title: '平均时间',
      dataIndex: 'time',
      render: (text, record) => {
        return `${record.questionNo.totalTime / record.questionNo.totalNumber}s`;
      },
    }, {
      title: '序号',
      dataIndex: 'no',
      render: (text, record) => {
        const { search } = this.state;
        if (search.paper_id) {
          return record.paper.no;
        }
        return '--';
      },
    }, {
      title: '修改时间',
      dataIndex: 'updateTime',
      render: (text, record) => {
        return formatDate(record.question.updateTime);
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <Link to={`/subject/question/${record.question_id}`}>编辑</Link>
          )}
          {(
            <a onClick={() => {
              // this.setState({ detail: { title: '题源联想', ids: record.question.associationContent, field: 'associationContent', module: 'exercise', modal: true, show: true } });
              asyncGet(() => import('../../../components/Association'),
                { title: '题源联想', ids: record.question.associationContent, field: 'associationContent', module: 'exercise', modal: true },
                (data) => {
                  data.id = record.questionId;
                  data.associationContent = data.associationContent.map(row => row.id);
                  return Question.edit(data).then(() => {
                    asyncSMessage('修改成功!');
                  });
                });
            }}>编辑</a>
          )}
        </div>;
      },
    }];
  }

  initAuto() {
    this.outPage();
    this.interval = setInterval(() => {
      Slient.exerciseAuto().then((result) => {
        if (result.process == null || result.process === 100) {
          this.actionList[1].disabled = false;
          result.process = 100;
        } else {
          this.actionList[1].disabled = true;
        }
        this.setState({ process: result.process });
      });
    }, 30000);
  }

  outPage() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  init() {
    Exercise.allStruct().then(result => {
      const list = result.filter(row => row.level > 2).map(row => { row.title = `${row.titleZh}/${row.titleEn}`; row.value = row.id; return row; });
      filterForm[1].tree = formatTreeData(list, 'id', 'title', 'parentId');
      this.categoryMap = getMap(result.map(row => { row.title = `${row.titleZh}/${row.titleEn}`; row.value = row.id; return row; }), 'id', 'title');
      this.setState({ exercise: result });
    });
    System.getPlace().then(result => {
      filterForm[3].select = [].concat(...Object.keys(result).map(key => result[key]));
      this.setState({ place: result });
    });
    bindSearch(filterForm, 'paper_id', this, (search) => {
      return Exercise.listPaper(search);
    }, (row) => {
      return {
        title: row.title,
        value: row.id,
      };
    }, this.state.search.paper_id ? [Number(this.state.search.paper_id)] : [], null);
    bindSearch(filterForm, 'question_no_id', this, (search) => {
      return Question.searchNo(search);
    }, (row) => {
      return {
        title: row.no,
        value: row.id,
      };
    }, this.state.search.question_no_id ? [Number(this.state.search.question_no_id)] : [], null);
    this.initAuto();
  }

  initData() {
    const { search } = this.state;
    const data = Object.assign({}, search);
    if (data.time) {
      data.startTime = data.time[0] || '';
      data.endTime = data.time[1] || '';
    }
    Exercise.listQuestion(data).then(result => {
      this.setTableData(result.list, result.total || 1);
    });
  }

  autoAction() {
    asyncDelConfirm('组卷确认', '是否重新组卷?', () => {
      return Exercise.auto().then(() => {
        asyncSMessage('开始组卷！');
        this.refresh();
      });
    });
  }

  deleteAction() {
    const { selectedRows } = this.state;
    asyncDelConfirm('删除确认', '是否删除选中题目?', () => {
      return Promise.all(selectedRows.map(row => Question.del({ id: row.question_id })));
    }).then(() => {
      asyncSMessage('删除成功!');
      this.refresh();
    });
  }

  renderView() {
    return <Block flex>
      <FilterLayout
        show
        itemList={filterForm}
        data={this.state.search}
        onChange={data => {
          if (data.time.length > 0) {
            data.time = [data.time[0].format('YYYY-MM-DD HH:mm:ss'), data.time[1].format('YYYY-MM-DD HH:mm:ss')];
          }
          this.search(data);
        }} />
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        select
        columns={this.columns}
        list={this.state.list}
        pagination={this.state.page}
        loading={this.props.core.loading}
        onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
        onSelect={(keys, rows) => this.tableSelect(keys, rows)}
        selectedKeys={this.state.selectedKeys}
      />
      {/* {this.state.detail && <Association {...this.state.detail} />} */}
    </Block>;
  }
}
