import { scanAccountMethod } from '@/request/api';
import { useFlowStore } from '@/stores';
import router                                from '@/router';

import { platformIsAIO, platformIsAIO_1 } from '@/platform';

export function waitFor(condition: () => boolean | Promise<boolean>, timeout: number = 300 * 1000) {
  const start = Date.now();
  const { promise, resolve, reject } = Promise.withResolvers<void>();
  const check = async () => {
    try {
      if (await condition()) resolve();
      else if (timeout && Date.now() - start >= timeout) reject({ message: 'waitForBridge timeout' });
      else requestAnimationFrame(check);
    } catch (e) {
      reject(e);
    }
  };
  return check().then(
    () => promise,
    () => promise
  );
}

export default function bridgeLoader(): DEV.Loader {
  window.AIO ??= {};
  window.AIO.scan ??= (value) => {
    if (!value) return -1;
    const event = new CustomEvent('scan', { detail: { code: 0, data: { code: value, state: 0, type: -1 } } });
    window.bridge.dispatchEvent(event);
    return 0;
  };
  window.AIO.print ??= (value) => {
    return (window as any).sixWisdom?.printPdfByUrl?.(value) ?? (function() { throw { message: `当前环境不支持` } })();
  };

  return async function (app, config) {
    const scanned = config.image.el?.includes('scan');
    if (platformIsAIO_1()) window.bridge = new EventTarget() as InstanceType<typeof Bridge>;
    else if (platformIsAIO()) await waitFor(() => window.bridge != null);
    window.bridge.addEventListener('scan', async ({ detail }) => {
      if (detail.code !== 0 || detail.data?.code == null) return;
      const route = unref(router.currentRoute);
      if (route.meta?.scan) {
        const { Toast } = await import(`@/platform/toast.ui`);
        if (!scanned) Toast.warning(`系统禁止扫码`)
        else {
          const toast = Toast.loading(100, { message: '加载中' });
          const data = await scanAccountMethod(detail.data.code).catch(() => {});

          if (data) {
            const path = data?.path ?? (route?.path === '/screen' ? useFlowStore().flow.next : route?.path);
            const key = Date.now();
            sessionStorage.setItem(`scan_${key}`, JSON.stringify(data));
            await router.replace({ path, query: { scan: key } });
            Toast.success('扫码成功');
          }

          toast.close();
        }
      } else import(`@/platform/notify.ui`).then(({ Notify }) => { Notify.warning(`请返回首页后，再进行扫码！`); });
    });
  };
}
