import React, { useRef, useState } from 'react'
import { Form, Input, Button, Radio } from 'antd'
import SearchItem from './SearchItem'
import { defaultLayout, getFormDataFrom } from './utils'

export default (props) => {
  const { fields = [], extraParams = {}, onSearch, onReset } = props
  const initValue = useRef(getFormDataFrom(fields))
  const [formData, setFormData] = useState(initValue.current)

  const handleChange = (data) => {
    setFormData({
      ...formData,
      ...data,
    })
  }

  const handleSubmit = () => {
    onSearch({
      ...formData,
      ...extraParams,
    })
  }

  const handleReset = () => {
    setFormData(initValue.current)
    onReset({
      ...initValue.current,
      ...extraParams,
    })
  }

  return (
    <Form layout="inline">
      {
        fields.map((field) => (
          <SearchItem
            key={field.name}
            config={field}
            label={field.label}
            name={field.name}
            value={formData[field.name]}
            onChange={handleChange}
          />
        ))
      }
      <Form.Item>
        <Button type="primary" onClick={handleSubmit}>搜索</Button>
        <Button onClick={handleReset} style={{marginLeft: '1em'}}>重置</Button>
      </Form.Item>
    </Form>
  )
}
