import { loadScript } from '@/utils/commons';
import { PROJECT_NAME } from '@/config';

export const loadPageSpy = (title) => {

  if (import.meta.env.DEV || window.$pageSpy) return

  const PageSpySrc = [
    'https://page-spy.mycht.cn/page-spy/index.min.js',
    'https://page-spy.mycht.cn/plugin/data-harbor/index.min.js',
    'https://page-spy.mycht.cn/plugin/rrweb/index.min.js',
  ];

  Promise.all(PageSpySrc.map((src) => loadScript(src))).then(() => {
    // 注册插件
    PageSpy.registerPlugin(new DataHarborPlugin({ maximum: 2 * 1024 * 1024 }));
    // 实例化 PageSpy
    window.$pageSpy = new PageSpy({ api: 'page-spy.mycht.cn', project: PROJECT_NAME, title: title, autoRender: false });
  });
};

export const uploadPageSpyLog = () => {
  window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
}

export const PageSpyLog = () => {
  return (
    <>
      {window.$pageSpy && (
        <a
          className='text-primary'
          onClick={() => {
            window.$pageSpy.triggerPlugins('onOfflineLog', 'download');
            window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
          }}>
          上传Debug日志 ({window.$pageSpy.address.substring(0, 4)})
        </a>
      )}
    </>
  );
};
