import React, { useState, useCallback, useRef } from 'react';
import { Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';
import { queryTable } from '@/utils/request';
import useExport from '@/utils/hooks/useExport';

export default (props) => {
  const { formRef, request, expfunc, params = {}, toolBarRender, ...leftProps } = props;

  // 如果 formRef 未设置, 则使用 fmRef 去代理
  const fmRef = useRef();
  const ref = formRef || fmRef;

  // 自动封装查询函数
  const getList = useCallback(queryTable(request), [request]);

  // 获取导出函数
  const [exporting, exportFunc] = useExport(expfunc);

  const handleExport = useCallback(() => {
    const formData = ref.current ? ref.current.getFieldsValue() : {};
    exportFunc({ ...formData, ...params });
  }, [exportFunc, params]);

  // 添加导出按钮
  const renderToolbar = useCallback(() => {
    const acts = [];
    if (toolBarRender) {
      acts.push(...toolBarRender());
    }

    if (typeof expfunc === 'function') {
      acts.push(
        <Button loading={exporting} key="export" icon={<UploadOutlined />} onClick={handleExport}>
          导出
        </Button>,
      );
    }

    return acts;
  }, [toolBarRender, exporting, handleExport, expfunc]);

  return (
    <ProTable
      {...leftProps}
      params={params}
      formRef={ref}
      request={getList}
      toolBarRender={renderToolbar}
    />
  );
};
