import React, { Component } from 'react';
import { Form, Modal, Alert } from 'antd';
import './index.less';
import Select from '@src/components/Select';
import { getMap, generateSearch } from '@src/services/Tools';
import QuestionNoList from '../QuestionNoList';
import { Question } from '../../stores/question';
// import { Sentence } from '../../stores/sentence';

class Association extends Component {
  constructor(props) {
    super(props);
    this.state = { ids: props.ids, show: !!props.modal, loading: false, err: '' };
    this.questionNos = [];

    generateSearch(props.field, { mode: 'multiple' }, this, (search) => {
      return this.searchQuestion(search);
    }, (row) => {
      return {
        title: row.title,
        value: row.id,
      };
    }, props.ids, null);
    this.listQuestion(props.ids, 'ids');
  }

  onConfirm() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return;
      }
      if (this.props.onConfirm) {
        this.setState({ loading: true });
        this.props
          .onConfirm(fieldsValue)
          .then(() => {
            this.setState({ loading: false });
            this.onCancel();
          })
          .catch(e => {
            this.setState({ loading: false, err: e.message });
          });
      } else {
        this.onCancel();
      }
    });
  }

  onCancel() {
    if (this.props.modal) this.setState({ show: false });
    if (this.props.onCancel) this.props.onCancel();
  }

  listQuestion(values, ids = 'ids') {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { field = 'questionNoIds' } = this.props;
    getFieldDecorator(field);
    setFieldsValue({ [field]: values });
    if (!values || values.length === 0) {
      this.setState({ questionNos: [] });
      return;
    }
    let handler;
    switch (this.props.module) {
      case 'sentence':
      case 'exercise':
        // 查找练习题目
        handler = Question.listNo({ [ids]: values, module: this.props.module });
        break;
      default:
        return;
    }
    this.setState({ loading: true });
    handler.then(result => {
      const map = getMap(result, 'id');
      const questionNos = values.map(row => map[row]).filter(row => row);
      this.setState({ questionNos, loading: false });
      if (!this.props.modal) this.onConfirm();
    });
  }

  searchQuestion(params) {
    let handler;
    params.module = this.props.module;
    switch (this.props.module) {
      case 'sentence':
      case 'exercise':
        // 查找练习题目
        handler = Question.searchNo(params);
        break;
      default:
        handler = Promise.reject(new Error('module is error'));
    }
    return handler;
  }

  renderForm() {
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { field = 'questionNoIds' } = this.props;
    return <Form>
      <Form.Item>
        {getFieldDecorator(field)(
          <Select mode='multiple' maxTagCount={200} notFoundContent={null} placeholder='输入题目id, 逗号分隔' tokenSeparators={[',', ',']} {...this.state[field]} onChange={(values) => {
            // this.setState({ nos: values });
            this.listQuestion(values, 'ids');
          }} />,
        )}
      </Form.Item>
      <QuestionNoList loading={this.state.loading} questionNos={this.state.questionNos} onChange={(nos) => {
        this.questionNos = nos;
        getFieldDecorator(field);
        setFieldsValue({ [field]: nos.map(row => row.id) });
      }} />
    </Form>;
  }

  render() {
    const { modal, title, confirmText = '确定', cancelText = '取消' } = this.props;
    const { show, loading, err } = this.state;
    return modal ? (
      <Modal
        title={title}
        visible={show}
        okText={confirmText}
        cancelText={cancelText}
        confirmLoading={loading}
        onOk={() => this.onConfirm()}
        onCancel={() => this.onCancel()}
      >
        {err && <Alert type="error" showIcon message={err} closable onClose={() => this.setState({ err: '' })} />}
        {this.renderForm()}
      </Modal>
    ) : (<div><h1>{title}</h1>{this.renderForm()}</div>);
  }
}
export default Form.create()(Association);