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/ticketBooking/utils/index.ts
var utils_exports = {};
__export(utils_exports, {
  addService: () => addService,
  addServiceScroll: () => addServiceScroll,
  clearAllCache: () => import_productCache.clearAllCache,
  clearAllCacheByOsKey: () => import_productCache.clearAllCacheByOsKey,
  clearAllProductCache: () => import_productCache.clearAllProductCache,
  clearBoardConfigCache: () => import_productCache.clearBoardConfigCache,
  clearCache: () => import_productCache.clearCache,
  clearProductCache: () => import_productCache.clearProductCache,
  createSimpleCacheItem: () => createSimpleCacheItem,
  formatBookingList: () => formatBookingList,
  formatDateToStr: () => formatDateToStr,
  formatHolder: () => formatHolder,
  formatOptions: () => formatOptions,
  formatScanCustomer: () => formatScanCustomer,
  formatScanGlobal: () => formatScanGlobal,
  genHolderKey: () => genHolderKey,
  genServiceKey: () => genServiceKey,
  getBoardConfigCache: () => import_productCache.getBoardConfigCache,
  getBookingTicketKey: () => getBookingTicketKey,
  getCache: () => import_productCache.getCache,
  getCartProductOverlay: () => getCartProductOverlay,
  getDefaultStartParam: () => getDefaultStartParam,
  getDisabledEdit: () => getDisabledEdit,
  getEffectiveMenuListIds: () => import_menuListIds.getEffectiveMenuListIds,
  getIsOverlayProduct: () => getIsOverlayProduct,
  getIsParallelResourcesBooking: () => getIsParallelResourcesBooking,
  getIsShowNumber: () => getIsShowNumber,
  getNextTimeSlice: () => getNextTimeSlice,
  getProductCache: () => import_productCache.getProductCache,
  getShopDiscountKey: () => getShopDiscountKey,
  isSameProduct: () => isSameProduct,
  normalizeMenuListIds: () => import_menuListIds.normalizeMenuListIds,
  restoreProductOtherData: () => restoreProductOtherData,
  rulesHooks: () => rulesHooks,
  setBoardConfigCache: () => import_productCache.setBoardConfigCache,
  setCache: () => import_productCache.setCache,
  setProductCache: () => import_productCache.setProductCache
});
module.exports = __toCommonJS(utils_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("../../booking/info/service2/utils");
var import_utils2 = require("@pisell/utils");
var import_utils3 = require("../../booking/info2/service/addService/utils");
var import_productCache = require("./productCache");
var import_menuListIds = require("./menuListIds");
var formatDateToStr = (date) => {
  const format = (val) => {
    return (0, import_dayjs.default)(val).format("YYYY-MM-DD HH:mm:ss");
  };
  if (Array.isArray(date)) {
    return date.map(format);
  }
  return format(date);
};
var getDefaultStartParam = () => {
  return formatDateToStr([(0, import_dayjs.default)().startOf("day"), (0, import_dayjs.default)().endOf("day")]);
};
var formatBookingList = (bookingList) => {
  return bookingList.map((item) => {
    var _a, _b, _c, _d, _e, _f;
    return {
      ...item,
      startDateTime: `${item.start_date} ${item.start_time}`,
      endDateTime: `${item.end_date} ${item.end_time}`,
      total_amount: (_a = item == null ? void 0 : item.order) == null ? void 0 : _a.total_amount,
      customer: ((_d = (_c = (_b = item == null ? void 0 : item.order) == null ? void 0 : _b.customer) == null ? void 0 : _c.display_name) == null ? void 0 : _d.trim()) || (((_f = (_e = item == null ? void 0 : item.order) == null ? void 0 : _e.customer) == null ? void 0 : _f.nickname) || "").trim()
      // durationStr: this.formatDurationStr(item),
      // durationNum: this.calcDuration(item),
    };
  });
};
var getNextTimeSlice = (sliceMinutes) => {
  const currentTime = (0, import_dayjs.default)();
  const nextSlice = Math.ceil(currentTime.minute() / sliceMinutes) * sliceMinutes;
  const nextTime = currentTime.minute(nextSlice);
  return nextTime;
};
var getDisabledEdit = ({ shop_discount, bookings, payment_status }) => {
  var _a;
  if ((_a = bookings == null ? void 0 : bookings.list) == null ? void 0 : _a.some((d) => !d.detail)) {
    return true;
  }
  let list = ["unfulfilled", "paid", "unpaid", "payment_processing"];
  const ps = payment_status === "partially_paid" ? "unpaid" : payment_status;
  if ((bookings == null ? void 0 : bookings.appointment_status) === "cancelled" || !list.includes(ps)) {
    return true;
  }
  return false;
};
var formatOptions = (detail) => {
  var _a;
  return (((_a = detail == null ? void 0 : detail.product_sku) == null ? void 0 : _a.option) || []).map((item) => {
    var _a2;
    return {
      ...item,
      name: ((_a2 = item.name) == null ? void 0 : _a2["auto"]) || item.name,
      price: item.price || item.add_price
    };
  });
};
var formatHolder = (detail) => {
  var _a, _b;
  return (_b = (_a = detail == null ? void 0 : detail.holder) == null ? void 0 : _a.form_record) == null ? void 0 : _b[0];
};
var restoreProductOtherData = (data) => {
  let { detail, ...resetD } = data;
  if (!detail && !data.product_id) {
    return;
  }
  if (!detail && data.product_id) {
    detail = data;
  }
  return {
    product_id: detail.product_id,
    option: formatOptions(detail),
    bundle: (detail.product_bundle || []).map((bundleItem) => {
      const price = (bundleItem == null ? void 0 : bundleItem.bundle_sum_type) === "markdown" ? `-${Number(bundleItem.bundle_sum_price)}` : Number(bundleItem.bundle_sum_price);
      return {
        ...bundleItem,
        title: bundleItem.bundle_title,
        group_id: bundleItem.bundle_group_id,
        id: bundleItem.bundle_id,
        product_id: bundleItem.bundle_product_id,
        _bundle_product_id: bundleItem.bundle_product_id,
        bundle_variant_id: bundleItem.bundle_variant_id,
        quantity: bundleItem.num,
        option: bundleItem.option.map((optionItem) => {
          return {
            ...optionItem,
            name: optionItem.name["auto"],
            quantity: bundleItem.num,
            product_option_item_id: optionItem.option_group_item_id
          };
        }),
        price,
        original_total: bundleItem.bundle_selling_price ?? price,
        original_price: bundleItem.bundle_selling_price ?? price
      };
    }),
    product_variant_id: detail.product_variant_id || 0,
    quantity: Number(detail.product_quantity)
  };
};
var normalizeProductNote = (item) => {
  var _a;
  const note = ((_a = item == null ? void 0 : item._extend) == null ? void 0 : _a.note) ?? (item == null ? void 0 : item.note) ?? "";
  return String(note).trim();
};
var isSameProduct = (a, b) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
  const isSameNote = normalizeProductNote(a) === normalizeProductNote(b);
  if ((0, import_utils.isNormalProductByDurationSchedule)(a) && (0, import_utils.isNormalProductByDurationSchedule)(b)) {
    return ((_b = (_a = a._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.rowKey) === ((_d = (_c = b._extend) == null ? void 0 : _c.other) == null ? void 0 : _d.rowKey) && ((_e = a._extend) == null ? void 0 : _e.total) === ((_f = b._extend) == null ? void 0 : _f.total) && isSameNote;
  }
  return ((_h = (_g = a._extend) == null ? void 0 : _g.other) == null ? void 0 : _h.rowKey) === ((_j = (_i = b._extend) == null ? void 0 : _i.other) == null ? void 0 : _j.rowKey) && a._serviceKey === b._serviceKey && a._holderKey === b._holderKey && isSameNote;
};
var getIsPromotionProduct = (item) => {
  var _a, _b, _c, _d;
  return ((_b = (_a = item._extend) == null ? void 0 : _a._promotion) == null ? void 0 : _b.inPromotion) && !((_d = (_c = item._extend) == null ? void 0 : _c._promotion) == null ? void 0 : _d._giftInfo);
};
var addService = (list, addItem, state, isMultiDay) => {
  var _a, _b;
  let value = list;
  let count;
  if (isMultiDay && (0, import_utils2.isArr)(addItem)) {
    return {
      list: [...addItem, ...value],
      count: 1
    };
  }
  if (!(0, import_utils.isNormalProductByDurationSchedule)(addItem) && !getIsOverlayProduct(addItem, state)) {
    const quantity = addItem._extend.quantity || 1;
    count = quantity;
    for (let i = 0; i < quantity; i++) {
      const singleItem = {
        ...addItem,
        _id: (0, import_utils2.getUniqueId)(),
        // 每个卡片都有独立的 ID
        _extend: {
          ...addItem._extend,
          quantity: 1,
          other: {
            ...((_a = addItem._extend) == null ? void 0 : _a.other) || {},
            quantity: 1
          }
        }
      };
      value.unshift(singleItem);
    }
  } else {
    let isNotSame = true;
    let isSetCount = false;
    if (addItem == null ? void 0 : addItem._giftInfo) {
      const _lists = [...list, addItem];
      const count2 = ((_b = addItem == null ? void 0 : addItem._extend) == null ? void 0 : _b.quantity) || 1;
      return { list: _lists, quantity: count2 };
    }
    value = (list || []).map((item) => {
      var _a2, _b2, _c, _d, _e;
      const isGoodPassDiscountProduct = (item.discount_list || []).some((item2) => item2.type === "good_pass");
      const isEdit = item == null ? void 0 : item.edit;
      const bundleDiscountList = [];
      (((_b2 = (_a2 = item == null ? void 0 : item._extend) == null ? void 0 : _a2.other) == null ? void 0 : _b2.bundle) || []).forEach((item2) => {
        bundleDiscountList.push(...(item2 == null ? void 0 : item2.discount_list) || []);
      });
      const isPromotion = getIsPromotionProduct(item);
      const isGoodPassBundleProduct = bundleDiscountList.some((item2) => item2.type === "good_pass");
      if (isSameProduct(item, addItem) && !isSetCount && !isGoodPassDiscountProduct && !isEdit && !isGoodPassBundleProduct && !isPromotion && !(item == null ? void 0 : item._giftInfo) && !addItem._extend.weighing) {
        isNotSame = false;
        const quantity = (((_c = item == null ? void 0 : item._extend) == null ? void 0 : _c.quantity) || 1) + (((_d = addItem == null ? void 0 : addItem._extend) == null ? void 0 : _d.quantity) || 1);
        count = quantity;
        isSetCount = true;
        return {
          ...item,
          _extend: {
            ...item._extend,
            quantity,
            other: {
              ...((_e = item._extend) == null ? void 0 : _e.other) || {},
              quantity
            }
          }
        };
      }
      return item;
    });
    const _idx = value.findIndex((item) => item.id === addItem.id);
    if (_idx !== -1) {
      const [removed] = value.splice(_idx, 1);
      value.unshift(removed);
    }
    if (isNotSame) {
      value.unshift(addItem);
      count = addItem._extend.quantity;
    }
  }
  return { list: value, quantity: count };
};
var addServiceScroll = (rowKey, cacheItem) => {
  const list = document.querySelectorAll(`#rowKey-${rowKey}`);
  setTimeout(() => {
    if (list.length && (0, import_utils.isNormalProductByDurationSchedule)(cacheItem)) {
      list[list.length - 1].scrollIntoView({
        behavior: "smooth",
        block: "center"
      });
    } else {
      setTimeout(() => {
        const bookingWrap = document.querySelectorAll(`.pisell-lowcode__booking-service-wrap`);
        if (bookingWrap.length) {
          bookingWrap[0].scrollTo({
            top: 0,
            behavior: "smooth"
          });
        }
      }, 100);
    }
  });
};
var getCartProductOverlay = (state) => {
  var _a, _b, _c;
  return ((_c = (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.cart_product_overlay) || { type: "product_all" };
};
var getIsOverlayProduct = (item, state) => {
  const { type, product_ids } = getCartProductOverlay(state);
  if (type === "product_all") {
    return true;
  }
  return product_ids.includes(item.product_id || item.id);
};
var getIsShowNumber = (item, state) => {
  const isBookingTicket2 = state.isBookingTicket2;
  if ((0, import_utils3.isMultiDayProduct)(item)) {
    return false;
  }
  return (0, import_utils.isNormalProductByDurationSchedule)(item) || isBookingTicket2 && getIsOverlayProduct(item, state);
};
var genServiceKey = (item) => {
  var _a, _b, _c;
  const product_id = item.product_id;
  const durationKey = (_a = item._extend) == null ? void 0 : _a.duration;
  const start_time = (_b = item._extend) == null ? void 0 : _b.start_time;
  const total = (_c = item._extend) == null ? void 0 : _c.total;
  let resourceKey = "";
  Object.values(item._extend.resource || []).forEach((resources) => {
    resources.forEach((resource) => {
      resourceKey += `${resource.relation_id}`;
    });
  });
  return `${product_id}-${durationKey}-${resourceKey}-${start_time}-${total}`;
};
var genHolderKey = (item) => {
  var _a, _b, _c;
  const product_id = item.product_id;
  let holder_id;
  if ((0, import_utils2.isArr)((_a = item._extend) == null ? void 0 : _a.holder_id)) {
    holder_id = (_b = item._extend) == null ? void 0 : _b.holder_id.join("-");
  } else {
    holder_id = (_c = item._extend) == null ? void 0 : _c.holder_id;
  }
  return `${product_id}-${holder_id}`;
};
var getIsParallelResourcesBooking = (record) => {
  return (record == null ? void 0 : record.relation_id) === 0 && (record == null ? void 0 : record.relation_type) === "";
};
var formatScanCustomer = (data) => {
  var _a;
  const { result, scanCode } = data;
  const { response, searchType } = result || {};
  const { data: customerData, code = 200 } = response || {};
  if (code !== 200) {
    return null;
  }
  if ((0, import_utils2.isArr)(customerData)) {
    return { searchType, data: (_a = customerData[0]) == null ? void 0 : _a.customer, scanCode };
  }
  return { searchType, data: customerData == null ? void 0 : customerData.customer, scanCode };
};
var formatScanGlobal = (data) => {
  var _a;
  const { result, scanCode } = data;
  const { response, searchType } = result || {};
  const { data: resultData, code } = response || {};
  if (code !== 200 && searchType !== "local_product") {
    return null;
  }
  if (searchType === "wallet") {
    return { searchType, data: resultData.customer, scanCode };
  }
  if (searchType === "walletPass") {
    return { searchType, data: (_a = resultData == null ? void 0 : resultData[0]) == null ? void 0 : _a.customer, scanCode };
  }
  if (searchType === "product" || searchType === "local_product") {
    return { searchType, data: resultData, scanCode };
  }
  if (searchType === "order") {
    return { searchType, data: resultData, scanCode };
  }
};
var createSimpleCacheItem = (item, e, state) => {
  let cacheItem = {
    ...item,
    product_id: item.id,
    _id: (0, import_utils2.getUniqueId)(),
    _key: e.key,
    _extend: {
      start_date: state.date.value,
      quantity: (e == null ? void 0 : e.quantity) || 1,
      price: item.price,
      product_name: item.title,
      other: e
    },
    new: 1
  };
  return cacheItem;
};
var getBookingTicketKey = (osKey) => {
  return `bookingTicket-${osKey}`;
};
var getShopDiscountKey = (osKey) => {
  return `shopDiscount-${osKey}`;
};
var rulesHooks = {
  // 获取商品关键信息
  getProduct(product) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
    let vouchersApplicable = product.vouchersApplicable;
    if (!(0, import_utils2.isBoolean)(vouchersApplicable)) {
      if (product == null ? void 0 : product._giftInfo) {
        vouchersApplicable = false;
      }
    }
    const price = ((_b = (_a = product._extend) == null ? void 0 : _a._promotion) == null ? void 0 : _b.finalPrice) ?? product._extend.price;
    const detail = {
      booking_id: product.booking_id,
      id: product.id,
      _id: product._id,
      price,
      total: product._extend.total,
      discount_list: product.discount_list,
      origin_total: product._extend.origin_total,
      num: product._extend.quantity,
      quantity: product._extend.quantity || 1,
      vouchersApplicable,
      holder_id: (_c = product._extend) == null ? void 0 : _c.holder_id,
      isNormalProduct: (_d = product._extend) == null ? void 0 : _d.isNormalProduct,
      startDate: (_e = product._extend) == null ? void 0 : _e.startDate,
      bundle: ((_g = (_f = product._extend) == null ? void 0 : _f.other) == null ? void 0 : _g.bundle) || [],
      options: ((_i = (_h = product._extend) == null ? void 0 : _h.other) == null ? void 0 : _i.option) || [],
      main_product_selling_price: (_j = product._extend) == null ? void 0 : _j.main_product_selling_price,
      inPromotion: (_l = (_k = product._extend) == null ? void 0 : _k._promotion) == null ? void 0 : _l.inPromotion,
      _promotion: (_m = product._extend) == null ? void 0 : _m._promotion
    };
    return detail;
  },
  setProduct(product, values) {
    const detail = {
      ...product,
      _id: values._id || product._id,
      discount_list: values.discount_list,
      _extend: {
        ...product._extend,
        other: {
          ...product._extend.other,
          ..."bundle" in values ? { bundle: values.bundle } : {},
          // 仅在有有效数组时写入，避免 `options: undefined` 清空 other.option
          ...Array.isArray(values.options) ? { option: values.options } : {}
        },
        ..."total" in values ? { total: values.total } : {},
        ..."main_product_selling_price" in values ? { main_product_selling_price: values.main_product_selling_price } : {},
        ..."quantity" in values ? { quantity: values.quantity } : {}
      }
    };
    return detail;
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  addService,
  addServiceScroll,
  clearAllCache,
  clearAllCacheByOsKey,
  clearAllProductCache,
  clearBoardConfigCache,
  clearCache,
  clearProductCache,
  createSimpleCacheItem,
  formatBookingList,
  formatDateToStr,
  formatHolder,
  formatOptions,
  formatScanCustomer,
  formatScanGlobal,
  genHolderKey,
  genServiceKey,
  getBoardConfigCache,
  getBookingTicketKey,
  getCache,
  getCartProductOverlay,
  getDefaultStartParam,
  getDisabledEdit,
  getEffectiveMenuListIds,
  getIsOverlayProduct,
  getIsParallelResourcesBooking,
  getIsShowNumber,
  getNextTimeSlice,
  getProductCache,
  getShopDiscountKey,
  isSameProduct,
  normalizeMenuListIds,
  restoreProductOtherData,
  rulesHooks,
  setBoardConfigCache,
  setCache,
  setProductCache
});
