var _excluded = ["bookings"],
  _excluded2 = ["bookings"],
  _excluded3 = ["bookings"];
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 _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';
/** 预约状态：协议 appointment_status 优先，兼容历史 status */
function getBookingAppointmentStatus(booking) {
  var _ref, _booking$appointment_;
  return String((_ref = (_booking$appointment_ = booking.appointment_status) !== null && _booking$appointment_ !== void 0 ? _booking$appointment_ : booking.status) !== null && _ref !== void 0 ? _ref : '');
}

// ─────────────────────────────────────────────────────────────────
// 时间戳 / 范围解析
// ─────────────────────────────────────────────────────────────────

function toTimestamp(value) {
  if (value === undefined || value === null || value === '') return 0;
  if (typeof value === 'number') return value;
  // 使用 dayjs 按本地时区解析，避免 new Date("YYYY-MM-DD") 被当作 UTC 0 点
  var d = dayjs(value);
  return d.isValid() ? d.valueOf() : 0;
}

/** 日期范围端点解析：纯日期串自动对齐到当天起止边界（本地时区） */
var DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
function toRangeBoundary(value, isEnd) {
  if (value === undefined || value === null || value === '') return 0;
  if (typeof value === 'number') return value;
  var str = String(value).trim();
  var d = dayjs(str);
  if (!d.isValid()) return 0;
  if (DATE_ONLY_RE.test(str)) {
    return (isEnd ? d.endOf('day') : d.startOf('day')).valueOf();
  }
  return d.valueOf();
}

/**
 * 将 start_date / start_time（或 end_*）拼成可被 Date 稳定解析的字符串。
 * 时间字段协议为 H:i（如 15:00）时补全为 H:i:00，避免部分环境对「无秒」非 ISO 串（空格分隔）解析不一致。
 */
function bookingDateTimeString(datePart, timePart) {
  var d = (datePart !== null && datePart !== void 0 ? datePart : '').trim();
  var t = (timePart !== null && timePart !== void 0 ? timePart : '').trim();
  if (t && /^\d{1,2}:\d{2}$/.test(t)) {
    t = "".concat(t, ":00");
  }
  return "".concat(d, " ").concat(t).trim();
}
function parseDateRange(range) {
  if (!Array.isArray(range) || range.length < 2) return null;
  var start = toRangeBoundary(range[0], false);
  var end = toRangeBoundary(range[1], true);
  if (!start && !end) return null;
  return [start, end];
}
function parseNumberRange(range) {
  if (!Array.isArray(range) || range.length < 2) return null;
  var min = Number(range[0]);
  var max = Number(range[1]);
  if (isNaN(min) || isNaN(max)) return null;
  return [min, max];
}

// ─────────────────────────────────────────────────────────────────
// 预编译过滤上下文：将 filters 一次性解析为高效的 Set / Range，
// 供 matchOrder、matchBooking 复用，避免重复计算
// ─────────────────────────────────────────────────────────────────

function prepareFilters(f) {
  var _f$order_payment_stat, _f$order_status, _f$order_sales_channe, _f$payment_method, _f$appointment_status, _f$form_record_ids;
  var hasCustomerId = f.customer_id !== undefined && f.customer_id !== null;
  return {
    orderPaymentStatusSet: (_f$order_payment_stat = f.order_payment_status) !== null && _f$order_payment_stat !== void 0 && _f$order_payment_stat.length ? new Set(f.order_payment_status) : null,
    orderStatusSet: (_f$order_status = f.order_status) !== null && _f$order_status !== void 0 && _f$order_status.length ? new Set(f.order_status) : null,
    orderSalesChannelSet: (_f$order_sales_channe = f.order_sales_channel) !== null && _f$order_sales_channe !== void 0 && _f$order_sales_channe.length ? new Set(f.order_sales_channel) : null,
    paymentMethodSet: (_f$payment_method = f.payment_method) !== null && _f$payment_method !== void 0 && _f$payment_method.length ? new Set(f.payment_method) : null,
    appointmentStatusSet: (_f$appointment_status = f.appointment_status) !== null && _f$appointment_status !== void 0 && _f$appointment_status.length ? new Set(f.appointment_status) : null,
    formRecordIdSet: (_f$form_record_ids = f.form_record_ids) !== null && _f$form_record_ids !== void 0 && _f$form_record_ids.length ? new Set(f.form_record_ids) : null,
    hasCustomerId: hasCustomerId,
    customerIdStr: hasCustomerId ? String(f.customer_id) : '',
    hasBusinessCode: !!f.business_code,
    businessCode: f.business_code,
    bookingTimeRange: parseDateRange(f.sales_time_between),
    createdAtRange: parseDateRange(f.created_at_between),
    updatedAtRange: parseDateRange(f.updated_at_between),
    numberRange: parseNumberRange(f.number_between),
    totalAmountRange: Array.isArray(f.total_amount_between) && f.total_amount_between.length === 2 ? f.total_amount_between : null,
    keywordLower: f.keyword ? f.keyword.toLowerCase() : '',
    afterExecutionTimeMs: function () {
      var raw = f.after_execution_time;
      if (raw === undefined || raw === null || raw === '') return null;
      var ms = toTimestamp(raw);
      return Number.isFinite(ms) ? ms : null;
    }(),
    enableChildBookingFilter: f.child_booking === 1
  };
}

