export function getURLSearchParams(value) {
  if (!value) value = `${location.search}&${location.hash.split('?')[1] || ''}`;
  return new URLSearchParams(value);
}

export function setSessionModalId(tag = 'modalId') {
  const params = getURLSearchParams();
  const modalId = params.get(tag);
  if (modalId) sessionStorage.setItem(tag, modalId);

  console.group(tag);
  console.log('search: ', location.search);
  console.log('hash: ', location.hash);
  console.log('modalId: ', modalId);
  console.groupEnd();

  return modalId;
}

export function getSessionModalId(tag = 'modalId') {
  const modalId = sessionStorage.getItem(tag);
  return modalId ? modalId : setSessionModalId(tag);
}

export function inform(data = {}, tag = 'modalId') {
  const modalId = getSessionModalId(tag);
  if (modalId) {
    sessionStorage.removeItem(tag);
    const message = {
      type: 'closeAnchorModal',
      data: {...data, modalId},
    }
    window.parent.postMessage(message, '*');
    console.group(tag);
    console.log('modalId: ', modalId);
    console.log('message: ', message);
    console.groupEnd();
  } else {
    try {
      const message = JSON.stringify(data);
      window.parent.postMessage(message, '*');
    } catch (e) { console.log(`通信失败：`, data); }
  }
}
