import React, { useState, useEffect } from 'react';
import { Breadcrumb } from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import { history, useLocation } from '@umijs/max';
import './breadcrumb.less';

const CustomBreadcrumb = () => {
  // 从sessionStorage初始化面包屑数据，与Vue实例保持一致
  const [breadcrumbList, setBreadcrumbList] = useState(() => {
    return JSON.parse(sessionStorage.getItem('breadcrumb')) || [];
  });

  const [currentRouterName, setCurrentRouterName] = useState('');

  const location = useLocation();

  // 递归搜索window.dynamicRoute中匹配当前路径的路由项
  const findMatchedRoute = (routes, pathname) => {
    for (const route of routes) {
      // 检查当前路由项是否匹配
      if (route.key === pathname) {
        return route;
      }
      // 如果有子路由，递归搜索
      if (route.children && route.children.length > 0) {
        const matchedChild = findMatchedRoute(route.children, pathname);
        if (matchedChild) {
          return matchedChild;
        }
      }
    }
    return null;
  };

  // 获取当前路由的真实信息
  const getCurrentRoute = () => {
    const pathname = location.pathname || '/';
    const href = window.location.href;

    console.log('当前路径:', pathname);

    // 使用自定义函数在window.dynamicRoute中匹配当前路径
    let matchedRoute = null;
    if (window.dynamicRoute && Array.isArray(window.dynamicRoute)) {
      matchedRoute = findMatchedRoute(window.dynamicRoute, pathname);
    }

    console.log('匹配的路由:', matchedRoute);

    // 如果有匹配的路由，获取路由信息
    if (matchedRoute) {
      // 使用route.label作为标题，route.key作为路径标识符
      const routeTitle = matchedRoute.label || '未知页面';
      const routeKey = matchedRoute.key || pathname;

      return {
        name: routeKey.replace(/\//g, '_').slice(1) || 'home',
        path: pathname,
        href,
        fullPath: href,
        meta: {
          title: routeTitle,
          affix: pathname === '/'
        }
      };
    }

    // 如果没有从window.dynamicRoute中匹配到路由，使用原来的逻辑处理
    // 将路径按照/分割，获取最后一段作为名称
    const parts = pathname.split('/').filter(Boolean);

    // 根路径处理
    if (parts.length === 0) {
      return {
        name: 'home',
        path: pathname,
        href,
        fullPath: href,
        meta: {
          title: '首页',
          affix: true
        }
      };
    }

    // 获取最后一段作为页面名称
    const lastPart = parts[parts.length - 1];

    // 使用最后一段作为标题
    const routeTitle = lastPart || '未知页面';

    return {
      name: lastPart.replace(/\//g, '_') || 'home',
      path: pathname,
      href,
      fullPath: href,
      meta: {
        title: routeTitle,
        affix: pathname === '/'
      }
    };
  };

  // 生成面包屑数据 - 修复了path指向错误的问题
  const generateBreadcrumb = () => {
    // 从当前路由获取信息
    const currentRoute = getCurrentRoute();
    const { meta: { title }, name, path } = currentRoute;

    // 如果title存在，将路由信息添加到breadcrumbList数组
    if (title) {
      const newBreadcrumbList = [...breadcrumbList];
      newBreadcrumbList.push({
        name,
        path: path,  // 正确使用当前路由的path属性
        title
      });

      // 使用reduce方法对breadcrumbList进行去重处理，并过滤 business 页签
      const uniqueList = newBreadcrumbList.reduce((accumulator, current) => {
        // 过滤掉 business 页签（title 为 business 或 key 仅为 business）
        if (
          current.title === 'business' ||
          current.name === 'topnavbar00_business' ||
          current.path === '/topnavbar00/business'
        ) {
          return accumulator;
        }
        const x = accumulator.find(item => item.name === current.name);
        if (!x) {
          return accumulator.concat(current);
        } else {
          accumulator.forEach((val, i) => {
            if (val.name == current.name) {
              val.title = current.title;
              val.path = current.path;
            }
          });
          return accumulator;
        }
      }, []);

      // 将处理后的面包屑数据存储到sessionStorage中
      setBreadcrumbList(uniqueList);
      sessionStorage.setItem('breadcrumb', JSON.stringify(uniqueList));
    }
  };

  // 处理导航逻辑
  const toPath = (item) => {
    const currentRoute = getCurrentRoute();
    // 如果路径相同，点击导航则不跳转
    if (item.name === currentRoute.name) {
      return '';
    }
    // 如果是固定路由，则不跳转
    if (item.meta?.affix) {
      return '';
    } else {
      // 跳转路由
      return item.path;
    }
  };

  // 关闭面包屑项，先跳转再删除面包屑
  const cloneCurrentPage = (item, index) => {
    // 如果没有面包屑页面或只剩一个页面，跳转到根目录
    if (!breadcrumbList || breadcrumbList.length <= 1) {
      // 使用window.location.href进行有感刷新
      window.location.href = '/';
      return;
    }

    const updatedList = [...breadcrumbList];
    updatedList.splice(index, 1);

    let length = updatedList.length;
    // 先进行页面跳转
    if (currentRouterName === item.name && length > 0) {
      // 使用history进行无刷新跳转
      history.push(updatedList[length - 1].path);
    }

    // 然后删除面包屑项
    setBreadcrumbList(updatedList);
    sessionStorage.setItem('breadcrumb', JSON.stringify(updatedList));
  };

  // 处理面包屑项点击事件
  const handleItemClick = (item) => {
    const path = toPath(item);
    if (path) {
      console.log(currentRouterName, 'yp')
      // 使用history进行无刷新跳转
      history.push(path);
    }
  };

  // 组件挂载时初始化
  useEffect(() => {
    const currentRoute = getCurrentRoute();
    setCurrentRouterName(currentRoute.name);
    generateBreadcrumb();
  }, []);

  // 监听路由变化，当路由变化时触发generateBreadcrumb方法
  useEffect(() => {
    const handleRouteChange = () => {
      const currentRoute = getCurrentRoute();
      setCurrentRouterName(currentRoute.name);
      generateBreadcrumb();
    };

    // 监听浏览器前进后退事件
    window.addEventListener('popstate', handleRouteChange);

    // 重写pushState和replaceState方法以捕获更多路由变化
    const originalPushState = window.history.pushState;
    const originalReplaceState = window.history.replaceState;

    window.history.pushState = function (...args) {
      originalPushState.apply(this, args);
      handleRouteChange();
    };

    window.history.replaceState = function (...args) {
      originalReplaceState.apply(this, args);
      handleRouteChange();
    };

    // 监听hash变化（针对hash路由）
    window.addEventListener('hashchange', handleRouteChange);

    return () => {
      window.removeEventListener('popstate', handleRouteChange);
      window.removeEventListener('hashchange', handleRouteChange);
      // 还原原始方法
      window.history.pushState = originalPushState;
      window.history.replaceState = originalReplaceState;
    };
  }, [breadcrumbList, location]);

  // 当location.pathname变化时，自动更新currentRouterName
  useEffect(() => {
    const currentRoute = getCurrentRoute();
    setCurrentRouterName(currentRoute.name);
  }, [location.pathname]);

  return (
    <div className="bread-crumb" style={{ maxHeight: '32px', flexWrap: 'nowrap' }}>
      <Breadcrumb separator="" >
        {breadcrumbList.map((item, index) => (
          <Breadcrumb.Item
            key={index}
            onClick={() => handleItemClick(item)}
            className={`breadcrumb-item ${item.name === currentRouterName ? 'breadcrumb-item-active' : ''}`}
          >
            <span className="breadcrumb-item-content">
              <span className={`breadcrumb-item-text ${item.name === currentRouterName ? 'breadcrumb-item-text-active' : ''}`}>{item.title}</span>
              <CloseCircleOutlined
                className="breadcrumb-close-icon"
                onClick={(e) => {
                  e.stopPropagation();
                  cloneCurrentPage(item, index);
                }}
              />
            </span>
          </Breadcrumb.Item>
        ))}
      </Breadcrumb>
    </div>
  );
};

export default CustomBreadcrumb;