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); }
/**
 * 将平面图点击得到的宿主 booking 原始行解析为详情弹窗视图模型（防御性读取，缺字段则省略对应区块）。
 * 人数、起止时刻、迟到/超时、倒计时、进度等与 {@link rawToBooking} / RoomCard 一致。
 */
import dayjs from 'dayjs';
import { locales } from '@pisell/utils';
import { rawToBooking, resolveBookingCardAmount, resolveBookingStripIdForUi, resolveFloorRoomCardHolder } from "../../floorRoomCard/mapRowToFloorRoomCardData";
import { maskPisellReservationPhoneTail, resolveFloorRoomCardProgressPercent, resolveFloorRoomCardReservedCountdownMinutesForBooking } from "../../floorRoomCard/floorRoomCardUtils";
function str(v) {
  if (v == null) return '';
  var s = String(v).trim();
  return s;
}

/** 预约 raw 是否已为 fully paid（优先 `order.payment_status`，否则顶层 `payment_status`） */
export function isBookingRawOrderPaid(raw) {
  var order = raw.order;
  var fromOrder = order === null || order === void 0 ? void 0 : order.payment_status;
  var fromTop = raw.payment_status;
  var v = fromOrder != null && String(fromOrder).trim() !== '' ? fromOrder : fromTop;
  return String(v !== null && v !== void 0 ? v : '').trim().toLowerCase() === 'paid';
}
function pickTitle(raw, order) {
  var _ref, _order$name;
  var rf = str(raw.relation_form_name);
  if (rf) return rf;
  var on = str((_ref = (_order$name = order.name) !== null && _order$name !== void 0 ? _order$name : order.title) !== null && _ref !== void 0 ? _ref : order.order_name);
  if (on) return on;
  var meta = raw.metadata;
  if (meta && _typeof(meta) === 'object') {
    var _meta$title;
    var t = str((_meta$title = meta.title) !== null && _meta$title !== void 0 ? _meta$title : meta.product_name);
    if (t) return t;
  }
  return '';
}
function formatMoney(v) {
  if (v == null || v === '') return '';
  if (typeof v === 'number' && Number.isFinite(v)) return String(v);
  return str(v);
}
function buildTimeRange(raw, order) {
  var _raw$start_at, _raw$end_at;
  var startAt = (_raw$start_at = raw.start_at) !== null && _raw$start_at !== void 0 ? _raw$start_at : order.start_at;
  var endAt = (_raw$end_at = raw.end_at) !== null && _raw$end_at !== void 0 ? _raw$end_at : order.end_at;
  if (startAt || endAt) {
    var a = startAt ? dayjs(String(startAt)) : null;
    var b = endAt ? dayjs(String(endAt)) : null;
    if (a !== null && a !== void 0 && a.isValid() && b !== null && b !== void 0 && b.isValid()) {
      if (a.isSame(b, 'day')) {
        return "".concat(a.format('HH:mm'), " \u2013 ").concat(b.format('HH:mm'), " \xB7 ").concat(a.format('D MMM'));
      }
      return "".concat(a.format('HH:mm'), " \u2013 ").concat(b.format('HH:mm'), " \xB7 ").concat(a.format('D MMM YYYY'));
    }
    if (a !== null && a !== void 0 && a.isValid()) return a.format('YYYY-MM-DD HH:mm');
  }
  var sd = str(raw.start_date);
  var st = str(raw.start_time);
  var ed = str(raw.end_date);
  var et = str(raw.end_time);
  if (sd && st && ed && et) {
    return "".concat(st, " \u2013 ").concat(et, " ").concat(sd);
  }
  if (sd && st) return "".concat(sd, " ").concat(st);
  var sched = str(order.schedule_date);
  if (sched) return sched;
  return '—';
}
function pickStaff(raw, order) {
  var _order$staff, _raw$staff;
  var s = str(raw.staff_name) || str(raw.assignee_name) || str(order.staff_name) || str((_order$staff = order.staff) === null || _order$staff === void 0 ? void 0 : _order$staff.name) || str((_raw$staff = raw.staff) === null || _raw$staff === void 0 ? void 0 : _raw$staff.name);
  return s || undefined;
}
function pickStatusBadge(raw) {
  var s = str(raw.status);
  if (!s) return undefined;
  var k = s.toLowerCase().replace(/\s+/g, '_');
  var successKeys = new Set(['started', 'confirmed', 'active', 'checked_in', 'checkin', 'in_progress']);
  var warningKeys = new Set(['pending', 'pending_payment', 'draft', 'waiting', 'hold']);
  var dangerKeys = new Set(['cancelled', 'canceled', 'void', 'refunded']);
  var variant = 'neutral';
  if (successKeys.has(k)) variant = 'success';else if (warningKeys.has(k)) variant = 'warning';else if (dangerKeys.has(k)) variant = 'danger';
  return {
    labelKey: "pisell-reservation.booking-detail.status-enum.".concat(k),
    variant: variant
  };
}
function titleCaseStatusWords(s) {
  return s.split(/[_\s\-]+/).filter(Boolean).map(function (w) {
    return w.charAt(0).toUpperCase() + w.slice(1).toLowerCase();
  }).join(' ');
}
function roomTitleFromRow(row) {
  if (!row) return undefined;
  var parts = [row.code, row.main_field].filter(function (x) {
    return x && String(x).trim();
  });
  return parts.length ? parts.join(' · ') : undefined;
}
function roomCapacityFromRow(row) {
  if (!(row !== null && row !== void 0 && row.capacityLabel)) return undefined;
  var c = String(row.capacityLabel).trim();
  return c || undefined;
}

