import React from 'react';
import { Button, Popconfirm, message } from 'antd';
import { ProTable } from '@ant-design/pro-components';
import { queryTable } from '@/utils/request';
import Page from './index';

export default React.forwardRef((props, ref) => {
  /**
   * request 与 ProTable 定义不同，这个只是普通的接口即可
   */
  const { request, rowKey, columns, onAdd, onDelete, onEdit, toolBarRender, optionRender, ...leftProps } = props;
  const actionRef = React.useRef();
  const hideRef = React.useRef();

  const api = React.useMemo(() => queryTable(request), [request]);

  // 统一实现操作列
  const cols = React.useMemo(() => [
    ...columns,
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      render: (_, record) => [
        (
          onEdit && 
          <Button style={{ padding: 0 }} type="link" key={1} onClick={() => onEdit(record) }>
            编辑
          </Button>
        ),
        (
          onDelete &&
          <Popconfirm
            key={3}
            title="您是否确认删除 ?"
            onConfirm={() => onDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button style={{ padding: 0 }} type="link">
              删除
            </Button>
          </Popconfirm>
        ),
        ...(optionRender ? optionRender(_, record) : []),
      ].filter(Boolean),
    },
  ], [columns, onEdit, onDelete]);

  React.useImperativeHandle(ref, () => {
    const showLoading = msg => (hideRef.current = message.loading(msg || '操作中, 请稍候...'));
    const hideLoading = () => hideRef.current && hideRef.current();
    const reload = () => actionRef.current?.reload && actionRef.current.reload();

    return {
      showLoading,
      hideLoading,
      reload,
      actionRef: actionRef,
    }
  }, []);

  return (
    <Page>
      <ProTable
        rowKey={rowKey}
        columns={cols}
        request={api}
        cardBordered
        actionRef={actionRef}
        toolBarRender={() => [
          (
            onAdd && 
            <Button
              key="1"
              type="primary"
              onClick={onAdd}
            >
              新增
            </Button>
          ),
          ...(toolBarRender ? toolBarRender() : []),
        ].filter(Boolean)}
        {...leftProps}
      />
    </Page>
  )
});