import qs from 'qs';

window.console = (function (origConsole) {
  const { debug } = qs.parse(window.location.search.slice(1));
  if (debug) {
    return origConsole;
  } else {
    return {
      ...Object.keys(origConsole).reduce((all, d) => {
        all[d] = origConsole[d];
        return all;
      }, {}),
      error: function () {
        // eslint-disable-next-line prefer-rest-params
        console.log(...arguments);
      },
    };
  }
})(window.console);

// 捕获意外错误
window.addEventListener(
  'error',
  function (e) {
    e.preventDefault();
    console.error(e);
    return false;
  },
  false,
);

window.onerror = function (msg, url, lineNo, columnNo, error) {
  const string = (msg as string)?.toLowerCase();
  const substring = 'script error';
  if (string.indexOf(substring) > -1) {
    console.error('Script Error: See Browser Console for Detail');
    return false;
  }
  const message = [
    'Message: ' + msg,
    'URL: ' + url,
    'Line: ' + lineNo,
    'Column: ' + columnNo,
    'Error object: ' + JSON.stringify(error),
  ].join(' - ');
  console.error(message);
  return true;
};

window.addEventListener(
  'unhandledrejection',
  (err) => {
    console.error(err.reason);

    err.preventDefault();
  },
  false,
);

// 或者
window.onunhandledrejection = function (err) {
  console.error(err.reason);
  return true;
};
