import React from 'react';
import { Breadcrumb } from 'antd';
import { useRouter } from 'next/router';
import styled from 'styled-components';

const BreadcrumbWrap = styled.div`
  position: relative;
  width: 100%;
  display: flex;
  align-content: center;
  justify-content: flex-start;
  .title {
    font-size: 13px;
    font-weight: 400;
    color: #666666;
    margin-bottom: 0.75rem;
  }
`;

const BreadcrumbView: React.FC = () => {
  // 路由钩子
  const router = useRouter();
  // 路由对应列表
  const routerList = [
    {
      name: '云享商城',
      path: 'mall',
      children: [{ name: '商品详情', path: 'product' }],
    },
    {
      name: '行业服务',
      path: 'service',
      children: [{ name: '服务详情', path: 'detail' }],
    },
    {
      name: '购物车',
      path: 'cart',
      children: [{ name: '提交订单', path: 'submit' }],
    },
    {
      name: '我的订单',
      path: 'order',
      children: [
        { name: '提交成功', path: 'success' },
        { name: '订单详情', path: 'product' },
      ],
    },
    { name: '设备租赁', path: 'rent' },
    { name: '执照培训', path: 'train' },
    { name: '飞手约单', path: 'flyer' },
  ];
  // 转换路由
  const getCurrentRouter = () => {
    // 首先分割所有的路由
    const route = router?.pathname?.split('/').filter((i) => i);
    // 找到一级路由的元素
    const item = routerList?.find((v) => v.path === route[0]);
    // 拍平一级元素的路由地址
    const arr = [item, ...(item?.children || [])];
    // 转换路由数据
    const brr = route
      ?.map((i, j) => {
        const title = arr?.find((n) => n?.path === i)?.name;
        const href = `/${router?.pathname
          .split('/')
          .slice(1, j + 2)
          .join('/')}`;
        return { title, href };
      })
      ?.filter((i) => i.title); // 过滤掉没有title的项
    // 最后一项不跳转
    brr[brr.length - 1] = { title: brr[brr.length - 1]?.title, href: '' };
    return brr;
  };
  return (
    <BreadcrumbWrap>
      <div className="title">您的位置：</div>
      <Breadcrumb
        separator=">"
        items={[
          {
            title: '首页',
            href: '/',
          },
          ...getCurrentRouter(),
        ]}
      />
    </BreadcrumbWrap>
  );
};

export default BreadcrumbView;
