import React, { useMemo, useRef, useCallback, useState } from 'react'
// import { PageHeaderWrapper } from '@ant-design/pro-layout'
import { Button, notification, Spin } from 'antd'
import { router } from 'umi'
import QueryTable from '@/components/QueryTable'
import AuthButton from '@/components/AuthButton'
import request from '@/utils/request'
import apis from '@/services/apis'
import getSearchFields from './searchFields'
import getTableColumns from './tableColumns'

export default (props) => {
  const ref = useRef()
  const [loading, setLoading] = useState(false)
  const [page, setPage] = useState({current: 1, pageSize: 10})
  const onPublish = useCallback((row) => {
    const buidingStatus = row.status === 1 ? 2 : 1
    request({ ...apis.building.updateStatus, data: { id: row.buildingId, status: buidingStatus } }).then(() => {
      notification.success({ message: '操作成功' })
      setLoading(false)
      ref.current.reload()
    }).catch(err => {
      console.error(err)
      setLoading(false)
    })
  }, [])

  const onDelete = useCallback((row) => {
    setLoading(true)
    request({ ...apis.building.deleteBuilding, urlData: { id: row.buildingId } }).then(() => {
      notification.success({ message: '操作成功' })
      setLoading(false)
      ref.current.reload()
    }).catch((err) => {
      console.error(err)
      setLoading(false)
    })
  }, [])

  const searchFields = useMemo(getSearchFields, [])
  const tableColumns = useMemo(() => {
    return getTableColumns({
      page,
      onPublish,
      onDelete,
    })
  }, [page])

  const actionRender = () => {
    const gotoAdd = () => router.push('/building/add')
    return (
      <AuthButton name="building.add">
        <Button type="primary" icon="plus" onClick={gotoAdd}>新增</Button>
      </AuthButton>
    )
  }

  return (
    // <PageHeaderWrapper>
      <Spin spinning={loading}>
        <QueryTable
          ref={ref}
          rowKey="buildingId"
          api={apis.building.getList}
          searchFields={searchFields}
          columns={tableColumns}
          actionRender={actionRender}
          onPageChange={(pg) => setPage(pg)}
        />
      </Spin>
    // </PageHeaderWrapper>
  )
}
