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, formatPercent } from '@src/services/Tools';
import { asyncSMessage, asyncDelConfirm } from '@src/services/AsyncTools';
import { QuestionType, QuestionDifficult } from '../../../../Constant';
import { Question } from '../../../stores/question';
import { Examination } from '../../../stores/examination';

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

const filterForm = [
  {
    key: 'structId',
    type: 'tree',
    allowClear: true,
    name: '出题原理',
    select: [],
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'paperId',
    type: 'select',
    allowClear: true,
    name: '练习册',
    select: [],
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'difficult',
    type: 'select',
    allowClear: true,
    name: '难度',
    select: QuestionDifficult,
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'questionType',
    type: 'select',
    allowClear: true,
    name: '题型',
    select: QuestionType,
    placeholder: '请选择',
    number: true,
  },
  {
    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: 'delete',
      name: '批量删除',
      needSelect: 1,
    }];
    this.categoryMap = {};
    this.columns = [{
      title: '出题原理',
      dataIndex: 'first',
      render: (text, record) => {
        return this.categoryMap[record.questionNo.moduleStruct[0]] || text;
      },
    }, {
      title: '类别',
      dataIndex: 'second',
      render: (text, record) => {
        return QuestionTypeMap[record.question.questionType] || text;
      },
    }, {
      title: '试卷',
      dataIndex: 'three',
      render: (text, record) => {
        return QuestionTypeMap[record.question.questionType] || text;
      },
    }, {
      title: '题型',
      dataIndex: 'questionType',
      render: (text, record) => {
        return QuestionTypeMap[record.question.questionType] || text;
      },
    }, {
      title: '难度',
      dataIndex: 'difficlut',
      render: (text, record) => {
        return record.question.difficult;
      },
    }, {
      title: '错误率',
      dataIndex: 'correct',
      render: (text, record) => {
        return formatPercent(record.questionNo.totalNumber - record.questionNo.totalCorrect, record.questionNo.totalNumber, false);
      },
    }, {
      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>
          )}
        </div>;
      },
    }];
  }

  init() {
    Examination.allStruct().then(result => {
      const list = result.filter(row => row.level < 3).map(row => { row.title = row.titleZh; row.value = row.id; return row; });
      filterForm[0].tree = formatTreeData(list, 'id', 'title', 'parentId');
      this.categoryMap = getMap(result.map(row => { row.title = row.titleZh; row.value = row.id; return row; }), 'id', 'title');
      this.setState({ examination: result });
    });
    bindSearch(filterForm, 'paperId', this, (search) => {
      return Examination.listPaper(search);
    }, (row) => {
      return {
        title: row.title,
        value: row.id,
      };
    }, this.state.search.paperId ? Number(this.state.search.paperId) : null, null);
    bindSearch(filterForm, 'questionNoId', this, (search) => {
      return Question.searchNo(search);
    }, (row) => {
      return {
        title: row.title,
        value: row.id,
      };
    }, this.state.search.questionNoId ? Number(this.state.search.questionNoId) : null, null);
  }

  initData() {
    const { search } = this.state;
    const data = Object.assign({}, search);
    Examination.listQuestion(data).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

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

  renderView() {
    const { examination } = this.state;
    return <Block flex>
      {examination && <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.tableSort(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}
      />
    </Block>;
  }
}