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, beforeSearchSubmit, ...leftProps } = props;

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

  // 导出函数需要使用的 params
  const exportParams = useRef()
  const handleBeforSearch = (params) => {
    if (typeof beforeSearchSubmit === 'function') {
      exportParams.current = beforeSearchSubmit(params);
    } else {
      exportParams.current = params;
    }
    return exportParams.current;
  }

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

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

  const handleExport = useCallback(() => {
    if (!exportParams.current) {
      const formData = ref.current ? ref.current.getFieldsValue() : {};
      exportParams.current = { ...formData, ...params }
    }
    exportFunc(exportParams.current);
  }, [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}
      beforeSearchSubmit={handleBeforSearch}
    />
  );
};
