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

/**
 * 页面参数管理组合式函数
 * 用于管理页面间的参数传递和获取
 */
export function usePageParams() {
  const store = usePageParamsStoreHook();
  const route = useRoute();
  const router = useRouter();

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

  /** 设置当前页面参数 */
  const setPageParams = (params: Record<string, any>, overwrite: boolean = false) => {
    store.setPageParams(currentPath.value, params, overwrite);
  };

  /** 获取当前页面参数 */
  const getPageParams = (): Record<string, any> => {
    return store.getPageParams(currentPath.value);
  };

  /** 获取当前页面参数及覆盖标志，读取后覆盖标志自动重置为false */
  const getPageParamsWithOverwrite = (): { params: Record<string, any>; overwrite: boolean } => {
    return store.getPageParamsWithOverwrite(currentPath.value);
  };

  /** 获取指定路径的页面参数 */
  const getPageParamsByPath = (path: string): Record<string, any> => {
    return store.getPageParams(path);
  };

  /** 设置页面参数并跳转到目标页面 */
  const navigateWithParams = (path: string, params: Record<string, any>, overwrite: boolean = false) => {
    store.setPageParams(path, params, overwrite);
    router.push({ path, query: params });
  };

  /** 清除当前页面参数 */
  const clearPageParams = () => {
    store.clearPageData(currentPath.value);
  };

  return {
    currentPath,
    route,
    router,
    setPageParams,
    getPageParams,
    getPageParamsWithOverwrite,
    getPageParamsByPath,
    navigateWithParams,
    clearPageParams
  };
}
