var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/solution/Checkout/utils/index.ts
var utils_exports = {};
__export(utils_exports, {
  calculateTotalAmount: () => calculateTotalAmount,
  createCheckoutError: () => createCheckoutError,
  debounce: () => debounce,
  deepClone: () => deepClone,
  extractAmountFromCartSummary: () => extractAmountFromCartSummary,
  formatAmount: () => formatAmount,
  formatDateTime: () => formatDateTime,
  generateLocalOrderId: () => generateLocalOrderId,
  generateOrderId: () => generateOrderId,
  getErrorMessage: () => getErrorMessage,
  isCashPayment: () => isCashPayment,
  isEmpty: () => isEmpty,
  isProduction: () => isProduction,
  isValidPaymentMethodCode: () => isValidPaymentMethodCode,
  isVirtualOrderId: () => isVirtualOrderId,
  logger: () => logger,
  retry: () => retry,
  safeJsonParse: () => safeJsonParse,
  shouldSyncOrderForPayment: () => shouldSyncOrderForPayment,
  throttle: () => throttle,
  validateAmount: () => validateAmount,
  validateCheckoutData: () => validateCheckoutData,
  validateLocalOrderData: () => validateLocalOrderData
});
module.exports = __toCommonJS(utils_exports);
var import_types = require("../../../modules/Payment/types");
function validateCheckoutData(params) {
  const errors = [];
  if (!params.cartItems || params.cartItems.length === 0) {
    errors.push("购物车不能为空");
  }
  if (params.cartItems) {
    params.cartItems.forEach((item, index) => {
      if (!item.id) {
        errors.push(`购物车商品 ${index + 1} 缺少商品ID`);
      }
      if (!item.price || parseFloat(String(item.price)) < 0) {
        errors.push(`购物车商品 ${index + 1} 价格无效`);
      }
      if (!item.num || item.num <= 0) {
        errors.push(`购物车商品 ${index + 1} 数量无效`);
      }
    });
  }
  if (params.platform && !["pc", "h5"].includes(params.platform)) {
    errors.push("平台类型无效，必须是 pc 或 h5");
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function createCheckoutError(type, message, details) {
  return {
    type,
    message,
    details,
    timestamp: Date.now()
  };
}
function formatAmount(amount) {
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(numAmount))
    return "0.00";
  return numAmount.toFixed(2);
}
function validateAmount(amount) {
  const numAmount = typeof amount === "string" ? parseFloat(amount) : amount;
  return !isNaN(numAmount) && numAmount >= 0;
}
function generateOrderId(prefix = "order") {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1e4).toString().padStart(4, "0");
  return `${prefix}_${timestamp}_${random}`;
}
function isValidPaymentMethodCode(code) {
  return typeof code === "string" && code.length > 0 && /^[a-zA-Z0-9_-]+$/.test(code);
}
function safeJsonParse(jsonString, defaultValue) {
  try {
    return JSON.parse(jsonString);
  } catch {
    return defaultValue;
  }
}
function deepClone(obj) {
  if (obj === null || typeof obj !== "object") {
    return obj;
  }
  if (obj instanceof Date) {
    return new Date(obj.getTime());
  }
  if (obj instanceof Array) {
    return obj.map((item) => deepClone(item));
  }
  if (typeof obj === "object") {
    const clonedObj = {};
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  return obj;
}
function debounce(func, wait) {
  let timeout = null;
  return (...args) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(() => {
      func.apply(null, args);
    }, wait);
  };
}
function throttle(func, wait) {
  let lastTime = 0;
  return (...args) => {
    const now = Date.now();
    if (now - lastTime >= wait) {
      lastTime = now;
      func.apply(null, args);
    }
  };
}
async function retry(fn, maxAttempts = 3, delay = 1e3) {
  let lastError;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
      if (attempt === maxAttempts) {
        throw lastError;
      }
      await new Promise((resolve) => setTimeout(resolve, delay * attempt));
    }
  }
  throw lastError;
}
function isEmpty(obj) {
  if (obj == null)
    return true;
  if (Array.isArray(obj) || typeof obj === "string")
    return obj.length === 0;
  if (typeof obj === "object")
    return Object.keys(obj).length === 0;
  return false;
}
function getErrorMessage(error) {
  if (error instanceof Error) {
    return error.message;
  }
  if (typeof error === "string") {
    return error;
  }
  if (error && typeof error === "object" && "message" in error) {
    return String(error.message);
  }
  return "未知错误";
}
function isProduction() {
  return process.env.NODE_ENV === "production";
}
var logger = {
  info: (message, ...args) => {
    console.log(`[Checkout] ${message}`, ...args);
  },
  warn: (message, ...args) => {
    console.warn(`[Checkout] ${message}`, ...args);
  },
  error: (message, ...args) => {
    console.error(`[Checkout] ${message}`, ...args);
  },
  debug: (message, ...args) => {
    if (!isProduction()) {
      console.debug(`[Checkout] ${message}`, ...args);
    }
  }
};
function validateLocalOrderData(orderData) {
  var _a;
  const errors = [];
  if (!orderData.type) {
    errors.push("订单类型不能为空");
  }
  if (!orderData.platform) {
    errors.push("平台信息不能为空");
  }
  if ((!orderData.bookings || orderData.bookings.length === 0) && !((_a = orderData == null ? void 0 : orderData.relation_products) == null ? void 0 : _a.length)) {
    errors.push("预订信息不能为空");
  }
  if (orderData.bookings) {
    orderData.bookings.forEach((booking, index) => {
      if (!booking.product || !booking.product.product_id) {
        errors.push(`预订项 ${index + 1} 缺少商品信息`);
      }
      if (!booking.start_date) {
        errors.push(`预订项 ${index + 1} 缺少开始日期`);
      }
      if (!booking.start_time) {
        errors.push(`预订项 ${index + 1} 缺少开始时间`);
      }
    });
  }
  return {
    valid: errors.length === 0,
    errors
  };
}
function generateLocalOrderId() {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 1e4).toString().padStart(4, "0");
  return `local_order_${timestamp}_${random}`;
}
function formatDateTime(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
function extractAmountFromCartSummary(cartSummary) {
  const result = {
    totalAmount: "0.00",
    subTotal: "0.00",
    taxAmount: "0.00",
    discountAmount: "0.00",
    shopDiscountAmount: "0.00",
    roundingAmount: "0.00"
  };
  cartSummary.forEach((item) => {
    const value = Number(item.value).toFixed(2);
    switch (item.key) {
      case "expect_amount":
        result.totalAmount = value;
        break;
      case "sub_total":
        result.subTotal = value;
        break;
      case "tax":
        result.taxAmount = value;
        if (item.tax) {
          result.taxDetails = item.tax;
        }
        break;
      case "discount":
        result.discountAmount = value;
        break;
      case "shop_discount":
        result.shopDiscountAmount = value;
        break;
      case "custom_roundingAmount":
        result.roundingAmount = value;
        break;
      default:
        if (item.key.includes("deposit")) {
          result.depositAmount = value;
        }
        break;
    }
  });
  console.log("[Checkout] 从购物车小计提取金额信息:", {
    totalAmount: result.totalAmount,
    subTotal: result.subTotal,
    taxAmount: result.taxAmount,
    discountAmount: result.discountAmount,
    shopDiscountAmount: result.shopDiscountAmount,
    roundingAmount: result.roundingAmount
  });
  return result;
}
function calculateTotalAmount(cartItems) {
  const total = cartItems.reduce((sum, item) => {
    const price = parseFloat(String(item.price) || "0");
    const quantity = item.quantity || 1;
    return sum + price * quantity;
  }, 0);
  return total.toFixed(2);
}
function isVirtualOrderId(orderId) {
  return orderId.startsWith("local_order_");
}
function shouldSyncOrderForPayment(paymentCode, paymentType) {
  const codeUpper = (paymentCode == null ? void 0 : paymentCode.toUpperCase()) || "";
  const typeUpper = (paymentType == null ? void 0 : paymentType.toUpperCase()) || "";
  const cashIdentifiers = ["CASHMANUAL", "CASH", "MANUAL"];
  if (cashIdentifiers.some(
    (id) => codeUpper.includes(id) || typeUpper.includes(id)
  )) {
    return false;
  }
  if (paymentCode === import_types.PaymentMethodType.Cash || paymentType === import_types.PaymentMethodType.Cash) {
    return false;
  }
  if (codeUpper.includes("CUSTOM") || typeUpper.includes("CUSTOM")) {
    return false;
  }
  return true;
}
function isCashPayment(paymentItem) {
  var _a, _b, _c;
  const codeUpper = ((_a = paymentItem.code) == null ? void 0 : _a.toUpperCase()) || "";
  const typeUpper = ((_b = paymentItem.type) == null ? void 0 : _b.toUpperCase()) || "";
  const isNameCash = (_c = paymentItem.name) == null ? void 0 : _c.toLowerCase().includes("cash");
  const cashIdentifiers = ["CASH", "CASHMANUAL", "MANUAL"];
  return cashIdentifiers.some(
    (identifier) => codeUpper.includes(identifier) || typeUpper.includes(identifier)
  ) || isNameCash;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  calculateTotalAmount,
  createCheckoutError,
  debounce,
  deepClone,
  extractAmountFromCartSummary,
  formatAmount,
  formatDateTime,
  generateLocalOrderId,
  generateOrderId,
  getErrorMessage,
  isCashPayment,
  isEmpty,
  isProduction,
  isValidPaymentMethodCode,
  isVirtualOrderId,
  logger,
  retry,
  safeJsonParse,
  shouldSyncOrderForPayment,
  throttle,
  validateAmount,
  validateCheckoutData,
  validateLocalOrderData
});
