import React, { useEffect, useState } from 'react'
import { InfiniteList } from '@zhst/biz'
import { Button, Input, Space } from 'antd'

export default () => {
  const [data, setData] = useState<any>([])
  const [loading, setLoading] = useState(false)
  const [params, setParams] = useState({})

  const loadMoreData = (params?: any) => {
    if (loading) {
      return;
    }
    setLoading(true);
    fetch('https://randomuser.me/api/?results=10&inc=id,key,name,gender,email,nat,picture&noinfo')
      .then((res) => res.json())
      .then((body) => {
        let res = body.results.map((o: { name: { first: any; last: any }; picture: { large: any } }) => {
          return {
            title: o.name.first,
            subtitle: o.name.last,
            url: o.picture.large
          }
        })
        setData([...data, ...res]);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    loadMoreData();
  }, []);

  return (
    <Space direction='vertical' size={10} style={{ padding: '12px', border: '1px solid #ccc' }}>
      <Space>
        <Input placeholder='名称' onChange={(e) => setParams(pre => ({ ...pre, name: e.target.value }))} style={{ width: '120px' }} />
        <Input placeholder='年龄' onChange={(e) => setParams(pre => ({ ...pre, age: e.target.value }))} style={{ width: '120px' }} />
        <Input placeholder='性别' onChange={(e) => setParams(pre => ({ ...pre, sex: e.target.value }))} style={{ width: '120px' }} />
        <Input placeholder='手机号' onChange={(e) => setParams(pre => ({ ...pre, tel: e.target.value }))} style={{ width: '120px' }} />
        <Button onClick={() => loadMoreData(params)}>加载更多</Button>
      </Space>
      <InfiniteList
        loading={loading}
        loadMore={() => loadMoreData(params)}
        height={300}
        hasMore={data.length < 100}
        data={data}
        loadingMessage={<Button onClick={() => loadMoreData(params)}>加载更多</Button>}
      />
    </Space>
  )
}
