function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import dayjs from 'dayjs';
import { sendWarningLog } from '@pisell/utils';

/**
 * 支付日志
 * 1. 支付日志实行单例模式，以交易记录的number为key
 * 2. 需要有init方法，用于初始化一次支付流程的日志，在初始化过程中需要首先判断localstorage中是否存在交易记录，如果存在需要将之前的交易记录上传飞书并从localstorage中删除，
 * 然后创建一个新的日志对象，用于记录本次支付流程的日志
 * 3. 需要有addLog方法，用于添加日志，日志内容需要包括支付状态，支付时间，支付金额，支付方式，支付结果等信息，需要记录到localstorage中
 * 4. 需要有sendLogs方法，用于发送日志，日志内容需要包括支付状态，支付时间，支付金额，支付方式，支付结果等信息，需要上传飞书
 * 5. 需要有clearLogs方法，用于清除日志，清除后需要将localstorage中记录的日志删除
 */

// 本地存储的固定key
var PAYMENT_LOGS_KEY = 'pisell2_eftpos_payment_logs';

// 日志条目接口

// 日志记录接口
var PaymentLogInstance = /*#__PURE__*/function () {
  function PaymentLogInstance() {
    _classCallCheck(this, PaymentLogInstance);
    /** 当前交易记录号 */
    _defineProperty(this, "currentNumber", null);
    /** 当前日志记录 */
    _defineProperty(this, "currentRecord", null);
  }

  /**
   * 获取单例实例
   */
  _createClass(PaymentLogInstance, [{
    key: "init",
    value:
    /**
     * 初始化支付日志
     * @param number 交易记录号
     * @param options 初始化选项
     */
    function init(number, options) {
      try {
        // 1. 检查是否有旧的日志记录需要上传
        this.checkAndUploadOldLogs();

        // 2. 创建新的日志记录
        this.currentNumber = number;
        this.currentRecord = {
          number: number,
          orderId: options === null || options === void 0 ? void 0 : options.orderId,
          deviceId: options === null || options === void 0 ? void 0 : options.deviceId,
          paymentCode: options === null || options === void 0 ? void 0 : options.paymentCode,
          createdAt: dayjs().format('YYYY-MM-DD HH:mm:ss.SSS'),
          logs: []
        };

        // 3. 添加初始化日志
        this.addLog({
          title: 'EFTPOS日志初始化',
          content: _objectSpread({
            number: number
          }, options || {})
        });
        console.log("\uD83D\uDCDD \u652F\u4ED8\u65E5\u5FD7\u521D\u59CB\u5316\u6210\u529F\uFF0C\u4EA4\u6613\u53F7: ".concat(number));
      } catch (error) {
        console.error('❌ 支付日志初始化失败:', error);
      }
    }

    /**
     * 添加日志条目
     * @param title 日志标题
     * @param content 日志内容
     */
  }, {
    key: "addLog",
    value: function addLog(params) {
      try {
        if (!this.currentRecord || !this.currentNumber) {
          console.warn('⚠️ 日志未初始化，无法添加日志');
          return;
        }
        var logEntry = {
          title: params.title,
          time: dayjs().format('YYYY-MM-DD HH:mm:ss.SSS')
        };
        // 如果content存在，则添加到日志内容中，节约空间
        if (params !== null && params !== void 0 && params.content) {
          logEntry.content = params.content;
        }

        // 添加到当前记录
        this.currentRecord.logs.push(logEntry);

        // 保存到 localStorage
        this.saveToLocalStorage();
        console.log("\uD83D\uDCDD \u6DFB\u52A0\u652F\u4ED8\u65E5\u5FD7: ".concat(params.title), logEntry);
      } catch (error) {
        console.error('❌ 添加日志失败:', error);
      }
    }

    /**
     * 构建日志内容
     * @param record 日志记录
     * @returns 格式化的日志内容数组
     */
  }, {
    key: "buildLogContent",
    value: function buildLogContent(record) {
      return [{
        key: '交易记录号',
        value: record.number
      }, {
        key: '订单ID',
        value: (record === null || record === void 0 ? void 0 : record.orderId) || '未知'
      }, {
        key: '设备ID',
        value: (record === null || record === void 0 ? void 0 : record.deviceId) || '未知'
      }, {
        key: '支付类型',
        value: (record === null || record === void 0 ? void 0 : record.paymentCode) || '未知'
      }, {
        key: '创建时间',
        value: record.createdAt
      }, {
        key: '详细日志',
        value: JSON.stringify(record.logs || [])
      }];
    }

    /**
     * 发送单条日志记录到飞书
     * @param record 日志记录
     * @param isRestore 是否是恢复上传
     */
  }, {
    key: "sendLogRecord",
    value: function sendLogRecord(record) {
      var isRestore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
      var prefix = isRestore ? '-[恢复上传]' : '';
      var title = "\u652F\u4ED8\u65E5\u5FD7-".concat(record.paymentCode || 'Unknown', "-").concat(record.orderId || 'Unknown').concat(prefix);
      var content = this.buildLogContent(record);
      sendWarningLog({
        title: title,
        content: content
      });
      console.log("\u2705 \u65E5\u5FD7\u5DF2\u53D1\u9001\u5230\u98DE\u4E66: ".concat(title));
    }

    /**
     * 发送日志到飞书
     * @param title 日志标题（可选，仅在需要自定义标题时使用）
     */
  }, {
    key: "sendLogs",
    value: function sendLogs(title) {
      try {
        if (!this.currentRecord) {
          console.warn('⚠️ 没有日志记录需要发送');
          return;
        }
        if (title) {
          // 如果提供了自定义标题，使用自定义标题
          var content = this.buildLogContent(this.currentRecord);
          sendWarningLog({
            title: title,
            content: content
          });
          console.log("\u2705 \u65E5\u5FD7\u5DF2\u53D1\u9001\u5230\u98DE\u4E66: ".concat(title));
        } else {
          // 否则使用默认格式
          this.sendLogRecord(this.currentRecord, false);
        }
      } catch (error) {
        console.error('❌ 发送日志到飞书失败:', error);
      }
    }

    /**
     * 清除当前日志
     * @param shouldSend 清除前是否发送到飞书，默认为 true
     */
  }, {
    key: "clearLogs",
    value: function clearLogs() {
      var shouldSend = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      try {
        if (!this.currentNumber) {
          console.warn('⚠️ 没有活动的日志记录需要清除');
          return;
        }

        // 如果需要，先发送到飞书
        if (shouldSend && this.currentRecord) {
          this.sendLogs();
        }

        // 从 localStorage 中删除
        this.removeFromLocalStorage(this.currentNumber);

        // 重置当前状态
        this.currentNumber = null;
        this.currentRecord = null;
        console.log('🧹 日志已清除');
      } catch (error) {
        console.error('❌ 清除日志失败:', error);
      }
    }

    /**
     * 检查并上传旧日志
     */
  }, {
    key: "checkAndUploadOldLogs",
    value: function checkAndUploadOldLogs() {
      try {
        var oldLogs = this.getOldLogsFromLocalStorage();
        if (oldLogs.length === 0) {
          return;
        }
        console.log("\uD83D\uDCE4 \u53D1\u73B0 ".concat(oldLogs.length, " \u6761\u65E7\u65E5\u5FD7\u8BB0\u5F55\uFF0C\u51C6\u5907\u4E0A\u4F20..."));

        // 逐个上传并删除
        var _iterator = _createForOfIteratorHelper(oldLogs),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var log = _step.value;
            try {
              // 使用统一的发送方法
              this.sendLogRecord(log, true);

              // 上传后删除
              this.removeFromLocalStorage(log.number);
              console.log("\u2705 \u65E7\u65E5\u5FD7\u5DF2\u4E0A\u4F20\u5E76\u5220\u9664: ".concat(log.number));
            } catch (error) {
              console.error("\u274C \u4E0A\u4F20\u65E7\u65E5\u5FD7\u5931\u8D25 (".concat(log.number, "):"), error);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      } catch (error) {
        console.error('❌ 检查旧日志失败:', error);
      }
    }

    /**
     * 获取所有支付日志对象
     */
  }, {
    key: "getAllLogsObject",
    value: function getAllLogsObject() {
      try {
        var value = localStorage.getItem(PAYMENT_LOGS_KEY);
        if (!value) {
          return {};
        }
        return JSON.parse(value);
      } catch (error) {
        console.error('❌ 读取 localStorage 失败:', error);
        return {};
      }
    }

    /**
     * 保存所有支付日志对象
     */
  }, {
    key: "saveAllLogsObject",
    value: function saveAllLogsObject(logsObject) {
      try {
        localStorage.setItem(PAYMENT_LOGS_KEY, JSON.stringify(logsObject));
      } catch (error) {
        console.error('❌ 保存到 localStorage 失败:', error);
      }
    }

    /**
     * 保存到 localStorage
     */
  }, {
    key: "saveToLocalStorage",
    value: function saveToLocalStorage() {
      try {
        if (!this.currentRecord || !this.currentNumber) {
          return;
        }
        var allLogs = this.getAllLogsObject();
        allLogs[this.currentNumber] = this.currentRecord;
        this.saveAllLogsObject(allLogs);
      } catch (error) {
        console.error('❌ 保存到 localStorage 失败:', error);
      }
    }

    /**
     * 从 localStorage 中删除
     */
  }, {
    key: "removeFromLocalStorage",
    value: function removeFromLocalStorage(number) {
      try {
        var allLogs = this.getAllLogsObject();
        delete allLogs[number];
        this.saveAllLogsObject(allLogs);
      } catch (error) {
        console.error('❌ 从 localStorage 删除失败:', error);
      }
    }

    /**
     * 获取所有旧日志
     */
  }, {
    key: "getOldLogsFromLocalStorage",
    value: function getOldLogsFromLocalStorage() {
      try {
        var allLogs = this.getAllLogsObject();
        return Object.values(allLogs);
      } catch (error) {
        console.error('❌ 获取旧日志失败:', error);
        return [];
      }
    }

    /**
     * 获取当前日志记录（用于调试）
     */
  }, {
    key: "getCurrentRecord",
    value: function getCurrentRecord() {
      return this.currentRecord;
    }

    /**
     * 获取当前交易号（用于调试）
     */
  }, {
    key: "getCurrentNumber",
    value: function getCurrentNumber() {
      return this.currentNumber;
    }
  }], [{
    key: "getInstance",
    value: function getInstance() {
      if (!PaymentLogInstance.instance) {
        PaymentLogInstance.instance = new PaymentLogInstance();
      }
      return PaymentLogInstance.instance;
    }
  }]);
  return PaymentLogInstance;
}();
_defineProperty(PaymentLogInstance, "instance", void 0);
var paymentLog = PaymentLogInstance.getInstance();
export default paymentLog;