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/modules/Order/utils.ts
var utils_exports = {};
__export(utils_exports, {
  buildManualProductDiscountItem: () => import_manualProductDiscount.buildManualProductDiscountItem,
  buildSubmitPayload: () => buildSubmitPayload,
  composeLinePrice: () => composeLinePrice,
  createDefaultOrderRulesHooks: () => createDefaultOrderRulesHooks,
  createDefaultTempOrder: () => createDefaultTempOrder,
  createEmptySummary: () => import_utils2.createEmptySummary,
  createUuidV4: () => createUuidV4,
  ensureManualProductDiscountList: () => import_manualProductDiscount.ensureManualProductDiscountList,
  findManualProductDiscountItem: () => import_manualProductDiscount.findManualProductDiscountItem,
  formatDateTime: () => formatDateTime,
  formatV1Product: () => formatV1Product,
  generateDuration: () => generateDuration,
  getAllDiscountList: () => getAllDiscountList,
  isTempOrder: () => isTempOrder,
  mapPaymentItemToOrderPayment: () => mapPaymentItemToOrderPayment,
  mapPaymentItemsToOrderPayments: () => mapPaymentItemsToOrderPayments,
  mergeManualProductDiscountIntoList: () => import_manualProductDiscount.mergeManualProductDiscountIntoList,
  mergeRelationForms: () => mergeRelationForms,
  normalizeBookingIsAll: () => normalizeBookingIsAll,
  normalizeBookingSubType: () => normalizeBookingSubType,
  normalizeOrderProductDiscountList: () => normalizeOrderProductDiscountList,
  normalizeSubmitBooking: () => normalizeSubmitBooking,
  normalizeSubmitCollectPaxValue: () => normalizeSubmitCollectPaxValue,
  resolveManualDiscountMessage: () => import_manualProductDiscount.resolveManualDiscountMessage,
  resolveManualDiscountOriginTotal: () => import_manualProductDiscount.resolveManualDiscountOriginTotal,
  resolveManualDiscountReasonFromSources: () => import_manualProductDiscount.resolveManualDiscountReasonFromSources,
  resolveManualOverrideLineOriginalPrice: () => resolveManualOverrideLineOriginalPrice,
  resolveRulesManualDiscountFlag: () => resolveRulesManualDiscountFlag,
  resolveSafeProductNum: () => import_manualProductDiscount.resolveSafeProductNum,
  resolveSubmitCollectPax: () => resolveSubmitCollectPax,
  shouldBuildManualProductDiscount: () => import_manualProductDiscount.shouldBuildManualProductDiscount,
  stripManualProductDiscountItems: () => import_manualProductDiscount.stripManualProductDiscountItems,
  sumOptionUnitPrice: () => sumOptionUnitPrice,
  syncManualProductDiscountProductNum: () => import_manualProductDiscount.syncManualProductDiscountProductNum
});
module.exports = __toCommonJS(utils_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_decimal = __toESM(require("decimal.js"));
var import_utils = require("../../solution/ScanOrder/utils");
var import_utils2 = require("../../solution/ScanOrder/utils");
var import_manualProductDiscount = require("./utils/manualProductDiscount");
function composeLinePrice(params) {
  const { mainPrice, bundle, useOriginalBundle } = params;
  let total = new import_decimal.default(Number(mainPrice) || 0);
  if (Array.isArray(bundle)) {
    for (const item of bundle) {
      const rawPrice = useOriginalBundle ? (item == null ? void 0 : item.original_price) ?? (item == null ? void 0 : item.product_price) ?? (item == null ? void 0 : item.price) : (item == null ? void 0 : item.bundle_selling_price) ?? (item == null ? void 0 : item.price);
      const price = new import_decimal.default(Number(rawPrice) || 0);
      const rawNum = (item == null ? void 0 : item.num) ?? (item == null ? void 0 : item.quantity) ?? 1;
      const num = new import_decimal.default(Number(rawNum) || 0);
      total = total.plus(price.times(num));
    }
  }
  return total.toDecimalPlaces(2).toFixed(2);
}
function sumOptionUnitPrice(options) {
  let total = new import_decimal.default(0);
  if (!Array.isArray(options))
    return total;
  for (const opt of options) {
    const price = new import_decimal.default(Number(opt == null ? void 0 : opt.price) || 0);
    const num = new import_decimal.default(Number(opt == null ? void 0 : opt.num) || 0);
    total = total.plus(price.times(num));
  }
  return total;
}
function resolveRulesManualDiscountFlag(metadata) {
  if (!metadata)
    return void 0;
  if (metadata.is_manual_discount === true || metadata.is_manual_discount === 1) {
    return true;
  }
  const priceOverride = metadata.price_override;
  if (priceOverride !== void 0 && priceOverride !== null && priceOverride !== "") {
    return true;
  }
  return void 0;
}
function normalizeOrderProductDiscountAmount(amount) {
  if (amount === void 0 || amount === null)
    return void 0;
  return String(amount);
}
function normalizeOrderProductDiscountList(discountList) {
  if (!Array.isArray(discountList))
    return [];
  return discountList.filter((item) => !!item && typeof item === "object").map((item) => {
    const normalized = {
      discount_id: Number.isFinite(Number(item.discount_id)) ? Number(item.discount_id) : 0
    };
    if (item.order_discount_id === null) {
      normalized.order_discount_id = null;
    } else if (item.order_discount_id !== void 0) {
      const orderDiscountId = Number(item.order_discount_id);
      if (Number.isFinite(orderDiscountId)) {
        normalized.order_discount_id = orderDiscountId;
      }
    }
    if (item.type !== void 0)
      normalized.type = item.type;
    const amount = normalizeOrderProductDiscountAmount(item.amount);
    if (amount !== void 0)
      normalized.amount = amount;
    if (item.discount && typeof item.discount === "object") {
      normalized.discount = { ...item.discount };
    }
    if (item.metadata === null) {
      normalized.metadata = null;
    } else if (item.metadata && typeof item.metadata === "object") {
      normalized.metadata = { ...item.metadata };
    }
    return normalized;
  });
}
function resolveManualOverrideLineOriginalPrice(params, fallbackCompositeOriginal) {
  var _a, _b;
  const metadata = params.metadata || {};
  const priceOverride = metadata.price_override;
  if (priceOverride === void 0 || priceOverride === null || priceOverride === "") {
    return fallbackCompositeOriginal;
  }
  const refTotal = (_b = (_a = metadata.origin) == null ? void 0 : _a._extend) == null ? void 0 : _b.origin_total;
  if (refTotal !== void 0 && refTotal !== null && refTotal !== "") {
    const parsed = Number(refTotal);
    if (Number.isFinite(parsed)) {
      return new import_decimal.default(parsed).toDecimalPlaces(2).toFixed(2);
    }
  }
  const lineOriginal = params.lineOriginalPrice;
  if (lineOriginal !== void 0 && lineOriginal !== null && lineOriginal !== "") {
    const parsedLine = Number(lineOriginal);
    const parsedFallback = Number(fallbackCompositeOriginal);
    if (Number.isFinite(parsedLine) && Number.isFinite(parsedFallback) && parsedLine > parsedFallback) {
      return new import_decimal.default(parsedLine).toDecimalPlaces(2).toFixed(2);
    }
  }
  return fallbackCompositeOriginal;
}
function createDefaultOrderRulesHooks() {
  const toUnitPriceString = (totalLike, num) => {
    const effectiveNum = Number(num) > 0 ? Number(num) : 1;
    return new import_decimal.default(Number(totalLike) || 0).dividedBy(effectiveNum).toDecimalPlaces(2).toString();
  };
  return {
    getProduct: (product) => {
      var _a, _b, _c, _d, _e;
      const metadataAny = product.metadata || {};
      const optionSum = sumOptionUnitPrice(product.product_option_item);
      let sourcePrice;
      if (metadataAny.source_product_price !== void 0) {
        sourcePrice = String(metadataAny.source_product_price);
      } else if (metadataAny.main_product_selling_price !== void 0) {
        sourcePrice = new import_decimal.default(
          Number(metadataAny.main_product_selling_price) || 0
        ).minus(optionSum).toDecimalPlaces(2).toString();
      } else {
        sourcePrice = String(product.selling_price ?? 0);
      }
      let sourceOriginalPrice;
      if (metadataAny.source_product_price !== void 0) {
        sourceOriginalPrice = String(metadataAny.source_product_price);
      } else if (metadataAny.main_product_original_price !== void 0) {
        sourceOriginalPrice = new import_decimal.default(
          Number(metadataAny.main_product_original_price) || 0
        ).minus(optionSum).toDecimalPlaces(2).toString();
      } else {
        sourceOriginalPrice = sourcePrice;
      }
      return {
        id: product.product_id,
        // Rules 引擎用 _id 作为 processedProductsMap 键；必须与购物车行级 identity 一致，
        // 否则同 SKU 不同小料会在 calcDiscount 重组时互相覆盖。
        // 不透明 identity 契约下，normalizeOrderProduct / restoreTempOrderFromStorage 已保证唯一值存在；
        // 留 fingerprint 分支仅作 Rules 单测里直接传裸 product 时的兜底。
        _id: ((_a = product.metadata) == null ? void 0 : _a.unique_identification_number) ? `${product.product_id}_${product.product_variant_id}_${product.metadata.unique_identification_number}` : `${product.product_id}_${product.product_variant_id}_${(0, import_utils.buildProductLineFingerprint)(
          product.product_option_item,
          product.product_bundle
        )}`,
        // Rules 内部 getProductTotalPrice / getProductOriginTotalPrice 会各自再叠加 bundle + option，
        // 所以这里必须喂 source-level（不含 option、不含 bundle、不含折扣）单价，避免双加 option。
        price: sourcePrice,
        // total / origin_total 使用 composite × num，跟 Rules 内部产出的 total 对齐（含 option + bundle）。
        total: new import_decimal.default(product.selling_price || 0).times(product.num || 1).toNumber(),
        origin_total: new import_decimal.default(
          product.original_price || product.selling_price || 0
        ).times(product.num || 1).toNumber(),
        original_price: sourceOriginalPrice,
        quantity: product.num || 1,
        num: product.num || 1,
        discount_list: product.discount_list || [],
        bundle: product.product_bundle || [],
        booking_id: ((_b = product.metadata) == null ? void 0 : _b.booking_id) || null,
        isClient: false,
        // 勿写死 false：否则 Rules 不会走 total≠origin_total 的手动价推断，
        // 无券时会把 bundle 价还原成 original_price（手动改价套餐会从 20 回到 30）。
        isManualDiscount: resolveRulesManualDiscountFlag(metadataAny),
        holder_id: (_c = product.metadata) == null ? void 0 : _c.holder_id,
        startDate: ((_d = product.metadata) == null ? void 0 : _d.start_date) || ((_e = product.metadata) == null ? void 0 : _e.startDate)
      };
    },
    setProduct: (product, values) => {
      const nextNum = Number(values.quantity ?? product.num ?? 1) || 1;
      const metadataAny = product.metadata || {};
      const existedSource = metadataAny.source_product_price ?? product.selling_price ?? "0";
      const nextOptions = product.product_option_item;
      const optionSum = sumOptionUnitPrice(nextOptions);
      const nextSourceSellingPrice = values.main_product_selling_price !== void 0 ? String(values.main_product_selling_price) : values.price !== void 0 ? String(values.price) : values.total !== void 0 ? toUnitPriceString(values.total, nextNum) : String(existedSource);
      const nextSourceOriginalPrice = values.original_price !== void 0 ? String(values.original_price) : String(existedSource);
      const nextMainSellingPrice = new import_decimal.default(Number(nextSourceSellingPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
      const nextMainOriginalPrice = new import_decimal.default(Number(nextSourceOriginalPrice) || 0).plus(optionSum).toDecimalPlaces(2).toFixed(2);
      const nextBundle = values.bundle ?? product.product_bundle;
      const composedSellingPrice = composeLinePrice({
        mainPrice: nextMainSellingPrice,
        bundle: nextBundle
      });
      const composedOriginalPrice = composeLinePrice({
        mainPrice: nextMainOriginalPrice,
        bundle: nextBundle,
        useOriginalBundle: true
      });
      const finalOriginalPrice = resolveManualOverrideLineOriginalPrice(
        { num: nextNum, metadata: metadataAny, lineOriginalPrice: product.original_price },
        composedOriginalPrice
      );
      return {
        ...product,
        selling_price: composedSellingPrice,
        original_price: finalOriginalPrice,
        discount_list: values.discount_list ?? product.discount_list,
        num: values.quantity ?? product.num,
        product_bundle: nextBundle,
        metadata: {
          ...metadataAny,
          source_product_price: nextSourceOriginalPrice,
          main_product_selling_price: nextMainSellingPrice,
          main_product_original_price: nextMainOriginalPrice,
          price_schema_version: 2
        }
      };
    }
  };
}
var generateDuration = (cartItem) => {
  const startDate = (0, import_dayjs.default)(`${cartItem.start_date} ${cartItem.start_time}`);
  const endDate = (0, import_dayjs.default)(`${cartItem.end_date} ${cartItem.end_time}`);
  const duration = endDate.diff(startDate, "minutes");
  return { duration, durationType: "minutes" };
};
var mergeRelationForms = (relationForms) => {
  return Object.values(
    relationForms.reduce((acc, cur) => {
      const { form_id, form_record_ids } = cur;
      if (!acc[form_id]) {
        acc[form_id] = { form_id, form_record_ids: [] };
      }
      const ids = Array.isArray(form_record_ids) ? form_record_ids : [form_record_ids];
      const validIds = ids.filter((id) => id != null);
      acc[form_id].form_record_ids.push(...validIds);
      acc[form_id].form_record_ids = [...new Set(acc[form_id].form_record_ids)];
      return acc;
    }, {})
  ).filter((item) => item.form_record_ids.length > 0);
};
var getAllDiscountList = (cartItem) => {
  var _a, _b, _c, _d;
  let discountList = ((_b = (_a = cartItem == null ? void 0 : cartItem._origin) == null ? void 0 : _a.product) == null ? void 0 : _b.discount_list) || [];
  (((_d = (_c = cartItem == null ? void 0 : cartItem._origin) == null ? void 0 : _c.product) == null ? void 0 : _d.product_bundle) || []).forEach((item) => {
    discountList = [...discountList, ...(item == null ? void 0 : item.discount_list) || []];
    item.discount_list = void 0;
  });
  return discountList;
};
function createUuidV4() {
  const template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
  return template.replace(/[xy]/g, (char) => {
    const randomValue = Math.floor(Math.random() * 16);
    const value = char === "x" ? randomValue : randomValue & 3 | 8;
    return value.toString(16);
  });
}
function isTempOrder(data) {
  if (!data || typeof data !== "object")
    return false;
  if (!Array.isArray(data.products))
    return false;
  return true;
}
function formatDateTime(date) {
  const pad = (value) => value.toString().padStart(2, "0");
  const year = date.getFullYear();
  const month = pad(date.getMonth() + 1);
  const day = pad(date.getDate());
  const hours = pad(date.getHours());
  const minutes = pad(date.getMinutes());
  const seconds = pad(date.getSeconds());
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
function normalizeSubmitPlatform(platform) {
  const value = String(platform || "").trim();
  if (!value)
    return "H5";
  const lower = value.toLowerCase();
  if (lower === "pc")
    return "PC";
  if (lower === "h5")
    return "H5";
  return value;
}
function formatSubmitOptionItems(options) {
  if (!Array.isArray(options))
    return [];
  return options.map((d) => {
    const option = {
      num: d == null ? void 0 : d.num,
      option_group_item_id: d == null ? void 0 : d.option_group_item_id,
      option_group_id: d == null ? void 0 : d.option_group_id
    };
    const addPrice = (d == null ? void 0 : d.add_price) ?? (d == null ? void 0 : d.price);
    if (addPrice !== void 0)
      option.add_price = String(addPrice);
    return option;
  });
}
function toBundleNumber(value, fallback = 0) {
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
}
function toMoneyString(value) {
  const parsed = Number(value);
  if (Number.isFinite(parsed))
    return parsed.toFixed(2);
  if (value === null || value === void 0 || value === "")
    return "0.00";
  return String(value);
}
function formatSubmitBundleItems(bundle) {
  if (!Array.isArray(bundle))
    return [];
  return bundle.map((b) => {
    const rawBundle = b && typeof b === "object" ? b : {};
    const existedMetadata = rawBundle.metadata && typeof rawBundle.metadata === "object" ? rawBundle.metadata : {};
    const sellingPrice = toMoneyString(
      rawBundle.bundle_selling_price ?? rawBundle.price
    );
    const priceValue = rawBundle.price ?? rawBundle.custom_price ?? rawBundle.bundle_selling_price;
    const relationSurchargeIds = Array.isArray(rawBundle.relation_surcharge_ids) ? rawBundle.relation_surcharge_ids : Array.isArray(existedMetadata.relation_surcharge_ids) ? existedMetadata.relation_surcharge_ids : [];
    const surchargeFee = toMoneyString(
      rawBundle.surcharge_fee ?? existedMetadata.surcharge_fee
    );
    const productDiscountDifference = toBundleNumber(
      existedMetadata.product_discount_difference,
      0
    );
    const num = toBundleNumber(rawBundle.num ?? rawBundle.quantity, 1);
    return {
      is_charge_tax: rawBundle.is_charge_tax ?? 0,
      bundle_variant_id: rawBundle.bundle_variant_id ?? 0,
      num,
      quantity: toBundleNumber(rawBundle.quantity ?? rawBundle.num, num),
      extension_id: rawBundle.extension_id ?? 0,
      extension_type: rawBundle.extension_type ?? "normal",
      price: priceValue,
      price_type: rawBundle.price_type ?? rawBundle.custom_price_type ?? "",
      price_type_ext: rawBundle.price_type_ext ?? rawBundle.custom_price_type_ext ?? "",
      bundle_selling_price: sellingPrice,
      option: formatSubmitOptionItems(rawBundle.option),
      bundle_group_id: (rawBundle == null ? void 0 : rawBundle.bundle_group_id) ?? (rawBundle == null ? void 0 : rawBundle.group_id),
      bundle_id: (rawBundle == null ? void 0 : rawBundle.bundle_id) ?? (rawBundle == null ? void 0 : rawBundle.id),
      bundle_product_id: (rawBundle == null ? void 0 : rawBundle.bundle_product_id) ?? (rawBundle == null ? void 0 : rawBundle._bundle_product_id),
      metadata: {
        ...existedMetadata,
        surcharge_fee: surchargeFee,
        relation_surcharge_ids: relationSurchargeIds,
        product_discount_difference: productDiscountDifference
      }
    };
  });
}
function normalizeSubmitProduct(product) {
  var _a;
  const { unique_identification_number: _runtimeUid, ...submitProduct } = product;
  const {
    num,
    product_option_item: productOptionItem,
    surcharge_fee: _productSurchargeFee,
    discount_amount: _deprecatedDiscountAmount,
    discount_type: _deprecatedDiscountType,
    discountway: _deprecatedDiscountway,
    product_discount_reason: _deprecatedProductDiscountReason,
    discount_per: _deprecatedDiscountPer,
    ...productRest
  } = submitProduct;
  const rawMetadata = submitProduct.metadata || {};
  const bookingUid = rawMetadata.booking_uid;
  const cleanMetadata = {};
  if (rawMetadata.unique_identification_number) {
    cleanMetadata.unique_identification_number = rawMetadata.unique_identification_number;
  }
  const priceMetaKeys = [
    "main_product_original_price",
    "main_product_selling_price",
    "source_product_price",
    "main_product_attached_bundle_surcharge_fee",
    "main_product_attached_bundle_tax_fee",
    "surcharge_rounding_remainder",
    "tax_fee_rounding_remainder",
    "relation_surcharge_ids",
    "discountable_flag",
    "parent_unique_identification_number",
    "product_add_schedule_time"
  ];
  for (const key of priceMetaKeys) {
    if (rawMetadata[key] !== void 0) {
      cleanMetadata[key] = rawMetadata[key];
    }
  }
  cleanMetadata.product_discount_difference = rawMetadata.product_discount_difference ?? "";
  if (rawMetadata.price_breakdown) {
    cleanMetadata.price_breakdown = rawMetadata.price_breakdown;
  }
  if (rawMetadata.is_rule !== void 0) {
    cleanMetadata.is_rule = rawMetadata.is_rule;
  }
  const productSku = {
    ...submitProduct.product_sku && typeof submitProduct.product_sku === "object" ? submitProduct.product_sku : {},
    option: formatSubmitOptionItems(
      (productOptionItem == null ? void 0 : productOptionItem.length) ? productOptionItem : (_a = submitProduct.product_sku) == null ? void 0 : _a.option
    )
  };
  return {
    ...productRest,
    ...bookingUid ? { booking_uid: bookingUid } : {},
    product_quantity: toBundleNumber(num ?? submitProduct.product_quantity, 1),
    product_sku: productSku,
    discount_list: normalizeOrderProductDiscountList(submitProduct.discount_list),
    product_bundle: formatSubmitBundleItems(submitProduct.product_bundle),
    metadata: cleanMetadata,
    // 出站兼容：后端消费 payment_price 字段，这里从 selling_price 直接派生。
    // 新语义下 selling_price 是 composite（含 option/bundle），payment_price 同语义。
    payment_price: submitProduct.selling_price
  };
}
var SUBMIT_BOOKING_METADATA_WHITELIST = [
  "unique_identification_number",
  "collect_pax",
  "capacity",
  "holder_id",
  "resource_select_type"
];
function normalizeBookingIsAll(booking) {
  return booking.is_all === true || booking.is_all === 1 || booking.is_all === "1" || booking.is_all === "true" ? 1 : 0;
}
function normalizeBookingSubType(booking) {
  if (normalizeBookingIsAll(booking) === 1)
    return "days";
  if (booking.sub_type !== void 0 && booking.sub_type !== null && booking.sub_type !== "") {
    return String(booking.sub_type);
  }
  return "minutes";
}
function normalizeSubmitBooking(booking) {
  const rawMetadata = booking.metadata || {};
  const cleanMetadata = {};
  for (const key of SUBMIT_BOOKING_METADATA_WHITELIST) {
    if (rawMetadata[key] !== void 0) {
      cleanMetadata[key] = rawMetadata[key];
    }
  }
  if (cleanMetadata.holder_id === void 0)
    cleanMetadata.holder_id = null;
  const bookingRecord = booking;
  const startDate = bookingRecord.start_date;
  const shouldRestoreSelectDate = bookingRecord.select_date === void 0 || bookingRecord.select_date === null || bookingRecord.select_date === "";
  const selectDateFromStartDate = typeof startDate === "string" ? startDate.split(/\s+/)[0] : startDate;
  return {
    ...booking,
    ...shouldRestoreSelectDate && selectDateFromStartDate ? { select_date: selectDateFromStartDate } : {},
    is_all: normalizeBookingIsAll(bookingRecord),
    sub_type: normalizeBookingSubType(bookingRecord),
    metadata: cleanMetadata
  };
}
function normalizeSubmitCollectPaxValue(value) {
  const n = Number(value);
  return Number.isFinite(n) && n > 0 ? Math.floor(n) : 1;
}
function resolveSubmitCollectPax(tempOrder) {
  var _a;
  return normalizeSubmitCollectPaxValue((_a = tempOrder.metadata) == null ? void 0 : _a.collect_pax);
}
function createDefaultTempOrder(params) {
  return {
    order_id: null,
    external_sale_number: "",
    order_number: null,
    shop_order_number: null,
    shop_full_order_number: null,
    type: "",
    business_code: void 0,
    platform: "h5",
    sales_channel: "my_pisel",
    order_sales_channel: "online_store",
    status: "normal",
    payment_status: "payment_processing",
    shipping_status: "unfulfilled",
    customer_id: 0,
    customer_name: "",
    country_calling_code: "",
    phone: "",
    email: "",
    customer: null,
    is_price_include_tax: 1,
    tax_title: "",
    tax_country_code: "",
    currency_code: "",
    currency_symbol: "",
    currency_format: "symbol_first",
    is_deposit: 0,
    deposit_amount: "0.00",
    shop_discount: "0.00",
    surcharge_fee: "0.00",
    note: "",
    schedule_date: params.now,
    created_at: params.now,
    request_unique_idempotency_token: "",
    products: [],
    bookings: [],
    payments: [],
    surcharges: [],
    relation_forms: [],
    contacts: [],
    contacts_info: null,
    holder: null,
    metadata: {},
    _extend: {
      productsByUid: {}
    }
  };
}
function buildSubmitPayload(params) {
  var _a;
  const {
    tempOrder,
    cacheId,
    now = /* @__PURE__ */ new Date(),
    platform,
    businessCode,
    channel,
    type,
    enhance
  } = params;
  const scheduleDate = tempOrder.schedule_date || tempOrder.created_at || formatDateTime(now);
  const bookingUuid = createUuidV4();
  const {
    _extend,
    relation_id: _relationId,
    table_form_id: _tableFormId,
    resource_id: _resourceId,
    summary: _summary,
    lastOrderInfo: _lastOrderInfo,
    paid_amount: _paidAmount,
    shop_id: _shopId,
    shop_note: _shopNote,
    shop_service_type: _shopServiceType,
    start_time: _startTime,
    customer: _customer,
    discount_list: _discountList,
    tax_fee: _rootTaxFee,
    total_amount: _totalAmount,
    total_refund_amount: _totalRefundAmount,
    create_date: _createDate,
    holder_id: _holderId,
    ...tempOrderRest
  } = tempOrder;
  let submitType = type ?? tempOrder.type;
  if (!submitType) {
    if ((_a = tempOrder == null ? void 0 : tempOrder.bookings) == null ? void 0 : _a.length) {
      submitType = "appointment_booking";
    } else {
      submitType = "virtual";
    }
  }
  const payload = {
    ...tempOrderRest,
    customer_id: tempOrder.customer_id ?? 0,
    order_number: null,
    shop_order_number: null,
    shop_full_order_number: null,
    platform: normalizeSubmitPlatform(platform),
    request_unique_idempotency_token: tempOrder.request_unique_idempotency_token || `${tempOrder.external_sale_number}_${now.getTime()}`,
    type: submitType,
    business_code: businessCode ?? tempOrder.business_code,
    sales_channel: tempOrder.sales_channel || "my_pisel",
    order_sales_channel: channel ?? tempOrder.order_sales_channel ?? "online_store",
    status: tempOrder.status || "normal",
    payment_status: tempOrder.payment_status || "payment_processing",
    // shipping_status: tempOrder.shipping_status || 'unfulfilled',
    is_price_include_tax: tempOrder.is_price_include_tax ?? 1,
    currency_format: tempOrder.currency_format || "symbol_first",
    is_deposit: tempOrder.is_deposit ?? 0,
    deposit_amount: tempOrder.deposit_amount || "0.00",
    shop_discount: tempOrder.shop_discount || "0.00",
    surcharge_fee: tempOrder.surcharge_fee || "0.00",
    note: tempOrder.note || "",
    delivery_type: tempOrder.delivery_type || "nil",
    schedule_date: scheduleDate,
    // created_at: tempOrder.created_at || formatDateTime(now), 和后端协定这个字段先不提交到接口
    bookings: (tempOrder.bookings || []).filter(
      (booking) => Number(booking.parent_id) !== 0
    ).map((booking) => normalizeSubmitBooking(booking)),
    payments: tempOrder.payments || [],
    relation_forms: tempOrder.relation_forms || [],
    // contacts: tempOrder.contacts || [],
    contacts_info: tempOrder.contacts_info && !Array.isArray(tempOrder.contacts_info) ? tempOrder.contacts_info : null,
    // holder: tempOrder.holder || null,
    // summary,
    metadata: (() => {
      const {
        collect_pax: _collectPax,
        table_occupancy_duration: _tableOccupancyDuration,
        ...rest
      } = tempOrder.metadata || {};
      return { ...rest };
    })(),
    products: (tempOrder.products || []).map(
      (product) => normalizeSubmitProduct(product)
    )
  };
  return enhance ? enhance(payload, { tempOrder, bookingUuid, now }) : payload;
}
function mapPaymentItemToOrderPayment(paymentItem) {
  const item = paymentItem;
  const customPaymentId = item.custom_payment_id ?? item.id;
  const metadata = item.metadata && typeof item.metadata === "object" ? { ...item.metadata } : {};
  if (item.uuid && !metadata.unique_payment_number) {
    metadata.unique_payment_number = String(item.uuid);
  }
  const paymentMetadataKeys = [
    "rounding_rule",
    "shop_wallet_pass_id",
    "actual_paid_amount",
    "change_given_amount"
  ];
  for (const key of paymentMetadataKeys) {
    if (item[key] !== void 0 && metadata[key] === void 0) {
      metadata[key] = item[key];
    }
  }
  return {
    amount: String(item.amount ?? "0.00"),
    code: String(item.code || ""),
    custom_payment_id: Number(customPaymentId ?? 0),
    name: String(item.name || ""),
    type: String(item.type || ""),
    ...item.voucher_id !== void 0 ? { voucher_id: item.voucher_id } : {},
    ...item.origin_amount !== void 0 ? { origin_amount: String(item.origin_amount) } : {},
    ...item.service_fee !== void 0 ? { service_fee: String(item.service_fee) } : {},
    ...item.status !== void 0 ? { status: item.status } : {},
    ...item.payment_time !== void 0 ? { payment_time: item.payment_time } : {},
    ...item.wallet_pass_usage_unit !== void 0 ? { wallet_pass_usage_unit: item.wallet_pass_usage_unit } : {},
    ...item.wallet_pass_use_value !== void 0 ? { wallet_pass_use_value: item.wallet_pass_use_value } : {},
    metadata,
    ...item.rounding_amount !== void 0 ? { rounding_amount: String(item.rounding_amount) } : {},
    ...item.service_charge !== void 0 ? { service_charge: item.service_charge } : {},
    ...item.order_payment_type !== void 0 ? { order_payment_type: item.order_payment_type } : {},
    ...item.created_at !== void 0 ? { created_at: item.created_at } : {},
    ...item.updated_at !== void 0 ? { updated_at: item.updated_at } : {}
  };
}
function mapPaymentItemsToOrderPayments(paymentItems, options = {}) {
  if (!Array.isArray(paymentItems))
    return [];
  return paymentItems.filter((item) => options.includeVoided || item.status !== "voided").map((item) => mapPaymentItemToOrderPayment(item));
}
function formatV1Product(products) {
  return products.map((product) => {
    var _a;
    return {
      bundle: product.product_bundle,
      key: product.product_id,
      option: ((_a = product.product_sku) == null ? void 0 : _a.option) || [],
      product_id: product.product_id,
      product_variant_id: product.product_variant_id,
      num: product.product_quantity,
      note: String(product.note ?? ""),
      rowKey: product.product_id,
      session: null,
      unique: createUuidV4()
    };
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  buildManualProductDiscountItem,
  buildSubmitPayload,
  composeLinePrice,
  createDefaultOrderRulesHooks,
  createDefaultTempOrder,
  createEmptySummary,
  createUuidV4,
  ensureManualProductDiscountList,
  findManualProductDiscountItem,
  formatDateTime,
  formatV1Product,
  generateDuration,
  getAllDiscountList,
  isTempOrder,
  mapPaymentItemToOrderPayment,
  mapPaymentItemsToOrderPayments,
  mergeManualProductDiscountIntoList,
  mergeRelationForms,
  normalizeBookingIsAll,
  normalizeBookingSubType,
  normalizeOrderProductDiscountList,
  normalizeSubmitBooking,
  normalizeSubmitCollectPaxValue,
  resolveManualDiscountMessage,
  resolveManualDiscountOriginTotal,
  resolveManualDiscountReasonFromSources,
  resolveManualOverrideLineOriginalPrice,
  resolveRulesManualDiscountFlag,
  resolveSafeProductNum,
  resolveSubmitCollectPax,
  shouldBuildManualProductDiscount,
  stripManualProductDiscountItems,
  sumOptionUnitPrice,
  syncManualProductDiscountProductNum
});
