import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import createForm from '@zjxpcyc/xrc-form2'
import { Button } from 'antd'

const XForm = createForm()

function clearProperties (o) {
  return Object.keys(o).reduce((acc, k) => {
    return {
      ...acc,
      [`${k}`]: undefined,
    }
  }, {})
}

export default class SearchForm extends PureComponent {
  static propTypes = {
    storage: PropTypes.object,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
    configs: PropTypes.object,
  }

  wrapperForm = null
  storage = this.props.storage || {}

  componentDidMount() {
    const conditions = this.storage.get('conditions')

    if (this.wrapperForm && conditions) {
      this.wrapperForm.props.form.setFieldsValue(conditions)
    }
  }

  handleCancel = () => {
    const conditions = this.storage.get('conditions') || {}
    this.storage.set('conditions', {})

    if (this.wrapperForm) {
      this.wrapperForm.props.form.setFieldsValue(clearProperties(conditions))
    }

    if (this.props.onCancel) {
      this.props.onCancel()
    }
  }

  wrapperFields = (fields) => {
    return [
      ...fields,
      {
        action: true,
        render: (props) => (<Button htmlType="submit" type="primary">搜索</Button>)
      },
      {
        action: true,
        render: (props) => (<Button htmlType="button" onClick={this.handleCancel} style={{ marginLeft: '16px' }}>重置</Button>)
      },
    ]
  }

  render() {
    const { fields, ...leftProps } = this.props.configs || {}

    return (
      <XForm
        submitBtn={false}
        cancelBtn={false}
        layout="inline"
        fields={this.wrapperFields(fields)}
        onSubmit={this.props.onSubmit}
        wrappedComponentRef={f => this.wrapperForm = f}
        {...leftProps}
      />
    )
  }
}

