import React, { useEffect } from 'react';
import { Breadcrumb, Button, Row } from 'antd';
import useMergedState from 'rc-util/lib/hooks/useMergedState';
import { getBreadcrumbProps, conversionFromLocation } from './getBreadcrumbProps';
import type { MenuDataItem } from './typings';
import { getMenuData } from '@ant-design/pro-layout';
import { Prompt, useLocation, history } from 'umi';
import qs from 'qs';

export const BreadcrumbContext = React.createContext<any>([]);
const PageComponent = (props: any) => {
  const [menuInfoData, setMenuInfoData] = useMergedState<{
    breadcrumb?: Record<string, MenuDataItem>;
    breadcrumbMap?: Map<string, MenuDataItem>;
    menuData?: MenuDataItem[];
  }>(() => getMenuData(props.route?.routes || []));
  const location = useLocation();
  const { breadcrumbMap } = menuInfoData;

  const itemRender = (route, params, routes, paths) => {
    const last = routes.indexOf(route) === routes.length - 1;
    return last || !route.component ? (
      <span>{route.breadcrumbName}</span>
    ) : (
      <a
        onClick={() => {
          breadClick(route);
        }}
      >
        {route.breadcrumbName}
      </a>
    );
  };

  const breadcrumbProps = getBreadcrumbProps({ ...props, breadcrumbMap, itemRender });
  useEffect(() => {
    const infoData = getMenuData(props.route?.routes || []);
    // 稍微慢一点 render，不然会造成性能问题，看起来像是菜单的卡顿
    const animationFrameId = requestAnimationFrame(() => {
      setMenuInfoData(infoData);
    });
    return () => window.cancelAnimationFrame && window.cancelAnimationFrame(animationFrameId);
  }, [props.route, props.location?.pathname]);

  useEffect(() => {
    if (props.onChange) {
      props.onChange(breadcrumbProps.routes);
    }
  }, [props.location.pathname]);

  const handleBeforeLeave = (e, action) => {
    // 当前 history 跳转的 action，有 PUSH、REPLACE 和 POP 三种类型
    if (action !== 'PUSH' || e.pass) {
      // @ts-ignore
      document.getElementById('pdmRightZone').scrollTop = 0;
      return true;
    }
    handleLink(e, location.query);
    return false;
  };

  const handleLink = (value: any, query = {}, actionType = 'push') => {
    const valueParams = { ...value };
    const beforeQuery = getBackQueryParams(value.pathname, query);
    valueParams.query = { ...beforeQuery, ...valueParams.query };
    valueParams.search = `?${qs.stringify(valueParams.query)}`;
    // @ts-ignore
    history[actionType]({
      ...valueParams,
      pass: true, // 代表不拦截
    });
  };

  const breadClick = (route) => {
    const routeValue = {
      pathname: route.path,
    };
    handleLink(routeValue, location.query || {}, 'push');
  };

  // 获取回填的参数,所需的参数放在meta里面
  const getBackQueryParams = (pathname: string, beforeQuery = {}) => {
    const routeList = conversionFromLocation(
      {
        pathname,
      },
      breadcrumbMap,
      {},
    );
    let metaParams: string[] = [];
    routeList?.map((item: any) => {
      item.meta.params && (metaParams = metaParams.concat(item.meta.params));
    });
    const routeQuery = {};
    [...new Set(metaParams)].map((item) => {
      routeQuery[item] = beforeQuery[item];
    });
    return routeQuery;
  };

  return (
    <>
      <Prompt when={true} message={handleBeforeLeave} />
      <Row align="middle" justify="space-between">
        <Breadcrumb {...breadcrumbProps}></Breadcrumb>
      </Row>
    </>
  );
};

export default PageComponent;
