import React, { useState, useEffect } from 'react';
import { Button, Input, InputNumber, Select, notification } from 'antd';

const { Group } = Input;
const { Option } = Select;

export default (props) => {
  const { fetch, placeholder, disabled, onSubmit } = props;

  const [data, setData] = useState([]);
  const [value, setValue] = useState();
  const [amount, setAmount] = useState();

  const options = data.map(d => <Option key={d.id}>{d.name}</Option>);

  const handleSearch = (name) => {
    fetch({ pageNum: 1, pageSize: 20, name }).then(res => {
      setData(res.records || []);
    })
  };

  const handleChange = (val) => {
    setValue(val);
  }

  const handleSubmit = () => {
    if (!amount || amount <= 0) {
      notification.warn({ message: '请输入正确的数量' });
      return;
    }

    if (!value) {
      notification.warn({ message: placeholder });
      return;
    }

    const item = data.filter(x => `${x.id}` === `${value}`)[0];
    if (item) {
      onSubmit({ item, amount });
    }
  }

  useEffect(() => {
    fetch({ pageNum: 1, pageSize: 20 }).then(res => {
      setData(res.records || []);
    })
  }, []);

  return (
    <Group compact>
      <Select
        allowClear
        showSearch
        disabled={disabled}
        value={value}
        style={{ width: '50%' }}
        placeholder={placeholder}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={handleSearch}
        onChange={handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
      <InputNumber
        style={{ width: '30%' }}
        placeholder="请输入数量"
        disabled={disabled}
        value={amount}
        onChange={setAmount}
      />
      <Button type="primary" disabled={disabled} onClick={handleSubmit}>确定</Button>
    </Group>
  )
}
