import React, { Component } from 'react';
import { Modal, Row, Col, Checkbox, Alert } from 'antd';
import './index.less';

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

  onConfirm() {
    const { questionNo } = this.state;
    if (!questionNo) {
      this.setState({ err: '请选择需要加载的题目' });
      return;
    }
    if (this.props.onConfirm && this.props.modal) {
      this.setState({ loading: true });
      this.props
        .onConfirm(questionNo)
        .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();
  }

  renderForm() {
    const { questionNos = [] } = this.props;
    const { questionNo } = this.state;
    return <div>
      {questionNos.map(row => {
        return <Row style={{ width: '100%' }}>
          <Col span={1}><Checkbox checked={questionNo && row.id === questionNo.id} onChange={(value) => {
            this.setState({ questionNo: value ? row : null });
          }} /></Col>
          <Col span={4} offset={1}>
            {row.title}
          </Col>
          <Col span={16} offset={1}>
            {row.question.description}
          </Col>
        </Row>;
      })}
    </div>;
  }

  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>{this.renderForm()}</div>);
  }
}
export default SimilarQuestionNo;