import React from 'react';
import { Form, Input, Button, Row, Col, DatePicker } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import Select from '@src/components/Select';
// import FileUpload from '@src/components/FileUpload';
import { formatFormError, generateSearch, getMap } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import QuestionNoList from '../../../components/QuestionNoList';
import { Preview } from '../../../stores/preview';
import { User } from '../../../stores/user';
import { Question } from '../../../stores/question';
import { Exercise } from '../../../stores/exercise';
import config from './index';

export default class extends Page {
  constructor(props) {
    super(props);
    const { id } = this.params;

    if (id) {
      config.title = '编辑预习作业';
    } else {
      config.title = '添加预习作业';
    }
  }

  init() {
    Exercise.allStruct().then(result => {
      result = result.filter(row => row.level === 2).map(row => { row.title = `${row.titleZh}/${row.titleEn}`; row.value = row.id; return row; });
      this.setState({ exercise: result });
    });
  }

  initData() {
    const { id } = this.params;
    const { form } = this.props;
    let handler;
    if (id) {
      handler = Preview.get({ id });
    } else {
      handler = Promise.resolve({ questionNoIds: [] });
    }
    handler
      .then(result => {
        const { questionNoIds } = result;
        form.setFieldsValue(result);
        generateSearch('userIds', { mode: 'multiple' }, this, (search) => {
          return User.list(search);
        }, (row) => {
          return {
            title: `${row.nickname}(${row.mobile})`,
            value: row.id,
          };
        }, result.userIds || [], null);
        this.setState({ questionNoIds });
      });
  }

  submit() {
    const { form } = this.props;
    form.validateFields((err) => {
      if (!err) {
        const data = form.getFieldsValue();
        let handler;
        data.questionNoIds = this.state.questionNos.map(row => row.id);
        if (data.id) {
          handler = Preview.add(data);
        } else {
          handler = Preview.edit(data);
        }
        handler.then(() => {
          asyncSMessage('保存成功');
        }).catch((e) => {
          if (e.result) form.setFields(formatFormError(data, e.result));
        });
      }
    });
  }

  deleteQuestion(index) {
    const { questionNos } = this.state;
    questionNos.splice(index, 1);
    this.setState({ questionNos });
    this.props.form.setFieldsValue({ questionNos: questionNos.map(row => row.no) });
  }

  orderQuestion(oldIndex, newIndex) {
    const { questionNos } = this.state;
    const tmp = questionNos[oldIndex];
    questionNos[oldIndex] = questionNos[newIndex];
    questionNos[newIndex] = tmp;
    this.setState({ questionNos });
    this.props.form.setFieldsValue({ questionNos: questionNos.map(row => row.no) });
  }

  searchQuestion(values, field = 'nos') {
    if (values.length === 0) {
      this.setState({ questionNos: [] });
      return;
    }
    // 查找练习题目
    Question.listNo({ [field]: values, module: 'exercise' }).then(result => {
      const map = getMap(result, 'no');
      const questionNos = values.map(no => map[no]).filter(row => row);
      this.setState({ questionNos });
      this.props.form.setFieldsValue({ questionNos: questionNos.map(row => row.no) });
    });
  }

  renderBase() {
    const { getFieldDecorator } = this.props.form;
    return <Block>
      <Form>
        {getFieldDecorator('id')(<input hidden />)}
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='选择课程'>
          {getFieldDecorator('category', {
            rules: [
              { required: true, message: '请选择课程' },
            ],
          })(
            <Select select={this.state.exercise} placeholder='请选择课程' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='起止时间'>
          {getFieldDecorator('time', {
            rules: [
              { required: true, message: '请输入起止时间' },
            ],
          })(
            <DatePicker.RangePicker />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='作业标题'>
          {getFieldDecorator('title', {
            rules: [
              { required: true, message: '请输入作业标题' },
            ],
          })(
            <Input placeholder='请输入作业标题' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='指定做题人'>
          {getFieldDecorator('userIds', {
            rules: [
              { required: true, message: '请指定做题人' },
            ],
          })(
            <Select {...this.state.userIds} placeholder='请指定做题人' />,
          )}
        </Form.Item>
        <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 16 }} label='选择作业题'>
          {getFieldDecorator('questionNos', {
            rules: [
              { required: true, message: '请选择作业题' },
            ],
          })(
            <Select mode='tags' maxTagCount={200} notFoundContent={null} placeholder='输入题目id, 逗号分隔' tokenSeparators={[',', '，']} onChange={(values) => {
              this.setState({ questionNos: values });
            }} />,
          )}
        </Form.Item>
      </Form>
    </Block>;
  }

  renderQuestionList() {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    return <Block>
      <h1>题目预览</h1>
      <QuestionNoList module='exercise' loading={false} ids={this.state.questionNoIds} nos={this.state.questionNos} onChange={(questionNos) => {
        this.questionNos = questionNos;
        getFieldDecorator('questionNos');
        setFieldsValue({ questionNos: questionNos.map(row => row.no) });
      }} />
    </Block>;
  }

  renderView() {
    return <div flex>
      {this.renderBase()}
      {this.renderQuestionList()}

      <Row type="flex" justify="center">
        <Col>
          <Button type="primary" onClick={() => {
            this.submit();
          }}>保存</Button>
        </Col>
      </Row>
    </div>;
  }
}
