import React from 'react';
import M from 'immutable';
import FormGenerator from 'components/FormGenerator';

import {
  Modal,
  Spin
} from 'antd';

function nil() {}

class BaseDialog extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      visible: false,
      loading: false
    }

    this.defaultProps = {
      reload: nil,
      handleSubmit: nil,
      successMessage: '执行成功',
      triggerClassName: ''
    }

    this.showModal = () => {
      this.setState({
        visible: true
      });
    }

    this.hideModal = () => {
      if (!this.state.loading) {
        this.setState({
          visible: false
        });
      }
    }
   
  }

  /**
   * [handleSubmit default submit handler]
   * @type {[type]}
   */
  handleSubmit = (values) => {
    if (this.state.loading) {
      return
    }

    this.setState({
      loading: true
    });

    this.props.handleSubmit(values, (ret) => {
      this.setState({
        loading: false,
        visible: false
      });
      Modal.success({
        title: ret.message || '执行成功'
      });
      this.props.reload();
    }, (ret) => {
      this.setState({
        loading: false,
        visible: false
      });

      Modal.error({
        title: ret.error,
        content: ret.message
      })
    });
  }

  /**
   * [render form type dialog]
   * @return {[type]} [description]
   */
  renderForm = () => {
    const props = this.props;
    const initialValue = props.initialValue;
    const schema = props.schema;

    return (
      <FormGenerator
        ref="formGenerator"
        schema={schema}
        initialValue={initialValue}
        onSubmit={this.handleSubmit}
        />
    );
  }
    
  /**
   * [render confirm type dialog]
   * @return {[type]} [description]
   */
  renderConfirm = () => {
    const props = this.props;
    return (
      <div>{props.message}</div>
    )
  }

  /**
   * render
   * @return {[type]} [description]
   */
  render() {
    const props = this.props
    let $content = null;
    let spreadProps = {};
    if (this.state.loading) {
      $content = (
        <div>处理中 <Spin/></div>
      )
    } else {
      if (props.type === 'form') {
        $content = this.renderForm();
        spreadProps.footer = null;
      }

      if (props.type === 'confirm') {
        $content = this.renderConfirm();
        spreadProps.onOk = this.handleSubmit;
      }
    }

    return (
      <a href="javascript:;" onClick={this.showModal} className={props.triggerClassName}>
        {props.name}
        <Modal
          title={props.title}
          visible={this.state.visible}
          onCancel={this.hideModal}
          {...spreadProps}>
          {$content}  
        </Modal>
      </a>
    )
  }
}
 
export default BaseDialog;