import React from 'react';
import PropTyps from 'prop-types';
import { Form, Button } from 'antd';

function isFunc(fn) { return typeof fn === 'function' };

class SearchForm extends React.PureComponent {
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err && isFunc(this.props.onSearch)) {
        this.props.onSearch(values)
        return
      }

      if (err) {
        console.error(err)
        if (isFunc(this.props.onError)) {
          this.props.onError(err)
        }
        return
      }
    });
  };

  handleReset = e => {
    this.props.form.resetFields()
    if (isFunc(this.props.onReset)) {
      this.props.onReset()
    }
  }

  render () {
    const { form, hideResetBtn } = this.props;

    return (
      <Form layout="inline" onSubmit={this.handleSubmit} colon={false}>
        {
          (this.props.fields || []).map((field, index) => {
            const { element, render, name, label, value } = field || {}

            if (!element && !render) return null;

            const conifg = value  ? { initialValue: value } : {}
            const Item = isFunc(render) ? render(this.props) : element

            return <Form.Item label={label} key={`fm-${index}`}>{form.getFieldDecorator(name, conifg)(Item)}</Form.Item>
          })
        }
        <Form.Item>
          <Button type="primary" htmlType="submit">搜索</Button>
        </Form.Item>
        { hideResetBtn && (
          <Form.Item>
            <Button type="default" onClick="handleReset">重置</Button>
          </Form.Item>
        )}
      </Form>
    );
  }
}

// 提供给父组件 onChange 事件
function onValuesChange(props, changedValues, allValues) {
  if (isFunc(props.onChange)) {
    props.onChange(changedValues, allValues)
  }
}

const EnhanceForm = Form.create({ onValuesChange })(SearchForm)

EnhanceForm.propTypes = {
  onSearch: PropTyps.func.isRequired,
  onReset: PropTyps.func,
  onError: PropTyps.func,
  onChange: PropTyps.func,
  fields: PropTyps.arrayOf(PropTyps.object),
  hideResetBtn: PropTyps.bool,
}

export default EnhanceForm;
