import { useRoute } from 'vue-router';
import { Ref } from '@vue/reactivity';
import { getCurrentInstance } from 'vue';

export function useTableSession(formModel: Recordable, formParamsRef: Ref, defaultPageRef: Ref, treeParamsRef?: Ref) {
  const instance = getCurrentInstance();
  const { enableTableSession } = instance?.props || {};
  const route = useRoute();

  const { fullPath, name } = route;
  const tableSession = JSON.parse(sessionStorage[fullPath] || '{}');

  function initTableSession() {
    if (!enableTableSession) return;
    tableSession['name'] = name;
    if (tableSession['formModel']) {
      Object.assign(formModel, tableSession['formModel']);
    }
    if (tableSession['formParams']) {
      formParamsRef.value = tableSession['formParams'];
    }
    if (tableSession['defaultPage']) {
      defaultPageRef.value = tableSession['defaultPage'];
    }
    if (tableSession['treeParams'] && treeParamsRef) {
      treeParamsRef.value = tableSession['treeParams'];
    }
  }

  function setTableSession(page: number) {
    if (!enableTableSession) return;
    tableSession['formModel'] = formModel;
    tableSession['formParams'] = formParamsRef.value;
    tableSession['defaultPage'] = page;
    tableSession['treeParams'] = treeParamsRef?.value;
    sessionStorage[fullPath] = JSON.stringify(tableSession);
  }

  initTableSession();

  return { setTableSession };
}
