import { defineStore } from "pinia";
import { store } from "@/store";
import { PageDataCollection } from "@/types/page";
import { get, set, cloneDeep, omit, pickBy, isUndefined } from "lodash-es";

export const usePageParamsStore = defineStore({
  id: "ag-page-params",
  state: (): { pageDataMap: PageDataCollection } => ({
    pageDataMap: {}
  }),
  actions: {
    /** 保存页面参数 */
    setPageParams(path: string, params: Record<string, any>, overwrite: boolean = false) {
      const pageData = get(this.pageDataMap, path);
      if (!pageData) {
        set(this.pageDataMap, path, {
          path,
          params: cloneDeep(params),
          state: {},
          lastVisitTime: Date.now(),
          overwrite
        });
      } else {
        set(pageData, 'params', cloneDeep(params));
        set(pageData, 'lastVisitTime', Date.now());
        if (overwrite !== undefined) {
          set(pageData, 'overwrite', overwrite);
        }
      }
    },

    /** 获取页面参数 */
    getPageParams(path: string): Record<string, any> {
      return cloneDeep(get(this.pageDataMap, `${path}.params`, {}));
    },

    /** 获取页面参数及覆盖标志，读取后重置覆盖标志 */
    getPageParamsWithOverwrite(path: string): { params: Record<string, any>; overwrite: boolean } {
      const pageData = get(this.pageDataMap, path);
      const params = cloneDeep(get(pageData, 'params', {}));
      const overwrite = get(pageData, 'overwrite', false);
      if (pageData) {
        set(pageData, 'overwrite', false);
      }
      return { params, overwrite };
    },



    /** 保存页面状态 */
    setPageState(path: string, key: string, value: any) {
      const pageData = get(this.pageDataMap, path);
      if (!pageData) {
        set(this.pageDataMap, path, {
          path,
          params: {},
          state: { [key]: value },
          lastVisitTime: Date.now()
        });
      } else {
        set(pageData.state, key, value);
        set(pageData, 'lastVisitTime', Date.now());
      }
    },

    /** 获取页面状态 */
    getPageState(path: string, key?: string): any {
      const state = get(this.pageDataMap, `${path}.state`);
      if (isUndefined(state)) return undefined;
      return key ? get(state, key) : state;
    },

    /** 清理单个页面数据 */
    clearPageData(path: string) {
      this.pageDataMap = omit(this.pageDataMap, path);
    },

    /** 清理所有页面数据 */
    clearAllPageData() {
      this.pageDataMap = {};
    },

    /** 清理过期页面数据（默认清理30分钟前的数据） */
    clearExpiredData(maxAge: number = 30 * 60 * 1000) {
      const now = Date.now();
      this.pageDataMap = pickBy(this.pageDataMap, (data) => {
        return now - data.lastVisitTime <= maxAge;
      });
    }
  },
  getters: {
    /** 获取所有已存储的页面路径 */
    getStoredPaths(state): string[] {
      return Object.keys(state.pageDataMap);
    }
  }
});

export function usePageParamsStoreHook() {
  return usePageParamsStore(store);
}
