import { computed, watch } from "vue";
import { useRoute } from "vue-router";
import { usePageParamsStoreHook } from "@/store/modules/pageParams";

/**
 * 页面状态管理组合式函数
 * 用于保存和恢复页面的状态数据（如表单数据、分页、选中项等）
 */
export function usePageState<T = any>(options?: {
  autoSave?: boolean;
  watchKeys?: string[];
}) {
  const store = usePageParamsStoreHook();
  const route = useRoute();
  const { autoSave = true, watchKeys = [] } = options || {};

  const currentPath = computed(() => route.path);

  /** 设置状态 */
  const setPageState = (key: string, value: T) => {
    store.setPageState(currentPath.value, key, value);
  };

  /** 获取状态 */
  const getPageState = (key?: string): T | Record<string, any> | undefined => {
    return store.getPageState(currentPath.value, key);
  };

  /** 批量设置状态 */
  const setPageStateBatch = (state: Record<string, T>) => {
    Object.entries(state).forEach(([key, value]) => {
      setPageState(key, value);
    });
  };

  /** 清理当前页面状态 */
  const clearPageState = () => {
    store.clearPageData(currentPath.value);
  };

  /** 监听并自动保存状态 */
  const watchAndSave = (reactiveState: Record<string, any>) => {
    if (autoSave) {
      watch(
        () => reactiveState,
        (newVal) => {
          Object.entries(newVal).forEach(([key, value]) => {
            if (watchKeys.length === 0 || watchKeys.includes(key)) {
              store.setPageState(currentPath.value, key, value);
            }
          });
        },
        { deep: true }
      );
    }
  };

  /** 恢复保存的状态到响应式对象 */
  const restoreState = (reactiveState: Record<string, any>) => {
    const savedState = getPageState();
    if (savedState) {
      Object.assign(reactiveState, savedState);
    }
  };

  return {
    currentPath,
    setPageState,
    getPageState,
    setPageStateBatch,
    clearPageState,
    watchAndSave,
    restoreState
  };
}
