function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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 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); }
/**
 * HUD 抽屉内 Monitor 表：筛选/排序仅影响抽屉展示，不调父级 floorDay / grid 请求。
 */
import dayjs from 'dayjs';
import { buildDateTime } from "../../pisellSalesManagement/hooks/perspectiveUtils";
import { extractResourceRecordIds } from "./bookingToReservationTables";
import { mergeGridBookingSearchParams } from "./reservationDataUtils";

/** 深拷贝筛参（无函数；与 RecordBoard searchParams 结构一致） */
export function cloneHudDrawerSearchParams(params) {
  try {
    return JSON.parse(JSON.stringify(params !== null && params !== void 0 ? params : {}));
  } catch (_unused) {
    return _objectSpread({}, params !== null && params !== void 0 ? params : {});
  }
}

/**
 * 抽屉内去掉 Monitor 预约日期快筛；从 `filter.values` 移除对应键，避免本地列表仍按父级日期段收窄。
 */
export function stripHudDrawerBookingDateQuickFilter(params) {
  var f = params.filter;
  if (_typeof(f) !== 'object' || f === null || Array.isArray(f)) {
    return;
  }
  var fo = f;
  var v = fo.values;
  if (_typeof(v) !== 'object' || v === null || Array.isArray(v)) {
    return;
  }
  var values = _objectSpread({}, v);
  delete values.booking_time_start_between;
  params.filter = _objectSpread(_objectSpread({}, fo), {}, {
    values: values
  });
}

/**
 * 合并抽屉内 onSearch 增量（与顶栏 Filter 行为对齐：filter.values 深合并）。
 */
export function mergeHudDrawerSearchParams(prev, incoming) {
  var next = _objectSpread(_objectSpread({}, prev), incoming);
  var prevFilter = _typeof(prev.filter) === 'object' && prev.filter !== null ? prev.filter : {};
  if (_typeof(incoming.filter) === 'object' && incoming.filter !== null && !Array.isArray(incoming.filter)) {
    var incFilter = incoming.filter;
    var prevV = _typeof(prevFilter.values) === 'object' && prevFilter.values !== null && !Array.isArray(prevFilter.values) ? prevFilter.values : {};
    var incV = _typeof(incFilter.values) === 'object' && incFilter.values !== null && !Array.isArray(incFilter.values) ? incFilter.values : undefined;
    next.filter = _objectSpread(_objectSpread(_objectSpread({}, prevFilter), incFilter), {}, {
      values: incV != null ? _objectSpread(_objectSpread({}, prevV), incV) : prevV
    });
  }
  return mergeGridBookingSearchParams(next);
}
function getRowStartMs(row) {
  var sa = row.start_at;
  if (typeof sa === 'string' && sa) {
    var d = dayjs(sa);
    if (d.isValid()) return d.valueOf();
  }
  var ds = row.start_date;
  var ts = row.start_time;
  var comb = buildDateTime(ds, ts);
  if (comb) {
    var _d = dayjs(comb);
    if (_d.isValid()) return _d.valueOf();
  }
  return 0;
}
function getRowEndMs(row) {
  var ea = row.end_at;
  if (typeof ea === 'string' && ea) {
    var d = dayjs(ea);
    if (d.isValid()) return d.valueOf();
  }
  var de = row.end_date;
  var te = row.end_time;
  var comb = buildDateTime(de, te);
  if (comb) {
    var _d2 = dayjs(comb);
    if (_d2.isValid()) return _d2.valueOf();
  }
  return 0;
}
function getRowCreatedMs(row) {
  var c = row.created_at;
  if (typeof c === 'string' && c) {
    var d = dayjs(c);
    if (d.isValid()) return d.valueOf();
  }
  return 0;
}
function normalizeRangeBounds(raw) {
  if (!Array.isArray(raw) || raw.length < 2) return null;
  var a = dayjs(raw[0]);
  var b = dayjs(raw[1]);
  if (!a.isValid() || !b.isValid()) return null;
  var t0 = a.valueOf();
  var t1 = b.valueOf();
  return t0 <= t1 ? [t0, t1] : [t1, t0];
}

/** 与 Monitor filter 多选一致：有选项时才收窄 */
function multiSelectMatch(rowVals, selected) {
  if (!Array.isArray(selected) || selected.length === 0) return true;
  var set = new Set(selected.map(function (x) {
    return String(x);
  }));
  if (Array.isArray(rowVals)) {
    return rowVals.some(function (x) {
      return set.has(String(x));
    });
  }
  if (rowVals == null || rowVals === '') return false;
  return set.has(String(rowVals));
}

