import { MoreOutlined } from '@ant-design/icons';
import { Button, Dropdown, Space } from 'antd';
import { ReactNode } from 'react';
import { useCurrentPermissions } from './GetRPermission';

interface MyTableActionsProps {
  actions: Record<string, ReactNode>;
  maxVisible?: number;
  path?: string;
}

export const MyTableActions = ({
  actions,
  maxVisible = 3,
  path,
}: MyTableActionsProps) => {
  const getCurrentPermissions = useCurrentPermissions();
  const permittedActions = getCurrentPermissions(actions, path);

  if (permittedActions.length === 0) {
    return null;
  }

  if (permittedActions.length <= maxVisible) {
    return <Space size="small">{permittedActions}</Space>;
  }

  const visible = permittedActions.slice(0, maxVisible);
  const overflow = permittedActions.slice(maxVisible);

  return (
    <Space size="small">
      {visible}
      <Dropdown
        menu={{
          items: overflow.map((node: ReactNode, index: number) => ({
            key: index.toString(),
            label: node,
          })),
        }}
      >
        <Button type="link" size="small">
          更多 <MoreOutlined />
        </Button>
      </Dropdown>
    </Space>
  );
};
