// #ifdef H5
import { initEnv } from 't-comm/lib/env/env';
// #endif

const pathWhiteList = [
  'web-container',
  'ai-room-pc',
  'noredirect=true',
];

export function isInIFrame() {
  const res = window.frames.length != parent.frames.length;
  return res;
}
const MESSAGE_TYPE_MAP = {
  ROUTE_CHANGE: 'ROUTE_CHANGE',
};


export const MESSAGE_HANDLER = {
  [MESSAGE_TYPE_MAP.ROUTE_CHANGE]: handleRouteChange,
};

function handleRouteChange(event: any) {
  const { data } = event.data;

  const newQuery = {
    ...data.query,
    webContainerPath: encodeURIComponent(data.webContainerPath),
  };
  const newUrl = composeUrlQuery(window.location.href.split('?')[0], newQuery);


  if (newUrl === window.location.href) {
    return;
  }
  window.history.replaceState('', '', newUrl);
}

export function sendMessageToTop(type: string, data: any) {
  // #ifdef H5
  window.parent.postMessage({ type,  data }, '*');
  // #endif
}

function sendToTopWindow(path: string, query: Record<string, string> = {}) {
  if (!isInIFrame()) {
    return;
  }

  sendMessageToTop(MESSAGE_TYPE_MAP.ROUTE_CHANGE, {
    webContainerPath: path,
    query,
  });
}

const getQueryStr = (query: Record<string, string> = {}): string => Object.keys(query).map(item => `${item}=${query[item]}`)
  .join('&');

export function composeUrlQuery(url = '', query = {}) {
  const baseUrl = url.split('?')[0];
  const originQueryStr = url.split('?')[1] || '';

  let originQuery = {};

  if (originQueryStr) {
    originQuery = originQueryStr.split('&')
      .reduce((acc: Record<string, string>, item) => {
        const list = item.split('=');

        if (list[0]) {
          acc[list[0]] = list[1] || '';
        }
        return acc;
      }, {});
  }

  const queryStr = getQueryStr({
    ...query,
    ...originQuery,
  });

  const result = `${baseUrl}?${queryStr}`;


  return result;
}

export function changeCurrentRouteInPc(route: any, router: any) {
  // #ifdef H5
  const env = initEnv();
  const isWhite = pathWhiteList.find(item => window.location.href?.includes(item));
  // const isDebug = process.env.NODE_ENV?.startsWith('development');
  const isPCWeixin = navigator.userAgent.includes('WindowsWechat')
    || navigator.userAgent.includes('MacWechat');


  const shouldRedirect = env.isPc
    && !isWhite
    && window.self === window.parent
    && !isPCWeixin
    && !route.path.includes('web-container');

  const shouldRedirectBack = (!env.isPc
    || window.self !== window.parent)
    && route.path.includes('web-container');


  if (shouldRedirect) {
    router.replace({
      path: 'web-container',
      query: {
        ...(route.query || {}),
        webContainerPath: encodeURIComponent(route.aliasPath || route.path),
      },
    });
  } else if (shouldRedirectBack && route.query?.webContainerPath) {
    const newPath = decodeURIComponent(route.query?.webContainerPath);

    console.log('newPath', newPath);
    delete route.query.webContainerPath;
    router.replace({
      path: newPath,
      query: route.query,
    });
  }
  // #endif
}


export function hookRouterInIframe(router: any) {
  // #ifdef H5
  router.afterEach((to: any) => {
    sendToTopWindow(to.aliasPath || to.path, to.query);
  });
  // #endif
}
