import React from 'react';
import { Tabs, Form, Row, Col, InputNumber, Button } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import EditTableCell from '@src/components/EditTableCell';
import { getMap, flattenObject } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import TableLayout from '@src/layouts/TableLayout';
import { QuestionDifficult } from '../../../../Constant';
import { System } from '../../../stores/system';
import { Examination } from '../../../stores/examination';
import { Exercise } from '../../../stores/exercise';

export default class extends Page {
  constructor(props) {
    super(props);
    this.exerciseColumns = [{
      title: '学科',
      dataIndex: 'title',
    }].concat(QuestionDifficult.map(row => {
      const { exercise = {} } = this.state;
      return {
        title: row.label,
        dataIndex: row.value,
        render: (text, result) => {
          return <EditTableCell value={(exercise[result.id] || {})[text] || 0} onChange={(v) => {
            this.changeMapValue('exercise', result.id, row.value, v);
          }} />;
        },
      };
    }));

    this.examinationColumns = [{
      title: '学科',
      dataIndex: 'title',
    }, {
      title: '题目数',
      dataIndex: 'number',
      render: (text, result) => {
        const { examination = [] } = this.state;
        return <EditTableCell value={(examination[result.id] || {}).number || 0} onChange={(v) => {
          this.changeMapValue('examination', result.id, 'number', v);
        }} />;
      },
    }, {
      title: '做题时间',
      dataIndex: 'time',
      render: (text, result) => {
        const { examination } = this.state;
        return <EditTableCell value={(examination[result.id] || {}).time || 0} onChange={(v) => {
          this.changeValue('examination', result.id, 'time', v);
        }} />;
      },
    }];
    this.state.tab = 'exercise';
  }

  initData() {
    Promise.all(this.structExamination(), this.structExercise())
      .then(() => {
        return this.refresh(this.state.tab);
      });
  }

  refresh(tab) {
    if (tab === 'exercise') {
      return this.refreshExercise();
    }
    if (tab === 'examination') {
      return this.refreshExamination();
    }
    if (tab === 'filter') {
      return this.refreshFilter();
    }
    return Promise.reject();
  }

  refreshExercise() {
    return System.getExerciseTime().then((result) => {
      this.setState({ exercise: result || {} });
    });
  }

  refreshExamination() {
    return System.getExaminationTime().then((result) => {
      this.setState({ examination: result || {} });
    });
  }

  refreshFilter() {
    return System.getFilterTime().then((result) => {
      this.setState({ filter: result });

      const { form } = this.props;
      form.setFieldsValue(flattenObject(result, 'filter'));
    });
  }

  structExercise() {
    return Exercise.allStruct().then(result => {
      const list = result.map(row => { row.title = `${row.titleZh}/${row.titleEn}`; return row; });
      const map = getMap(list, 'id');
      this.setState({
        exerciseList: list.filter(row => row.level === 2).map(row => {
          const parent = map[row.parentId];
          row.title = `${parent.title}-${row.title}`;
          return row;
        }),
      });
    });
  }

  structExamination() {
    return Examination.allStruct().then(result => {
      const list = result.map(row => { row.title = `${row.titleZh}/${row.titleEn}`; return row; });
      this.setState({
        examinationList: list.filter(row => row.level === 1),
      });
    });
  }

  changeMapValue(field, index, key, value) {
    const data = this.state[field] || {};
    data[index] = data[index] || {};
    data[index][key] = value;
    this.setState({ [field]: data });
  }

  changeValue(field, key, value) {
    const data = this.state[field] || {};
    data[key] = value;
    this.setState({ [field]: data });
  }

  submit(tab) {
    let handler;
    if (tab === 'exercise') {
      handler = this.submitExercise();
    }
    if (tab === 'examination') {
      handler = this.submitExamination();
    }
    if (tab === 'filter') {
      handler = this.submitFilter();
    }
    handler.then(() => {
      asyncSMessage('保存成功');
    });
  }

  submitExercise() {
    const { exercise } = this.state;
    return System.setExerciseTime(exercise);
  }

  submitExamination() {
    const { examination } = this.state;
    return System.setExaminationTime(examination);
  }

  submitFilter() {
    const { form } = this.props;
    return new Promise((resolve, reject) => {
      form.validateFields(['filter'], (err, values) => {
        if (!err) {
          System.setFilterTime(values.filter)
            .then(() => {
              resolve();
            })
            .catch((e) => {
              reject(e);
            });
        }
      });
    });
  }

  renderExercise() {
    return <TableLayout
      columns={this.exerciseColumns}
      list={this.state.exerciseList}
      pagination={false}
      loading={this.props.core.loading}
    />;
  }

  renderFilterTime() {
    const { getFieldDecorator } = this.props.form;
    return <Form>
      <Row>
        <Col span={12}>
          <Form.Item labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} label='最短时间/题'>
            {getFieldDecorator('filter.min', {
              rules: [
                { required: true, message: '输入最短做题时间' },
              ],
            })(
              <InputNumber placeholder='请输入最短做题时间' addonAfter="s" onChange={(value) => {
                this.changeValue('filter', 'min', value);
              }} style={{ width: '200px' }} />,
            )}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} label='最长时间/题'>
            {getFieldDecorator('filter.max', {
              rules: [
                { required: true, message: '输入最长做题时间' },
              ],
            })(
              <InputNumber placeholder='请输入最长做题时间' addonAfter="s" onChange={(value) => {
                this.changeValue('filter', 'max', value);
              }} style={{ width: '200px' }} />,
            )}
          </Form.Item>
        </Col>
      </Row>
    </Form>;
  }

  renderExamination() {
    return <TableLayout
      columns={this.exerciseColumns}
      list={this.state.exerciseList}
      pagination={false}
      loading={this.props.core.loading}
    />;
  }

  renderView() {
    const { tab } = this.state;
    return <Block><Tabs activeKey={tab} onChange={(value) => {
      this.setState({ tab: value, selectedKeys: [], checkedKeys: [] });
      this.refresh(value);
    }}>
      <Tabs.TabPane tab="预估做题时间" key="exercise">
        {this.renderExercise()}
      </Tabs.TabPane>
      <Tabs.TabPane tab="数据剔除时间" key="filter">
        {this.renderFilterTime()}
      </Tabs.TabPane>
      <Tabs.TabPane tab="预估考试时间" key="examination">
        {this.renderExamination()}
      </Tabs.TabPane>
    </Tabs>
      <Row type="flex" justify="center">
        <Col>
          <Button type="primary" onClick={() => {
            this.submit(tab);
          }}>保存</Button>
        </Col>
      </Row>
    </Block>;
  }
}