// ─────────────────────────────────────────────────────────────────
// 订单级匹配：不通过则整个 order 下所有 bookings 跳过
// ─────────────────────────────────────────────────────────────────

function matchOrder(order, ctx) {
  if (ctx.hasBusinessCode && order.business_code !== ctx.businessCode) return false;
  if (ctx.hasCustomerId && String(order.customer_id) !== ctx.customerIdStr) return false;
  if (ctx.orderPaymentStatusSet && !ctx.orderPaymentStatusSet.has(order.payment_status)) return false;
  if (ctx.orderStatusSet && !ctx.orderStatusSet.has(order.status)) return false;
  if (ctx.orderSalesChannelSet && !ctx.orderSalesChannelSet.has(order.order_sales_channel)) return false;
  if (ctx.paymentMethodSet) {
    var pm = order.payments;
    if (!Array.isArray(pm) || pm.length === 0) return false;
    var matched = false;
    for (var k = 0; k < pm.length; k++) {
      if (ctx.paymentMethodSet.has(pm[k].code)) {
        matched = true;
        break;
      }
    }
    if (!matched) return false;
  }
  if (ctx.createdAtRange) {
    var ts = toTimestamp(order.created_at);
    if (ts < ctx.createdAtRange[0] || ts > ctx.createdAtRange[1]) return false;
  }
  if (ctx.updatedAtRange) {
    var _ts = toTimestamp(order.updated_at);
    if (_ts < ctx.updatedAtRange[0] || _ts > ctx.updatedAtRange[1]) return false;
  }
  if (ctx.totalAmountRange) {
    var _order$summary$total_, _order$summary;
    var raw = (_order$summary$total_ = (_order$summary = order.summary) === null || _order$summary === void 0 ? void 0 : _order$summary.total_amount) !== null && _order$summary$total_ !== void 0 ? _order$summary$total_ : order.total_amount;
    var amt = Number(raw);
    if (isNaN(amt)) return false;
    if (ctx.totalAmountRange[0] != null && amt < ctx.totalAmountRange[0]) return false;
    if (ctx.totalAmountRange[1] != null && amt > ctx.totalAmountRange[1]) return false;
  }
  return true;
}

// ─────────────────────────────────────────────────────────────────
// Booking 级匹配：在订单通过之后逐条检查每个 booking
// orderInfo 用于 keyword 搜索时的 JSON 序列化
// ─────────────────────────────────────────────────────────────────

function matchBooking(booking, orderInfo, ctx) {
  if (ctx.enableChildBookingFilter) {
    var _parent_id, _item_type;
    var parentId = Number((_parent_id = booking.parent_id) !== null && _parent_id !== void 0 ? _parent_id : 0);
    var itemType = String((_item_type = booking.item_type) !== null && _item_type !== void 0 ? _item_type : '');
    var isMatched = parentId !== 0 && itemType !== 'recurring_booking' || parentId === 0 && itemType === 'recurring_booking';
    if (!isMatched) return false;
  }
  if (ctx.appointmentStatusSet && !ctx.appointmentStatusSet.has(getBookingAppointmentStatus(booking))) return false;
  if (ctx.bookingTimeRange) {
    var ts = toTimestamp(bookingDateTimeString(booking.start_date, booking.start_time));
    if (ts < ctx.bookingTimeRange[0] || ts > ctx.bookingTimeRange[1]) return false;
  }
  if (ctx.afterExecutionTimeMs != null) {
    var bookingStartMs = toTimestamp(bookingDateTimeString(booking.start_date, booking.start_time));
    if (!Number.isFinite(bookingStartMs) || bookingStartMs < ctx.afterExecutionTimeMs) return false;
  }
  if (ctx.numberRange) {
    var num = Number(booking.number);
    if (isNaN(num) || num < ctx.numberRange[0] || num > ctx.numberRange[1]) return false;
  }
  if (ctx.formRecordIdSet) {
    var formMatched = false;
    var resources = booking.resources;
    if (Array.isArray(resources)) {
      for (var r = 0; r < resources.length; r++) {
        if (resources[r].relation_type === 'form' && ctx.formRecordIdSet.has(resources[r].relation_id)) {
          formMatched = true;
          break;
        }
      }
    }
    if (!formMatched && booking.relation_type === 'form' && booking.relation_id && booking.relation_id > 0) {
      formMatched = ctx.formRecordIdSet.has(booking.relation_id);
    }
    if (!formMatched) return false;
  }
  if (ctx.keywordLower) {
    var target = orderInfo ? _objectSpread(_objectSpread({}, booking), {}, {
      order: orderInfo
    }) : booking;
    var str = JSON.stringify(target).toLowerCase();
    if (!str.includes(ctx.keywordLower)) return false;
  }
  return true;
}

