import React, { useContext } from 'react';
import {
  ConfigProvider,
  Breadcrumb as AntdBreadcrumb,
  BreadcrumbProps,
} from 'antd';
import { Menu } from '../Menu';
import classNames from 'classnames';
import BreadcrumbItem, { BreadcrumbItemInterface } from './BreadcrumbItem';
import './style/index.less';
import { getUuid } from '@btri-ui/utils';

interface ExtraProperty {
  Item: BreadcrumbItemInterface;
}

const Breadcrumb = (props: BreadcrumbProps & ExtraProperty) => {
  // 为了与 antd 的生态保持兼容性，我们要求必须要使用 `.@{ant-prefix}` 变量来生成类名
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('btri-breadcrumb');
  const { children } = props;

  let overlayMenu;
  if ((children as Array<any>).length > 3) {
    const overlay = (children as Array<any>).slice(1, -2).map(Item => {
      const { children, href } = Item.props;
      return (
        <Menu.Item key={getUuid()}>
          <a href={href}>{children}</a>
        </Menu.Item>
      );
    });
    overlayMenu = <Menu>{overlay}</Menu>;
  }
  const crumbs = overlayMenu
    ? [
        ...(children as Array<any>).slice(0, 1),
        <BreadcrumbItem
          href="#"
          overlay={overlayMenu}
          className={`${prefixCls}-ellipsis`}
          isOutEllipsis={true}
          key={getUuid()}
        >
          <span>...</span>
        </BreadcrumbItem>,
        (children as Array<any>).slice(-2),
      ]
    : children;

  return (
    <AntdBreadcrumb {...props} className={classNames(`${prefixCls}-box`)}>
      {crumbs}
    </AntdBreadcrumb>
  );
};
Breadcrumb.Item = BreadcrumbItem;
export { Breadcrumb };
