import Vue from "vue";
import { createLog } from "@/utils/logger";

Vue.config.errorHandler = (error) => {
  window._hmt.push(["_trackEvent", "Vue组件错误"]);
  createLog({
    action: "Vue组件错误",
    path: window.location,
    errorJSON: JSON.stringify(error, (key, value) =>
      key === "token" ? "" : value
    ),
    errorName: error.name,
    errorMessage: error.message,
    errorStack: error.stack,
  });
  console.trace(error);
  throw error;
};

window.addEventListener("error", function (event) {
  window._hmt.push([
    "_trackEvent",
    "全局JS错误:" +
      window.location.pathname.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
    event.message,
    "detail see ali",
  ]);
  createLog({
    action: "全局JS错误",
    page: window.location,
    message: event.message,
    errorJSON: JSON.stringify(event.error, (key, value) =>
      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，阿里云日志的错误不应该触发到这里

  // 这会触发Circular JSON error
  if (event.reason.name === "NavigationDuplicated") {
    createLog({
      action: "unhandledrejection错误",
      page: window.location.pathname,
      reason: "NavigationDuplicated",
    });
    return;
  }
  try {
    console.log(
      "unhandledrejection event",
      event,
      event.reason,
      JSON.stringify(event.reason)
    );
    // 会造成死循环，logger.log 在网络异常的情况下，会有unhandledrejection
    createLog({
      action: "unhandledrejection错误",
      page: window.location.pathname,
      reason: event.reason,
      reasonJson: JSON.stringify(event.reason),
    });
    console.trace(event);
  } catch {
    console.log("promise error log");
  }
  if (
    event.reason?.message?.includes("Box.constructor") ||
    event.reason?.message?.includes("Error: toNetInput")
  ) {
    window._hmt.push([
      "_trackEvent",
      "全局Promise未处理错误",
      event.reason.message.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
    ]);
  } else {
    window._hmt.push([
      "_trackEvent",
      "全局Promise未处理错误",
      window.location.pathname.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
      event.reason?.message?.replace(/=\w*/g, "=").replace(/\d+/g, "{id}"),
    ]);
  }
});

window.addEventListener("rejectionhandled", function (event) {
  console.log("rejectionhandled"); // 似乎并不触发
  window._hmt.push(["_trackEvent", "全局Promise已处理错误", event.reason]);
});
