/*
 * @Author: 赵伟
 * @Date: 2024-04-28 11:49:48
 * @Description: 页面状态缓存，pop 回到这个页面的时候，重新构建之前的状态
 */

import { parseJsonText } from '@/utils';
import { useCallback, useState } from 'react';

const pageKeys: string[] = [];
// let stateCaches: Record<string, any> = {};

// 获取页面缓存
const getCacheState = (key: string) => {
  const jsonStr = sessionStorage.getItem(key);
  if (jsonStr) {
    removeCacheState(key);
    return parseJsonText(jsonStr);
  }
  return undefined;
};

// 移除页面 state 缓存
const removeCacheState = (key: string) => {
  sessionStorage.removeItem(key);
  const index = pageKeys.indexOf(key);
  if (index !== -1) {
    pageKeys.splice(index, 1);
  }
};

/**
 * 移除所有页面 state 缓存
 */
export const removeAllPageCacheState = () => {
  pageKeys.forEach((key) => {
    sessionStorage.removeItem(key);
  });
};

/**
 * 缓存页面数据
 */
export const useCacheState = () => {
  const { pathname } = window.location;
  const key = 'pagecache:' + pathname;

  const setCacheState = useCallback(
    (state?: any) => {
      if (state) {
        pageKeys.push(key);
        sessionStorage.setItem(key, JSON.stringify(state));
      }
    },
    [key],
  );

  const [cacheState] = useState(() => getCacheState(key));
  return [cacheState, setCacheState] as const;
};
