import React from 'react';
import PropTypes from 'prop-types';
import { Form, Button } from 'antd';
import WrapperItem from './WrapperItem';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

class WrapperForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {}
  }

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        if (typeof this.props.onError === 'function') {
          typeof this.props.onError(err)
        } else {
          window.console.error(err)
        }
      } else {
        if (typeof this.props.onSubmit === 'function') {
          typeof this.props.onSubmit(values)
        }
      }
    });
  }

  handleCancel = e => {
    e.preventDefault();

    if (typeof this.props.onCancel === 'function') {
      typeof this.props.onCancel()
    }
  }

  renderDefaultAction = (submitBtn, cancelBtn) => {
    let FieldSubmit = null
    let FieldCancel = null
    if (submitBtn !== false) {
      FieldSubmit = <Button htmlType="submit" type="primary">提交</Button>
    }
    if (cancelBtn !== false) {
      FieldCancel = <Button htmlType="button" onClick={this.handleCancel} style={{ marginLeft: '48px' }}>取消</Button>
    }

    return FieldSubmit || FieldCancel ? <WrapperItem action render={<>{FieldSubmit}{FieldCancel}</>} /> : null
  }

  render () {
    const {fields, form, children, submitBtn, cancelBtn, ...formProps} = this.props;
    console.log('fields:', fields)
    const FeildItems = (fields || []).filter(x => x).map((props, inx) => (<WrapperItem key={inx} {...props} form={form} />))
    
    return (
      <Form {...formItemLayout} {...formProps} onSubmit={this.handleSubmit}>
        {FeildItems}
        {this.renderDefaultAction(submitBtn, cancelBtn)}
        {children}
      </Form>
    );
  }
}

WrapperForm.propTypes = {
  fields: PropTypes.array.isRequired
}

export default WrapperForm;