/** numberRange：`{ min, max }`，null / 空 表示该端不限 */
function numberRangeContains(n, raw) {
  if (raw == null || _typeof(raw) !== 'object' || Array.isArray(raw)) {
    return true;
  }
  var o = raw;
  var minN = o.min != null && o.min !== '' ? Number(o.min) : NaN;
  var maxN = o.max != null && o.max !== '' ? Number(o.max) : NaN;
  var hasMin = Number.isFinite(minN);
  var hasMax = Number.isFinite(maxN);
  if (!hasMin && !hasMax) return true;
  if (!Number.isFinite(n)) return false;
  if (hasMin && n < minN) return false;
  if (hasMax && n > maxN) return false;
  return true;
}
function parseAmount(v) {
  if (v == null || v === '') return null;
  if (typeof v === 'number' && Number.isFinite(v)) return v;
  var n = Number(String(v).replace(/,/g, '').trim());
  return Number.isFinite(n) ? n : null;
}

/** 与列表请求侧一致：partially_paid 与 unpaid 筛选项对齐 */
function paymentStatusForMatch(row) {
  var _order$payment_status;
  var order = row.order;
  var st = (_order$payment_status = order === null || order === void 0 ? void 0 : order.payment_status) !== null && _order$payment_status !== void 0 ? _order$payment_status : row.payment_status;
  var s = String(st !== null && st !== void 0 ? st : '').trim().toLowerCase();
  if (s === 'partially_paid') return 'unpaid';
  return s;
}
function rowMatchesKeyword(row, keyword) {
  var k = keyword.trim().toLowerCase();
  if (!k) return true;
  var acc = [];
  var push = function push(v) {
    if (v == null) return;
    var s = String(v).toLowerCase().trim();
    if (s) acc.push(s);
  };
  push(row.id);
  push(row.booking_id);
  var order = row.order;
  if (order) {
    push(order.shop_full_order_number);
    push(order.note);
    var cust = order.customer;
    if (cust) {
      push(cust.name);
      push(cust.first_name);
      push(cust.last_name);
      push(cust.company_name);
    }
    var ci = order.contacts_info;
    if (ci) {
      push(ci.first_name);
      push(ci.last_name);
      push(ci.phone);
      push(ci.email);
    }
  }
  push(row.notes);
  return acc.some(function (p) {
    return p.includes(k);
  });
}
function rowMatchesValues(row, values) {
  var payment = values.order_payment_status;
  if (Array.isArray(payment) && payment.length > 0) {
    var st = paymentStatusForMatch(row);
    var allowed = new Set(payment.map(function (x) {
      return String(x).toLowerCase();
    }));
    if (st === '' || !allowed.has(st)) {
      return false;
    }
  }
  var appt = values.appointment_status;
  if (Array.isArray(appt) && appt.length > 0) {
    if (!multiSelectMatch(row.appointment_status, appt)) {
      return false;
    }
  }
  var orderStatus = values.order_status;
  if (Array.isArray(orderStatus) && orderStatus.length > 0) {
    var _order$order_status;
    var _order = row.order;
    if (!multiSelectMatch((_order$order_status = _order === null || _order === void 0 ? void 0 : _order.order_status) !== null && _order$order_status !== void 0 ? _order$order_status : _order === null || _order === void 0 ? void 0 : _order.status, orderStatus)) {
      return false;
    }
  }
  var salesCh = values.order_sales_channel;
  if (Array.isArray(salesCh) && salesCh.length > 0) {
    var _order2 = row.order;
    if (!multiSelectMatch(_order2 === null || _order2 === void 0 ? void 0 : _order2.order_sales_channel, salesCh)) {
      return false;
    }
  }
  var payMethod = values.payment_method;
  if (Array.isArray(payMethod) && payMethod.length > 0) {
    var _ref, _order3$payment_metho;
    var _order3 = row.order;
    var rowPm = (_ref = (_order3$payment_metho = _order3 === null || _order3 === void 0 ? void 0 : _order3.payment_method) !== null && _order3$payment_metho !== void 0 ? _order3$payment_metho : _order3 === null || _order3 === void 0 ? void 0 : _order3.pay_method) !== null && _ref !== void 0 ? _ref : _order3 === null || _order3 === void 0 ? void 0 : _order3.payment_methods;
    if (!multiSelectMatch(rowPm, payMethod)) {
      return false;
    }
  }
  var custFilter = values.customer_id;
  if (Array.isArray(custFilter) && custFilter.length > 0) {
    var _order4$customer_id, _order4$customer;
    var _order4 = row.order;
    var cid = (_order4$customer_id = _order4 === null || _order4 === void 0 ? void 0 : _order4.customer_id) !== null && _order4$customer_id !== void 0 ? _order4$customer_id : _order4 === null || _order4 === void 0 || (_order4$customer = _order4.customer) === null || _order4$customer === void 0 ? void 0 : _order4$customer.id;
    if (cid == null || !custFilter.map(String).includes(String(cid))) {
      return false;
    }
  }
  var formIds = values.form_record_ids;
  if (Array.isArray(formIds) && formIds.length > 0) {
    var need = new Set(formIds.map(function (x) {
      return String(x);
    }));
    var got = extractResourceRecordIds(row);
    if (!got.some(function (id) {
      return need.has(id);
    })) {
      return false;
    }
  }
  var numBetween = values.number_between;
  if (numBetween != null && _typeof(numBetween) === 'object') {
    var party = typeof row.number === 'number' && Number.isFinite(row.number) ? row.number : Number(row.number);
    if (!numberRangeContains(Number.isFinite(party) ? party : NaN, numBetween)) {
      return false;
    }
  }
  var order = row.order;
  var sum = order === null || order === void 0 ? void 0 : order.summary;
  var amtBetween = values.total_amount_between;
  if (amtBetween != null && _typeof(amtBetween) === 'object') {
    var _ref2, _parseAmount, _row$amount;
    var amt = (_ref2 = (_parseAmount = parseAmount(sum === null || sum === void 0 ? void 0 : sum.total_amount)) !== null && _parseAmount !== void 0 ? _parseAmount : parseAmount(order === null || order === void 0 ? void 0 : order.total_amount)) !== null && _ref2 !== void 0 ? _ref2 : parseAmount((_row$amount = row.amount) !== null && _row$amount !== void 0 ? _row$amount : row.total);
    if (amt == null || !numberRangeContains(amt, amtBetween)) {
      return false;
    }
  }
  var createdR = normalizeRangeBounds(values.created_at_between);
  if (createdR) {
    var cm = getRowCreatedMs(row);
    if (cm === 0) return false;
    var _createdR = _slicedToArray(createdR, 2),
      t0 = _createdR[0],
      t1 = _createdR[1];
    if (cm < t0 || cm > t1) return false;
  }
  var updatedRaw = row.updated_at;
  var updatedR = normalizeRangeBounds(values.updated_at_between);
  if (updatedR) {
    var u = typeof updatedRaw === 'string' && updatedRaw ? dayjs(updatedRaw).valueOf() : 0;
    if (!u) return false;
    var _updatedR = _slicedToArray(updatedR, 2),
      _t = _updatedR[0],
      _t2 = _updatedR[1];
    if (u < _t || u > _t2) return false;
  }
  var range = normalizeRangeBounds(values.booking_time_start_between);
  if (range) {
    var _range = _slicedToArray(range, 2),
      _t3 = _range[0],
      _t4 = _range[1];
    var startMs = getRowStartMs(row);
    if (startMs === 0) return false;
    if (startMs < _t3 || startMs > _t4) return false;
  }
  return true;
}
function applySort(rows, sortKey) {
  if (!sortKey || !String(sortKey).includes(':')) {
    return rows;
  }
  var _String$split = String(sortKey).split(':'),
    _String$split2 = _slicedToArray(_String$split, 2),
    field = _String$split2[0],
    dir = _String$split2[1];
  var desc = dir === 'desc';
  var list = _toConsumableArray(rows);
  var pick = function pick(r) {
    switch (field) {
      case 'start_at':
      case 'after_execution_time':
        return getRowStartMs(r);
      case 'end_at':
        return getRowEndMs(r);
      case 'created_at':
        return getRowCreatedMs(r);
      default:
        return 0;
    }
  };
  list.sort(function (a, b) {
    var da = pick(a);
    var db = pick(b);
    if (da === db) return 0;
    return desc ? db - da : da - db;
  });
  return list;
}

/**
 * 在「画布资源子集」行上做 keyword + filter.values 本地过滤 + sort。
 * 与 Monitor `getFilterButtonList` 常见项对齐（支付/预约态/订单态/渠道/人数/金额/资源/时间窗等）；未覆盖字段忽略。
 */
export function applyHudDrawerLocalListQuery(rows, searchParams) {
  var out = rows;
  var kw = searchParams.keyword;
  if (typeof kw === 'string' && kw.trim()) {
    out = out.filter(function (r) {
      return rowMatchesKeyword(r, kw);
    });
  }
  var filter = searchParams.filter;
  var values = filter && _typeof(filter) === 'object' && filter !== null && _typeof(filter.values) === 'object' && filter.values !== null && !Array.isArray(filter.values) ? filter.values : {};
  if (Object.keys(values).length > 0) {
    out = out.filter(function (r) {
      return rowMatchesValues(r, values);
    });
  }
  var sort = searchParams.sort;
  if (typeof sort === 'string' && sort) {
    out = applySort(out, sort);
  }
  return out;
}