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/aggregatePayment/utils/logs.ts
var logs_exports = {};
__export(logs_exports, {
  default: () => logs_default
});
module.exports = __toCommonJS(logs_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var PAYMENT_LOGS_KEY = "pisell2_eftpos_payment_logs";
var PaymentLogInstance = class _PaymentLogInstance {
  static instance;
  /** 当前交易记录号 */
  currentNumber = null;
  /** 当前日志记录 */
  currentRecord = null;
  constructor() {
  }
  /**
   * 获取单例实例
   */
  static getInstance() {
    if (!_PaymentLogInstance.instance) {
      _PaymentLogInstance.instance = new _PaymentLogInstance();
    }
    return _PaymentLogInstance.instance;
  }
  /**
   * 初始化支付日志
   * @param number 交易记录号
   * @param options 初始化选项
   */
  init(number, options) {
    try {
      this.checkAndUploadOldLogs();
      this.currentNumber = number;
      this.currentRecord = {
        number,
        orderId: options == null ? void 0 : options.orderId,
        deviceId: options == null ? void 0 : options.deviceId,
        paymentCode: options == null ? void 0 : options.paymentCode,
        createdAt: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss.SSS"),
        logs: []
      };
      this.addLog({
        title: "EFTPOS日志初始化",
        content: { number, ...options || {} }
      });
      console.log(`📝 支付日志初始化成功，交易号: ${number}`);
    } catch (error) {
      console.error("❌ 支付日志初始化失败:", error);
    }
  }
  /**
   * 添加日志条目
   * @param title 日志标题
   * @param content 日志内容
   */
  addLog(params) {
    try {
      if (!this.currentRecord || !this.currentNumber) {
        console.warn("⚠️ 日志未初始化，无法添加日志");
        return;
      }
      const logEntry = {
        title: params.title,
        time: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss.SSS")
      };
      if (params == null ? void 0 : params.content) {
        logEntry.content = params.content;
      }
      this.currentRecord.logs.push(logEntry);
      this.saveToLocalStorage();
      console.log(`📝 添加支付日志: ${params.title}`, logEntry);
    } catch (error) {
      console.error("❌ 添加日志失败:", error);
    }
  }
  /**
   * 构建日志内容
   * @param record 日志记录
   * @returns 格式化的日志内容数组
   */
  buildLogContent(record) {
    return [
      {
        key: "交易记录号",
        value: record.number
      },
      {
        key: "订单ID",
        value: (record == null ? void 0 : record.orderId) || "未知"
      },
      {
        key: "设备ID",
        value: (record == null ? void 0 : record.deviceId) || "未知"
      },
      {
        key: "支付类型",
        value: (record == null ? void 0 : record.paymentCode) || "未知"
      },
      {
        key: "创建时间",
        value: record.createdAt
      },
      {
        key: "详细日志",
        value: JSON.stringify(record.logs || [])
      }
    ];
  }
  /**
   * 发送单条日志记录到飞书
   * @param record 日志记录
   * @param isRestore 是否是恢复上传
   */
  sendLogRecord(record, isRestore = false) {
    const prefix = isRestore ? "-[恢复上传]" : "";
    const title = `支付日志-${record.paymentCode || "Unknown"}-${record.orderId || "Unknown"}${prefix}`;
    const content = this.buildLogContent(record);
    (0, import_utils.sendWarningLog)({ title, content });
    console.log(`✅ 日志已发送到飞书: ${title}`);
  }
  /**
   * 发送日志到飞书
   * @param title 日志标题（可选，仅在需要自定义标题时使用）
   */
  sendLogs(title) {
    try {
      if (!this.currentRecord) {
        console.warn("⚠️ 没有日志记录需要发送");
        return;
      }
      if (title) {
        const content = this.buildLogContent(this.currentRecord);
        (0, import_utils.sendWarningLog)({ title, content });
        console.log(`✅ 日志已发送到飞书: ${title}`);
      } else {
        this.sendLogRecord(this.currentRecord, false);
      }
    } catch (error) {
      console.error("❌ 发送日志到飞书失败:", error);
    }
  }
  /**
   * 清除当前日志
   * @param shouldSend 清除前是否发送到飞书，默认为 true
   */
  clearLogs(shouldSend = true) {
    try {
      if (!this.currentNumber) {
        console.warn("⚠️ 没有活动的日志记录需要清除");
        return;
      }
      if (shouldSend && this.currentRecord) {
        this.sendLogs();
      }
      this.removeFromLocalStorage(this.currentNumber);
      this.currentNumber = null;
      this.currentRecord = null;
      console.log("🧹 日志已清除");
    } catch (error) {
      console.error("❌ 清除日志失败:", error);
    }
  }
  /**
   * 检查并上传旧日志
   */
  checkAndUploadOldLogs() {
    try {
      const oldLogs = this.getOldLogsFromLocalStorage();
      if (oldLogs.length === 0) {
        return;
      }
      console.log(`📤 发现 ${oldLogs.length} 条旧日志记录，准备上传...`);
      for (const log of oldLogs) {
        try {
          this.sendLogRecord(log, true);
          this.removeFromLocalStorage(log.number);
          console.log(`✅ 旧日志已上传并删除: ${log.number}`);
        } catch (error) {
          console.error(`❌ 上传旧日志失败 (${log.number}):`, error);
        }
      }
    } catch (error) {
      console.error("❌ 检查旧日志失败:", error);
    }
  }
  /**
   * 获取所有支付日志对象
   */
  getAllLogsObject() {
    try {
      const value = localStorage.getItem(PAYMENT_LOGS_KEY);
      if (!value) {
        return {};
      }
      return JSON.parse(value);
    } catch (error) {
      console.error("❌ 读取 localStorage 失败:", error);
      return {};
    }
  }
  /**
   * 保存所有支付日志对象
   */
  saveAllLogsObject(logsObject) {
    try {
      localStorage.setItem(PAYMENT_LOGS_KEY, JSON.stringify(logsObject));
    } catch (error) {
      console.error("❌ 保存到 localStorage 失败:", error);
    }
  }
  /**
   * 保存到 localStorage
   */
  saveToLocalStorage() {
    try {
      if (!this.currentRecord || !this.currentNumber) {
        return;
      }
      const allLogs = this.getAllLogsObject();
      allLogs[this.currentNumber] = this.currentRecord;
      this.saveAllLogsObject(allLogs);
    } catch (error) {
      console.error("❌ 保存到 localStorage 失败:", error);
    }
  }
  /**
   * 从 localStorage 中删除
   */
  removeFromLocalStorage(number) {
    try {
      const allLogs = this.getAllLogsObject();
      delete allLogs[number];
      this.saveAllLogsObject(allLogs);
    } catch (error) {
      console.error("❌ 从 localStorage 删除失败:", error);
    }
  }
  /**
   * 获取所有旧日志
   */
  getOldLogsFromLocalStorage() {
    try {
      const allLogs = this.getAllLogsObject();
      return Object.values(allLogs);
    } catch (error) {
      console.error("❌ 获取旧日志失败:", error);
      return [];
    }
  }
  /**
   * 获取当前日志记录（用于调试）
   */
  getCurrentRecord() {
    return this.currentRecord;
  }
  /**
   * 获取当前交易号（用于调试）
   */
  getCurrentNumber() {
    return this.currentNumber;
  }
};
var paymentLog = PaymentLogInstance.getInstance();
var logs_default = paymentLog;