/** 与平面图 RoomCard（guestDisplayLine(holder, true)）同序逻辑 */
function floorRoomCardGuestHeadline(holder) {
  var _holder$name;
  if (!holder) return '';
  var n = (_holder$name = holder.name) === null || _holder$name === void 0 ? void 0 : _holder$name.trim();
  if (n) return n;
  if (holder.phone) {
    var m = maskPisellReservationPhoneTail(holder.phone);
    return m || '';
  }
  return '';
}

/**
 * @param raw 单条 floorMapSourceBookings 项
 * @param roomRow 当前桌位行（容量、展示名与图元一致）
 */
/** 彩色信息头（订单摘要 + 支付/Due） */

function parseQuantity(v) {
  if (v == null || v === '') return null;
  if (typeof v === 'number' && Number.isFinite(v)) return Math.max(0, Math.round(v));
  var n = Number(String(v).replace(/,/g, '').trim());
  return Number.isFinite(n) ? Math.max(0, Math.round(n)) : null;
}
function orderCurrencySymbol(order) {
  var s = str(order.currency_symbol);
  if (s) return s;
  return '$';
}
function moneyWithSymbol(symbol, amount) {
  var f = formatMoney(amount);
  if (!f) return "".concat(symbol, "\u2014");
  if (f.startsWith(symbol) || f.startsWith('$') || f.startsWith('¥') || f.startsWith('€')) return f;
  return "".concat(symbol).concat(f);
}

/**
 * 与截图一致：`15:10 31 Mar ~ 15:40 31 Mar`；无完整字段时回退 {@link buildTimeRange}。
 */
function buildStripScheduleLine(raw, order) {
  var _raw$start_at2, _raw$end_at2;
  var startAt = (_raw$start_at2 = raw.start_at) !== null && _raw$start_at2 !== void 0 ? _raw$start_at2 : order.start_at;
  var endAt = (_raw$end_at2 = raw.end_at) !== null && _raw$end_at2 !== void 0 ? _raw$end_at2 : order.end_at;
  if (startAt || endAt) {
    var a = startAt ? dayjs(String(startAt)) : null;
    var b = endAt ? dayjs(String(endAt)) : null;
    if (a !== null && a !== void 0 && a.isValid() && b !== null && b !== void 0 && b.isValid()) {
      return "".concat(a.format('HH:mm'), " ").concat(a.format('D MMM'), " ~ ").concat(b.format('HH:mm'), " ").concat(b.format('D MMM'));
    }
    if (a !== null && a !== void 0 && a.isValid()) return "".concat(a.format('HH:mm'), " ").concat(a.format('D MMM'));
  }
  var sd = str(raw.start_date);
  var st = str(raw.start_time);
  var ed = str(raw.end_date);
  var et = str(raw.end_time);
  if (sd && st && ed && et) {
    var padTime = function padTime(t) {
      return t.length === 5 ? "".concat(t, ":00") : t;
    };
    var _a = dayjs("".concat(sd, "T").concat(padTime(st)));
    var _b = dayjs("".concat(ed, "T").concat(padTime(et)));
    if (_a.isValid() && _b.isValid()) {
      return "".concat(_a.format('HH:mm'), " ").concat(_a.format('D MMM'), " ~ ").concat(_b.format('HH:mm'), " ").concat(_b.format('D MMM'));
    }
  }
  return buildTimeRange(raw, order);
}

/** 与弹窗商品列表同源：顶层 `products[]` 有效元素个数 */
function countTopLevelProductLines(raw) {
  var p = raw.products;
  if (!Array.isArray(p)) return null;
  return p.filter(function (x) {
    return x && _typeof(x) === 'object';
  }).length;
}

/**
 * 预约详情正文顶部信息条：字段来自 order.summary / order 与 raw 起止时间。
 */
