import { isReactive, isRef, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Searchs } from '@/utils/searchs';

function setLoading(loading: any, val: any) {
  if (loading != undefined && isRef(loading)) {
    loading.value = val;
  } else if (loading != undefined && isReactive(loading)) {
    loading.loading = val;
  }
}

export const useAsync = async (
  func: Promise<any>,
  loading: any
): Promise<any> => {
  setLoading(loading, true);

  return await func.finally(() => setLoading(loading, false));
};

export const getTabsCache = (callBack: any) => {
  const route = useRoute();
  const searchs = new Searchs(route.path);

  const active = searchs.get(route.path);
  onMounted(() => {
    callBack(active);
  });
};

export const setTabsCaches = (current: any, key = 'current', routes: any) => {
  const searchs = new Searchs(routes.path);
  searchs.update({ [key]: current }, undefined, 'form');
  const active = searchs.get(routes.path);
  // console.log(active, 'setTabsCaches');
};

/**
 * 初始化缓存
 * @param {object} { key 默认form 关键字, saveKey 地址, current 对象, callBack 回调 }
 */
export const initCache = (params: any) => {
  const route = useRoute();
  if (!params.current) {
    return;
  }
  if (!params.key) {
    params.key = 'form';
  }
  if (!params.saveKey) {
    params.saveKey = route.path;
  }
  const searchs = new Searchs(params.saveKey);
  const active: any = searchs.get(params.saveKey);
  const model: any = params.current;
  const tempActive: any = active[params.key];
  for (const key in tempActive) {
    if (Object.prototype.hasOwnProperty.call(model, key)) {
      const item = tempActive[key];
      model[key] = item;
    }
  }
  searchs.update({ ...model }, undefined, params.key);

  onMounted(() => {
    params.callBack && params.callBack(model);
  });
};

/**
 * 设置缓存
 * @param {object} { key 默认form 关键字, saveKey 默认当前路由地址, current 对象, callBack 回调 }
 */
export const setCache = (params: any) => {
  if (!params.current || !params.saveKey) {
    return;
  }
  if (!params.key) {
    params.key = 'form';
  }

  const searchs = new Searchs(params.saveKey);
  searchs.update({ ...params.current }, undefined, params.key);
};
