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

export const loadPageSpy = (title) => {

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

  const PageSpyConfig = { api: 'page-spy.mycht.cn', project: PROJECT_NAME, title: title, autoRender: false };
  const PageSpySrc = [
    'https://page-spy.mycht.cn/page-spy/index.min.js'+`?${BUILD_VERSION}`,
    'https://page-spy.mycht.cn/plugin/data-harbor/index.min.js'+`?${BUILD_VERSION}`,
    'https://page-spy.mycht.cn/plugin/rrweb/index.min.js'+`?${BUILD_VERSION}`,
  ];

  Promise.all(PageSpySrc.map((src) => loadScript(src))).then(() => {
    // 注册插件
    window.$harbor = new DataHarborPlugin();
    window.$rrweb = new RRWebPlugin();
    [window.$harbor, window.$rrweb].forEach(p => {
      PageSpy.registerPlugin(p)
    })
    window.$pageSpy = new PageSpy(PageSpyConfig);
  });
};

export const uploadPageSpyLog = async () => {
  // window.$pageSpy.triggerPlugins('onOfflineLog', 'upload');
  if (window.$pageSpy) {
    await window.$harbor.upload() // 上传日志 { clearCache: true, remark: '' }
    alert('Success')
  } else {
    alert('Failure')
  }
}

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>
      )}
    </>
  );
};