// ─────────────────────────────────────────────────────────────────
// 当前预约归属商品：先按 schedule_event_id 命中，再按 relation_items.resource_id 追加（去重保序）
// ─────────────────────────────────────────────────────────────────

/**
 * 从整单 `order.products` 中归集属于指定 `booking` 的明细行。
 * - 第一遍：`product.schedule_event_id === booking.schedule_event_id`（保持 products 原顺序）
 * - 第二遍：按 `relation_items` 顺序追加 `resource_id` 与 `order_detail_id` 匹配且尚未收录的行
 */
export function productsForBooking(order, booking) {
  var products = order.products;
  if (!Array.isArray(products) || products.length === 0) return [];
  var bookingEventId = booking.schedule_event_id;
  var byDetailId = new Map();
  for (var i = 0, len = products.length; i < len; i++) {
    var p = products[i];
    var oid = p.order_detail_id;
    if (oid === undefined || oid === null) continue;
    var detailId = Number(oid);
    if (Number.isNaN(detailId)) continue;
    byDetailId.set(detailId, p);
  }
  var seen = new Set();
  var out = [];
  for (var _i = 0, _len = products.length; _i < _len; _i++) {
    var _p = products[_i];
    var _oid = _p.order_detail_id;
    if (_oid === undefined || _oid === null) continue;
    var _detailId = Number(_oid);
    if (Number.isNaN(_detailId)) continue;
    if (bookingEventId !== undefined && bookingEventId !== null && _p.schedule_event_id !== undefined && _p.schedule_event_id !== null && Number(_p.schedule_event_id) === Number(bookingEventId)) {
      if (!seen.has(_detailId)) {
        seen.add(_detailId);
        out.push(_p);
      }
    }
  }
  var relationItems = booking.relation_items;
  if (Array.isArray(relationItems) && relationItems.length > 0) {
    for (var r = 0, rLen = relationItems.length; r < rLen; r++) {
      var _relationItems$r;
      var rid = (_relationItems$r = relationItems[r]) === null || _relationItems$r === void 0 ? void 0 : _relationItems$r.resource_id;
      if (rid === undefined || rid === null) continue;
      var _detailId2 = Number(rid);
      if (Number.isNaN(_detailId2) || seen.has(_detailId2)) continue;
      var line = byDetailId.get(_detailId2);
      if (line) {
        seen.add(_detailId2);
        out.push(line);
      }
    }
  }
  return out;
}

// ─────────────────────────────────────────────────────────────────
// 转换：OrderData[] → BookingData[]（独立导出，供其他场景使用）
// ─────────────────────────────────────────────────────────────────

export function flattenOrdersToBookings(orders) {
  if (!orders || !Array.isArray(orders)) return [];
  var result = [];
  for (var i = 0, len = orders.length; i < len; i++) {
    var order = orders[i];
    var bookings = order.bookings;
    if (!Array.isArray(bookings) || bookings.length === 0) continue;
    var _omit = order.bookings,
      orderInfo = _objectWithoutProperties(order, _excluded);
    for (var j = 0, bLen = bookings.length; j < bLen; j++) {
      var booking = bookings[j];
      result.push(_objectSpread(_objectSpread({}, booking), {}, {
        order: orderInfo,
        products: order.products
      }));
    }
  }
  return result;
}

// ─────────────────────────────────────────────────────────────────
// 核心：单遍扫描 — 展开 + 过滤 + 分页
//
// 性能策略：
//  1. 订单级条件在外层循环 matchOrder 预判，不匹配则整组 bookings 跳过
//  2. orderInfo 延迟到有命中 booking 时才创建，同一 order 只创建一次
//  3. 只对最终命中的 booking 做 object spread
// ─────────────────────────────────────────────────────────────────

