import dayjs from 'dayjs';
import { isProdMode } from './env';
import { isNewVersion } from './versionUpdate';
// 监听前端异常事件，用于捕获错误
export default function onError() {
  window.addEventListener('error', (e) => errorHandler(e), true);
  // 【code、api】异常收集处理函数
  const errorHandler = (e) => {
    // console.log('🚀 ~ file: error.ts ~ line 71 ~ errorHandler ~ e', e);
    // 要收集的信息对象
    const basicInfo = {
      errType: e.errType || '运行错误',
      createDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      projectId: 'pca-tuoren',
      projectName: document.title,
      projectUrl: window.location.href,
      message: '',
    } as any;
    const target = e.target || e.srcElement;
    if (
      target instanceof HTMLElement &&
      ['LINK', 'SCRIPT', 'IMG'].indexOf(target.nodeName) !== -1
    ) {
      // 下载资源失败
      // @ts-ignore
      const src = target.src || target.href;
      if (window.location.href.indexOf(src) !== 0) {
        basicInfo.message = 'Not Found: ' + e.target.src;
        basicInfo.errType = '资源引入错误';
        // 生产环境下才判断 version 版本 进行页面刷新
        isProdMode() ? isNewVersion() : '';
      }
    } else {
      const str = 'ResizeObserver loop limit exceeded';
      basicInfo.message = e.message === str ? '可忽略错误: ' + str : e.message;
    }
    console.log('🚀 ~ file: error.ts ~ line 66 ~ errorHandler ~ basicInfo', basicInfo);
  };
}
