var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/eftposPay/utils/payLog.ts
var payLog_exports = {};
__export(payLog_exports, {
  default: () => payLog_default,
  usePayLog: () => usePayLog
});
module.exports = __toCommonJS(payLog_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_react = require("react");
var import_utils = require("@pisell/utils");
var STORAGE_KEY = "pisell2_eftpos_paylog";
var ERROR_KEYWORDS = ["失败", "错误", "异常", "error", "fail", "timeout", "超时"];
function generateSessionKey() {
  const ts = Date.now();
  const rand = Math.random().toString(36).substring(2, 8);
  return `eft_${ts}_${rand}`;
}
function isErrorLog(title) {
  const lower = title.toLowerCase();
  return ERROR_KEYWORDS.some((kw) => lower.includes(kw));
}
function shallowEqual(a, b) {
  if (a === b) return true;
  if (a == null && b == null) return true;
  if (a == null || b == null) return false;
  try {
    return JSON.stringify(a) === JSON.stringify(b);
  } catch {
    return false;
  }
}
function compressLogs(logs) {
  if (logs.length === 0) return [];
  const result = [];
  let i = 0;
  while (i < logs.length) {
    const current = logs[i];
    if (isErrorLog(current.t)) {
      result.push({ t: current.t, ts: current.ts, d: current.d });
      i++;
      continue;
    }
    let j = i + 1;
    while (j < logs.length && logs[j].t === current.t && !isErrorLog(logs[j].t)) {
      j++;
    }
    const count = j - i;
    if (count === 1) {
      result.push({ t: current.t, ts: current.ts, d: current.d });
    } else {
      const last = logs[j - 1];
      const entry = {
        t: current.t,
        ts: current.ts,
        count,
        lastTs: last.ts
      };
      if (current.d !== void 0) entry.d = current.d;
      if (!shallowEqual(current.d, last.d) && last.d !== void 0) {
        entry.lastD = last.d;
      }
      result.push(entry);
    }
    i = j;
  }
  return result;
}
var PayLog = class _PayLog {
  static instance;
  sessionKey = null;
  context = {};
  logs = [];
  startTime = 0;
  flushed = false;
  constructor() {
  }
  static getInstance() {
    if (!_PayLog.instance) {
      _PayLog.instance = new _PayLog();
    }
    return _PayLog.instance;
  }
  /**
   * 初始化一次交易会话
   * - 生成唯一 sessionKey
   * - 恢复上报 localStorage 中残留的旧日志
   * - 接受部分 context（后续可通过 setContext 补充）
   */
  init(context) {
    try {
      this.recoverOrphanedLogs();
      this.sessionKey = generateSessionKey();
      this.context = context || {};
      this.logs = [];
      this.startTime = Date.now();
      this.flushed = false;
      this.log("PayLog 初始化", context);
    } catch (error) {
      console.error("PayLog init error:", error);
    }
  }
  /**
   * 补充/更新上下文信息
   * 新值覆盖旧值，extra 做浅合并
   */
  setContext(partial) {
    var _a;
    if (!this.sessionKey) return;
    const { extra, ...rest } = partial;
    Object.assign(this.context, rest);
    if (extra) {
      this.context.extra = { ...((_a = this.context) == null ? void 0 : _a.extra) || {}, ...extra || {} };
    }
    this.persistToStorage();
  }
  /**
   * 记录一条日志
   */
  log(title, data) {
    if (!this.sessionKey) {
      console.warn("PayLog: 未初始化，日志将被忽略 -", title);
      return;
    }
    const entry = {
      t: title,
      ts: (0, import_dayjs.default)().format("HH:mm:ss.SSS")
    };
    if (data !== void 0) {
      entry.d = data;
    }
    this.logs.push(entry);
    this.persistToStorage();
  }
  /**
   * 上报日志到飞书并清理 localStorage
   */
  async flush(customTitle) {
    if (this.flushed || !this.sessionKey) return;
    this.flushed = true;
    const _sessionKey = this.sessionKey;
    try {
      const elapsed = ((Date.now() - this.startTime) / 1e3).toFixed(1);
      const compressed = compressLogs(this.logs);
      const { paymentType, mode, orderId } = this.context;
      const title = customTitle || `[EFTPOS] ${paymentType || "Unknown"}-${mode || "unknown"}-${orderId || "Unknown"}`;
      const content = this.buildContent(compressed, elapsed);
      await (0, import_utils.sendWarningLog)({ title, content });
      this.removeFromStorage(_sessionKey);
    } catch (error) {
      console.error("PayLog flush error:", error);
    } finally {
      this.sessionKey = null;
    }
  }
  /**
   * flush + 重置内部状态
   */
  destroy() {
    this.flush();
    this.sessionKey = null;
    this.context = {};
    this.logs = [];
    this.startTime = 0;
    this.flushed = false;
  }
  // ─── 私有方法 ───
  /**
   * 构建 sendWarningLog 所需的 content 数组
   */
  buildContent(compressed, elapsed) {
    const ctx = this.context;
    return [
      { key: "sessionKey", value: this.sessionKey || "" },
      { key: "发起时间", value: (0, import_dayjs.default)(this.startTime).format("YYYY-MM-DD HH:mm:ss") },
      { key: "交易号", value: String(ctx.transactionNumber || "未知") },
      { key: "订单ID", value: String(ctx.orderId || "未知") },
      { key: "设备ID", value: String(ctx.deviceId || "未知") },
      { key: "支付类型", value: String(ctx.paymentType || "未知") },
      { key: "模式", value: String(ctx.mode || "未知") },
      { key: "渠道", value: String(ctx.channel || "未知") },
      { key: "总耗时", value: `${elapsed}s` },
      // { key: '日志条数(原始/压缩)', value: `${this.logs.length}/${compressed.length}` },
      { key: "时间线", value: JSON.stringify(compressed) }
    ];
  }
  /**
   * 持久化当前会话到 localStorage
   */
  persistToStorage() {
    if (!this.sessionKey) return;
    try {
      const all = this.getAllSessions();
      all[this.sessionKey] = {
        sessionKey: this.sessionKey,
        context: this.context,
        logs: this.logs,
        startTime: this.startTime
      };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
    } catch (error) {
      console.error("PayLog persist error:", error);
    }
  }
  /**
   * 从 localStorage 移除指定 session
   */
  removeFromStorage(key) {
    try {
      const all = this.getAllSessions();
      delete all[key];
      if (Object.keys(all).length === 0) {
        localStorage.removeItem(STORAGE_KEY);
      } else {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
      }
    } catch (error) {
      console.error("PayLog removeFromStorage error:", error);
    }
  }
  /**
   * 获取 localStorage 中所有 session
   */
  getAllSessions() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return {};
      return JSON.parse(raw);
    } catch {
      return {};
    }
  }
  /**
   * 恢复上报 localStorage 中残留的旧日志（崩溃/异常退出场景）
   */
  recoverOrphanedLogs() {
    try {
      const all = this.getAllSessions();
      const keys = Object.keys(all);
      if (keys.length === 0) return;
      for (const key of keys) {
        const session = all[key];
        try {
          const elapsed = ((Date.now() - session.startTime) / 1e3).toFixed(1);
          const compressed = compressLogs(session.logs);
          const ctx = session.context;
          const title = `[PRE][EFTPOS] ${ctx.paymentType || "未知支付"}-${ctx.mode || "未知模式"}-${ctx.orderId || "未知订单ID"}`;
          const content = [
            { key: "sessionKey", value: session.sessionKey },
            { key: "发起时间", value: (0, import_dayjs.default)(session.startTime).format("YYYY-MM-DD HH:mm:ss") },
            { key: "交易号", value: String(ctx.transactionNumber || "未知") },
            { key: "订单ID", value: String(ctx.orderId || "未知") },
            { key: "设备ID", value: String(ctx.deviceId || "未知") },
            { key: "支付类型", value: String(ctx.paymentType || "未知") },
            { key: "模式", value: String(ctx.mode || "未知") },
            { key: "总耗时", value: `${elapsed}s` },
            { key: "日志条数(原始/压缩)", value: `${session.logs.length}/${compressed.length}` },
            { key: "时间线", value: JSON.stringify(compressed) }
          ];
          (0, import_utils.sendWarningLog)({ title, content });
          this.removeFromStorage(key);
        } catch (err) {
          console.error(`PayLog: 恢复上报失败 (${key}):`, err);
          this.removeFromStorage(key);
        }
      }
    } catch (error) {
      console.error("PayLog recoverOrphanedLogs error:", error);
    }
  }
};
var payLog = PayLog.getInstance();
var payLog_default = payLog;
function usePayLog(context) {
  const initialized = (0, import_react.useRef)(false);
  (0, import_react.useEffect)(() => {
    if (!initialized.current) {
      initialized.current = true;
      payLog.init(context);
    }
    return () => {
      payLog.log("流程结束，上报日志");
      payLog.destroy();
    };
  }, []);
  return {
    log: (title, data) => payLog.log(title, data),
    setContext: (partial) => payLog.setContext(partial)
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  usePayLog
});
