import React, { useEffect, useState, useCallback, useRef } from 'react'
import { PageHeader, Form, Input, Button, Icon, Table, Rate, Tag, Spin, notification, Tooltip } from 'antd'

export default (props) => {
  const defaultPageInfo = { pageNum: 1, pageSize: 10 }
  const [loading, updateLoading] = useState(false)
  const [filterParams, updateFilterParams] = useState({})
  const [pageData, updatePageData] = useState([])
  const [pageNavData, updatePageNavData] = useState({})

  const getList = (params) => {
    updateLoading(true)
    props.fetchList(params).then(res => {
      updateLoading(false)
      updatePageData(res[0])
      updatePageNavData(res[1])

      if (!res[1].total) {
        notification.info({ message: '没有查询到数据' })
      }
    }).catch(err => {
      updateLoading(false)
      // do nothing
    })
  }

  const handleSearch = (params) => {
    updateFilterParams(params || {})
    
    getList({
      ...defaultPageInfo,
      ...(params || {})
    })
  }

  const handlePageChange = (pageNum, pageSize) => {
    getList({
      pageNum,
      pageSize,
      ...filterParams
    })
  }

  const dataRef = useRef()
  dataRef.current = pageData

  useEffect(() => {
    getList(defaultPageInfo)

    if (props.refreshData) {
      props.refreshData((callback) => {
        const newList = callback(dataRef.current)
        updatePageData(newList)
      })
    }
  }, [])

  const pagination = {
    ...pageNavData,
    onChange: handlePageChange
  }

  const showFilterForm = props.showFilterForm !== false
  const tableProp = {
    ...(props.table || {}),
    dataSource: pageData
  }

  return (
    <div>
      <PageHeader
        ghost={false}
        backIcon={false}
        title={props.title || "列表"}
        extra={[<Button key={1} type="primary" onClick={props.onAdd}>新增</Button>]}
      ></PageHeader>

      {
        showFilterForm && (
          <FilterForm onSearch={handleSearch} render={props.renderFilter} />
        )
      }
      
      <div style={{marginTop: '16px'}}>
        <Spin spinning={loading} delay={300} tip="请稍候...">
          <Table
            {...tableProp}
            pagination={pagination} />
        </Spin>
      </div>
    </div>
  )
}
