import { STORAGE_CHILD_KEY } from './config';


function getRouteQueryChildInfo(routeQuery: Record<string, any> = {}) {
  const { QUERY_KEY  } = STORAGE_CHILD_KEY;
  const queryInfo = routeQuery[QUERY_KEY];

  let childInfo;

  if (queryInfo) {
    try {
      childInfo = JSON.parse(decodeURIComponent(queryInfo));
    } catch (err) {
      try {
        childInfo = JSON.parse(decodeURIComponent(decodeURIComponent(queryInfo)));
      } catch (err) {
        childInfo = '';
      }
    }
    if (childInfo) {
      return childInfo;
    }
  }
}


function getStorageChildInfo(childId: string | number) {
  const { STORAGE_KEY } = STORAGE_CHILD_KEY;
  let childInfo;

  const localStr = localStorage.getItem(STORAGE_KEY);

  if (localStr) {
    try {
      const childMap = JSON.parse(localStr);
      childInfo = childMap[childId];
    } catch (err) {
      childInfo = '';
    }

    if (childInfo) {
      return childInfo;
    }
  }
}


function saveStorageChildInfo({
  childId,
  childInfo,
}: {
  childId: number | string;
  childInfo: Record<string, any>;
}) {
  if (!childInfo) return;

  const { STORAGE_KEY } = STORAGE_CHILD_KEY;
  let childMap: any = {};

  const localStr = localStorage.getItem(STORAGE_KEY);

  if (localStr) {
    try {
      childMap = JSON.parse(localStr) || {};
    } catch (err) {
      childMap = {};
    }
  }
  childMap[childId] = childInfo;
  localStorage.setItem(STORAGE_KEY, JSON.stringify(childMap));
}


export function getCachedChildInfo({
  routeQuery = {},
  childId,
  cgiRequest,
}: {
  routeQuery: Record<string, any>;
  childId: string | number;
  cgiRequest: () => Promise<any>;
}) {
  const routerQueryChildInfo = getRouteQueryChildInfo(routeQuery);
  const storageChildInfo = getStorageChildInfo(childId);
  if (routerQueryChildInfo) {
    return Promise.resolve(routerQueryChildInfo);
  }

  if (storageChildInfo) {
    return Promise.resolve(storageChildInfo);
  }

  if (typeof cgiRequest === 'function') {
    return new Promise((resolve, reject) => {
      cgiRequest().then((res) => {
        saveStorageChildInfo({
          childId,
          childInfo: res,
        });
        resolve(res);
      })
        .catch((err) => {
          reject(err);
        });
    });
  }

  return Promise.reject('请稍后重试');
}
