import { processMethod, scanAccountMethod } from '@/request/api';
import router                               from '@/router';

import type { RouteLocation } from 'vue-router';


export interface globalAIO {
  scan(value: string): number;
  print(value: string): void;
}

declare var window: Window & typeof globalThis & { AIO: globalAIO };


export default function bridgeLoader(): DEV.Loader {
  async function scan(value: string, route?: RouteLocation) {
    const { Toast } = await import(`@/platform/toast.ui`);
    const toast = Toast.loading(100, { message: '加载中' });
    const data = await scanAccountMethod(value).catch(() => {});

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


  return async function() {
    window.AIO ??= {} as globalAIO;

    window.AIO.scan = (value) => {
      if ( !value ) return -1;

      const route = unref(router.currentRoute);

      if ( !route.meta?.scan ) {
        import(`@/platform/notify.ui`).then(({ Notify }) => { Notify.warning(`请返回首页后，再进行扫码！`); });
        return 1;
      }
      scan(value, route);
      return 0;
    };

    window.AIO.print = (value) => {
      (
        window as any
      ).sixWisdom.printPdfByUrl(value);
    };
  };
}
