bridge.loader.ts 2.5 KB

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