export function bookingDetailOrderStripFromRaw(raw) {
  var _ref2, _countTopLevelProduct, _order$payment_status, _sum$expect_amount;
  var order = (_ref2 = raw.order) !== null && _ref2 !== void 0 ? _ref2 : {};
  var sum = order.summary;
  var sym = orderCurrencySymbol(order);
  var eyebrow = str(raw.relation_form_name) || pickTitle(raw, order) || str(raw.booking_id) || '—';
  var stripBookingId = resolveBookingStripIdForUi(raw);
  var itemsCount = (_countTopLevelProduct = countTopLevelProductLines(raw)) !== null && _countTopLevelProduct !== void 0 ? _countTopLevelProduct : parseQuantity(sum === null || sum === void 0 ? void 0 : sum.product_quantity);
  var orderTotalWithSymbol = moneyWithSymbol(sym, sum === null || sum === void 0 ? void 0 : sum.total_amount);
  var payRaw = (_order$payment_status = order.payment_status) !== null && _order$payment_status !== void 0 ? _order$payment_status : raw.payment_status;
  var paymentStatusRaw = payRaw != null && String(payRaw).trim() !== '' ? String(payRaw).trim() : undefined;
  var dueBase = (_sum$expect_amount = sum === null || sum === void 0 ? void 0 : sum.expect_amount) !== null && _sum$expect_amount !== void 0 ? _sum$expect_amount : sum === null || sum === void 0 ? void 0 : sum.total_amount;
  var dueWithSymbol = moneyWithSymbol(sym, dueBase);
  return {
    eyebrow: eyebrow,
    stripBookingId: stripBookingId,
    scheduleLine: buildStripScheduleLine(raw, order),
    itemsCount: itemsCount,
    orderTotalWithSymbol: orderTotalWithSymbol,
    paymentStatusRaw: paymentStatusRaw,
    dueWithSymbol: dueWithSymbol
  };
}
export function bookingDetailFromRaw(raw, roomRow) {
  var _ref3, _raw$booking_id, _holderResolved$name, _order$payment_status2;
  var order = (_ref3 = raw.order) !== null && _ref3 !== void 0 ? _ref3 : {};
  var bid = (_raw$booking_id = raw.booking_id) !== null && _raw$booking_id !== void 0 ? _raw$booking_id : raw.id;
  var bookingIdLabel = bid != null && String(bid) !== '' ? String(bid) : '—';
  var title = pickTitle(raw, order) || bookingIdLabel;
  var holderResolved = resolveFloorRoomCardHolder(raw);
  var contactName = (holderResolved === null || holderResolved === void 0 || (_holderResolved$name = holderResolved.name) === null || _holderResolved$name === void 0 ? void 0 : _holderResolved$name.trim()) || undefined;
  var contactPhone = holderResolved === null || holderResolved === void 0 ? void 0 : holderResolved.phone;
  var guestHeadline = floorRoomCardGuestHeadline(holderResolved);
  var payRaw = (_order$payment_status2 = order.payment_status) !== null && _order$payment_status2 !== void 0 ? _order$payment_status2 : raw.payment_status;
  var payLower = payRaw != null && String(payRaw).trim() !== '' ? String(payRaw).trim().toLowerCase() : '';
  var displayAmt = resolveBookingCardAmount(raw, order, payLower);
  var totalAmountLabel = displayAmt != null && String(displayAmt) !== '' ? formatMoney(displayAmt) : undefined;
  var paymentStatusRaw = payRaw != null && String(payRaw).trim() !== '' ? String(payRaw).trim() : undefined;
  var bk = rawToBooking(raw, 0);
  var reservedCountdownMinutes = resolveFloorRoomCardReservedCountdownMinutesForBooking(bk);
  var progressPercent = resolveFloorRoomCardProgressPercent(bk);
  var badge = pickStatusBadge(raw);
  var statusStr = str(raw.status);
  var statusBadgeLabel;
  var statusBadgeVariant;
  if (statusStr && badge) {
    statusBadgeVariant = badge.variant;
    var localized = locales.getText(badge.labelKey);
    statusBadgeLabel = localized && localized !== badge.labelKey ? localized : titleCaseStatusWords(statusStr);
  }
  return {
    bookingIdLabel: bookingIdLabel,
    internalId: raw.id,
    statusRaw: statusStr || undefined,
    statusBadgeLabel: statusBadgeLabel,
    statusBadgeVariant: statusBadgeVariant,
    title: title,
    contactName: contactName || undefined,
    contactPhone: contactPhone,
    guestHeadline: guestHeadline,
    timeRangeLabel: buildTimeRange(raw, order),
    staffLabel: pickStaff(raw, order),
    paymentStatusRaw: paymentStatusRaw,
    totalAmountLabel: totalAmountLabel,
    partySize: bk.number,
    startDisplay: "".concat(bk.start_date, " ").concat(bk.start_time).trim(),
    endDisplay: "".concat(bk.end_date, " ").concat(bk.end_time).trim(),
    cardAmount: bk.amount,
    lateTimeMinutes: bk.lateTime != null && bk.lateTime > 0 ? bk.lateTime : undefined,
    timeoutTimeMinutes: bk.timeoutTime != null && bk.timeoutTime > 0 ? bk.timeoutTime : undefined,
    reservedCountdownMinutes: reservedCountdownMinutes,
    progressPercent: progressPercent,
    hostBookingStatus: bk.hostBookingStatus,
    roomCapacityLabel: roomCapacityFromRow(roomRow),
    roomTitleLabel: roomTitleFromRow(roomRow)
  };
}