import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Table, Row, Col, Form, Button, Space } from 'antd'
import IconReset from '@/assets/images/icon/reset.png'
import IconReload from '@/assets/images/icon/reload.png'
import IconFilter from '@/assets/images/icon/filter.png'

const AppList = (props, ref) => {
  const { remote = {}, filters = [], filterAside, ...rest } = props
  const [data, setData] = useState({ total: 0, list: [] })
  const [page, setPage] = useState({ current: 1, pageSize: 10 })
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  // 分页配置
  const pagination = {
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '30', '40'],
    showTotal: total => `共${total}条数据`,
    onChange: handlePageChange
  }

  // 获取列表数据
  async function fetchData() {
    let { request, beforeRequest, afterRequest } = remote
    if (!request) return
    setLoading(true)
    let params = { page: page.current, page_size: page.pageSize, ...form.getFieldsValue() }
    if (beforeRequest) {
      params = await beforeRequest(params)
    }
    const res = await request(params)
    const { list = [], total = 0 } = afterRequest ? await afterRequest(res.data, params) : res.data || {}
    setData({ list, total })
    setLoading(false)
  }
  useEffect(() => {
    fetchData()
  }, [page])
  // 筛选
  async function handleSearch() {
    setPage({ ...page, current: 1 })
  }
  // 重置
  async function handleReset() {
    // 清空筛选条件
    form.resetFields()
    setPage({ ...page, current: 1 })
  }
  // 刷新
  async function handleReload(isForce = false) {
    isForce ? await handleSearch() : await fetchData()
  }
  // 分页改变
  async function handlePageChange(current, pageSize) {
    setPage({ current, pageSize })
  }
  const onValuesChange = changedValues => {
    const [value] = Object.values(changedValues)
    !value && handleReload()
  }
  useImperativeHandle(ref, () => {
    return { handleSearch, handleReset, handleReload }
  })

  const filterElement = (
    <div className="app-list-filter" style={{ marginBottom: 20 }}>
      <div className="app-list-filter" style={{ marginBottom: 20 }}>
        <Row justify="space-between">
          <Col>
            <Form layout="inline" autoComplete="off" form={form} onValuesChange={onValuesChange}>
              {filters.map(item => (
                <Form.Item label={item.label} name={item.name} key={item.label}>
                  {item.element}
                </Form.Item>
              ))}
              <Space>
                <Button type="primary" htmlType="button" ghost icon={<Icon src={IconFilter} />} onClick={handleSearch}>
                  筛选
                </Button>
                <Button type="primary" htmlType="button" ghost icon={<Icon src={IconReset} />} onClick={handleReset}>
                  重置
                </Button>

                <Button type="primary" htmlType="button" ghost icon={<Icon src={IconReload} />} onClick={handleReload}>
                  刷新
                </Button>
              </Space>
            </Form>
          </Col>
          <Col>{filterAside}</Col>
        </Row>
      </div>
    </div>
  )
  return (
    <div className="app-list">
      {filters.length > 0 && filterElement}
      <div className="app-list-table">
        <Table rowKey="id" dataSource={data.list} loading={loading} pagination={pagination} {...rest}></Table>
      </div>
    </div>
  )
}

const Icon = ({ src }) => {
  const IconStyle = { height: '12px', objectFit: 'contain' }
  return <img src={src} style={IconStyle} />
}

export default forwardRef(AppList)
