/**
 * @description 全局错误日志采集，捕获 JS 运行时异常与 Vue 组件错误
 * @author D吕贺034244311
 * @date 20260615
 */
import { getCurrentInstance } from 'vue'
import store from '@/store'
import { isString, isArray } from '@/utils/validate'
import settings from '@/settings'

const { errorLog: needErrorLog } = settings

function checkNeed() {
  const env = import.meta.env.MODE
  if (isString(needErrorLog)) {
    return env === needErrorLog
  }
  if (isArray(needErrorLog)) {
    return needErrorLog.includes(env)
  }
  return false
}

if (checkNeed()) {
  // Vue 3 使用 app.config.errorHandler
  // 这里在 app 创建后设置，通过延迟设置
  window.__setErrorhandler__ = function(app) {
    app.config.errorHandler = function(err, vm, info) {
      setTimeout(() => {
        store.dispatch('errorLog/addErrorLog', {
          err,
          vm,
          info,
          url: window.location.href
        })
        console.error(err, info)
      }, 0)
    }
  }
}
