bridge.loader.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { getNextProcess, scanAccountMethod } from '@/request/api';
  2. import router from '@/router';
  3. import { platformIsAIO, platformIsAIO_1 } from '@/platform';
  4. export function waitFor(condition: () => boolean | Promise<boolean>, timeout: number = 300 * 1000) {
  5. const start = Date.now();
  6. const { promise, resolve, reject } = Promise.withResolvers<void>();
  7. const check = async () => {
  8. try {
  9. if (await condition()) resolve();
  10. else if (timeout && Date.now() - start >= timeout) reject({ message: 'waitForBridge timeout' });
  11. else requestAnimationFrame(check);
  12. } catch (e) {
  13. reject(e);
  14. }
  15. };
  16. return check().then(
  17. () => promise,
  18. () => promise
  19. );
  20. }
  21. export default function bridgeLoader(): DEV.Loader {
  22. window.AIO ??= {};
  23. window.AIO.scan ??= (value) => {
  24. if (!value) return -1;
  25. const event = new CustomEvent('scan', { detail: { code: 0, data: { code: value, state: 0, type: -1 } } });
  26. window.bridge.dispatchEvent(event);
  27. return 0;
  28. };
  29. window.AIO.print ??= (value) => {
  30. (window as any).sixWisdom.printPdfByUrl(value);
  31. };
  32. return async function () {
  33. if (platformIsAIO_1()) window.bridge = new EventTarget() as InstanceType<typeof Bridge>;
  34. if (platformIsAIO()) {
  35. await waitFor(() => window.bridge != null);
  36. window.bridge.addEventListener('scan', async ({ detail }) => {
  37. if (detail.code !== 0 || detail.data?.code == null) return;
  38. const route = unref(router.currentRoute);
  39. if (route.meta?.scan) {
  40. const { Toast } = await import(`@/platform/toast.ui`);
  41. const toast = Toast.loading(100, { message: '加载中' });
  42. const data = await scanAccountMethod(detail.data.code).catch(() => {});
  43. if (data) {
  44. const path = data?.path ?? (route?.path === '/screen' ? await getNextProcess().catch(() => route?.path) : route?.path);
  45. const key = Date.now();
  46. sessionStorage.setItem(`scan_${key}`, JSON.stringify(data));
  47. await router.replace({ path, query: { scan: key } });
  48. Toast.success('扫码成功');
  49. }
  50. toast.close();
  51. } else import(`@/platform/notify.ui`).then(({ Notify }) => { Notify.warning(`请返回首页后,再进行扫码!`); });
  52. });
  53. }
  54. };
  55. }