import qs from 'query-string';
import { useRef, useState } from 'react';

// 解决ProTable组件支持路由储存参数针对hash路由支持异常问题，它会在路由#前面加上?name-name形式，切换到目标页面还会保留参数，导致路由参数混乱
type ParamsProps = Record<string, any>;
type InitialFormatterProps = (values: ParamsProps) => ParamsProps;
type DefaultQueryProps = () => ParamsProps;
interface KeepAliveProps {
  initialFormatter?: InitialFormatterProps; // 用于格式化初始参数，一般用于时间范围选择组件
  defaultQuery?: DefaultQueryProps | ParamsProps; // 用于支持路由本身存在search参数的页面
}
export function useKeepAlive<T = ParamsProps>(props?: KeepAliveProps) {
  const [url, urlSearchString] = location.href.split('?');
  const { initialFormatter, defaultQuery: defaultQueryTarget } = props || {};

  const { current: defaultQuery } = useRef(
    typeof defaultQueryTarget === 'function'
      ? defaultQueryTarget()
      : defaultQueryTarget,
  );

  const searchParams = qs.parse(urlSearchString);
  const { current: initialAliveQuery } = useRef(
    initialFormatter ? initialFormatter(searchParams) : searchParams,
  );
  const [aliveQuery, setAliveQuery] = useState<T>({
    ...initialAliveQuery,
    ...defaultQuery,
  });

  const saveAliveQuery = (newAliveQuery: T) => {
    const query = {
      ...aliveQuery,
      ...newAliveQuery,
    };
    const newUrlSearchString = qs.stringify(query as ParamsProps);
    const newHref = `${url}?${newUrlSearchString}`;
    if (location.href === newHref) return;
    setAliveQuery(query);
    window.history.replaceState({}, '', newHref);
  };

  return { initialAliveQuery, aliveQuery, saveAliveQuery };
}