export function filterBookingsFromOrders(orders, filters) {
  var f = filters || {};
  if (!orders || !Array.isArray(orders)) {
    return {
      list: [],
      count: 0,
      size: 0,
      skip: 0
    };
  }
  var size = f.num || 20;
  var page = f.skip || 1;
  var startIndex = (page - 1) * size;
  var ctx = prepareFilters(f);
  var totalCount = 0;
  var paginatedList = [];
  for (var i = 0, oLen = orders.length; i < oLen; i++) {
    var order = orders[i];
    var bookings = order.bookings;
    if (!Array.isArray(bookings) || bookings.length === 0) continue;

    // 订单级预过滤
    if (!matchOrder(order, ctx)) continue;

    // 订单通过，遍历其 bookings；orderInfo 延迟创建
    var orderInfo = null;
    for (var j = 0, bLen = bookings.length; j < bLen; j++) {
      var booking = bookings[j];

      // keyword 匹配需要 orderInfo，提前创建
      if (ctx.keywordLower && !orderInfo) {
        var _omit = order.bookings,
          rest = _objectWithoutProperties(order, _excluded2);
        orderInfo = rest;
      }
      if (!matchBooking(booking, orderInfo, ctx)) continue;

      // 命中：收集到分页窗口内
      if (totalCount >= startIndex && paginatedList.length < size) {
        if (!orderInfo) {
          var _omit2 = order.bookings,
            _rest = _objectWithoutProperties(order, _excluded3);
          orderInfo = _rest;
        }
        paginatedList.push(_objectSpread(_objectSpread({}, booking), {}, {
          order: orderInfo,
          products: order.products
        }));
      }
      totalCount++;
    }
  }
  return {
    list: paginatedList,
    count: totalCount,
    size: size,
    skip: page
  };
}

// ─────────────────────────────────────────────────────────────────
// 排序预约列表
// order_by 格式："field:direction"，如 "start_at:desc"
// 不带方向后缀则不排序
// ─────────────────────────────────────────────────────────────────

export function sortBookings(result, filters) {
  var f = filters || {};
  var orderBy = f.order_by;
  if (!orderBy) return result;
  var separatorIdx = orderBy.lastIndexOf(':');
  if (separatorIdx === -1) return result;
  var field = orderBy.slice(0, separatorIdx);
  var direction = orderBy.slice(separatorIdx + 1);
  if (direction !== 'asc' && direction !== 'desc') return result;
  var multiplier = direction === 'asc' ? 1 : -1;
  var getTimestamp = function getTimestamp(booking) {
    switch (field) {
      case 'start_at':
        return toTimestamp(bookingDateTimeString(booking.start_date, booking.start_time));
      case 'end_at':
        return toTimestamp(bookingDateTimeString(booking.end_date, booking.end_time));
      case 'created_at':
        return toTimestamp(booking.order.created_at);
      case 'updated_at':
        return toTimestamp(booking.order.updated_at);
      default:
        return 0;
    }
  };
  var sorted = result.list.slice().sort(function (a, b) {
    return (getTimestamp(a) - getTimestamp(b)) * multiplier;
  });
  return _objectSpread(_objectSpread({}, result), {}, {
    list: sorted
  });
}

// ─────────────────────────────────────────────────────────────────
// 兼容独立调用：对已展开的 BookingData[] 做筛选
// 复用 matchOrder + matchBooking，仅负责迭代与分页
// ─────────────────────────────────────────────────────────────────

export function filterBookings(bookings, filters) {
  var f = filters || {};
  if (!bookings || !Array.isArray(bookings)) {
    return {
      list: [],
      count: 0,
      size: 0,
      skip: 0
    };
  }
  var size = f.num || 20;
  var page = f.skip || 1;
  var startIndex = (page - 1) * size;
  var ctx = prepareFilters(f);
  var totalCount = 0;
  var paginatedList = [];
  for (var i = 0, len = bookings.length; i < len; i++) {
    var booking = bookings[i];
    var order = booking.order;

    // 订单级 + booking 级统一匹配
    if (!matchOrder(order, ctx)) continue;
    if (!matchBooking(booking, order, ctx)) continue;
    if (totalCount >= startIndex && paginatedList.length < size) {
      paginatedList.push(_objectSpread(_objectSpread({}, booking), {}, {
        products: booking.order.products
      }));
    }
    totalCount++;
  }
  return {
    list: paginatedList,
    count: totalCount,
    size: size,
    skip: page
  };
}