import { ComponentPublicInstance } from "vue";

export function vueErrorHandler(
  error: unknown,
  instance: ComponentPublicInstance | null,
  // `info` is a Vue-specific error info,
  // e.g. which lifecycle hook the error was thrown in
  info: string
) {
  // window._hmt.push(["_trackEvent", "Vue组件错误"]);
  logger({
    lvl: "error",
    cnl: ["console", "server"],
    key: "Vue组件错误",
    pgu: "AUTO",
    ext: {
      error,
      errorJSON: JSON.stringify(error, (key, value) =>
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        key === "token" ? "" : value
      ),
      info,
    },
  });
  console.trace("vue error", instance, info);
  throw error;
}

window.addEventListener("error", function (event) {
  logger({
    key: "全局JS错误",
    cnl: ["console", "local", "server"],
    pgu: "AUTO",
    ext: {
      message: event.message,
      errorJSON: JSON.stringify(event.error, (key, value) =>
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        key === "token" ? "" : value
      ),
      errorName: event.error.name,
      errorMessage: event.error.message,
      errorStack: event.error.stack,
      errorFileName: event.error.filename,
      errorLineNo: event.error.lineno,
      errorColNo: event.error.colno,
    },
  });
  console.trace(event);
});

window.addEventListener("unhandledrejection", function (event) {
  // 此错误由上传阿里云日志触发，会被重复好几次
  // 改为fetch，阿里云日志的错误不应该触发到这里

  try {
    // 会造成死循环，logger.log 在网络异常的情况下，会有unhandledrejection
    setTimeout(
      () =>
        logger({
          key: "unhandledrejection",
          cnl: ["console", "local", "server"],
          pgu: "AUTO",
          stk: JSON.stringify(event),
          dtl: event.reason,
          ejn: JSON.stringify(event.reason),
        }),
      10 * 1000
    );
    console.trace(event);
  } catch {
    logger({
      cnl: ["console", "local"],
      pgu: "AUTO",
      dtl: "promise error log",
    });
  }
});

window.addEventListener("rejectionhandled", function (event) {
  console.log("rejectionhandled", event); // 似乎并不触发
  logger({
    pgu: "AUTO",
    cnl: ["console", "local", "server"],
    dtl: event.reason,
  });
});
