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); }
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); }
import dayjs from 'dayjs';
import { isMultiDayProduct, isSessionProduct, getDays } from "./serviceTimes";
import { getSumCapacity } from "./resources";
import { flexibleObj } from "./flexible";

/**
 * 把 info2 `cacheItem` 转换为 OS `addProductToOrder(product, booking)` 所需的 booking 入参。
 *
 * 协议严格对齐 `pisell_os/src/modules/Order/TEMP_ORDER_FIELDS_SUMMARY.md` 的 Bookings 章节：
 *   - 顶层只允许出现：schedule_event_id / appointment_status / start_date / start_time / end_date /
 *     end_time / select_date / duration / sub_type / like_status / number / resources / relation_forms /
 *     holder / metadata / is_all / schedule_id / relation_id / form_id / relation_type / product_uid
 *   - bookings[] 不允许出现 `_extend`
 *   - bookings[].metadata 走白名单：unique_identification_number / collect_pax / capacity / holder_id / resource_select_type
 *   - bookings[].resources[] 只接受协议白名单：form_id / relation_type / relation_id / capacity / like_status / metadata / children
 *
 * `product_uid` / `metadata.unique_identification_number` 不在这里生成：
 *   OS `addProductToOrder` 内的 `createLinkedProductAndBooking` 会在最终一步统一改写，
 *   保证商品行 uid 与 booking root 唯一值始终对齐。
 *
 * 复杂 multi-day 展开（createBookingItemsByGroup / concatBookings）首版**不支持**，
 * 由 UI 在 `cart.confirmDetail` 之外通过辅助 API 处理。
 */

/** custom / package 人数维度快照，与 info2 `_extend.capacity` / `metadata.capacity` 对齐。 */

/** 将 UI `_extend.capacity[]` 规范化为 booking.metadata.capacity。 */
function normalizeExtendCapacityForMetadata(capacity) {
  if (!Array.isArray(capacity) || capacity.length === 0) return undefined;
  var normalized = capacity.map(function (item) {
    var _item$value;
    if (!item || _typeof(item) !== 'object') return null;
    if (item.id === undefined || item.id === null) return null;
    var row = {
      id: item.id,
      value: Number((_item$value = item.value) !== null && _item$value !== void 0 ? _item$value : 0)
    };
    if (item.name !== undefined) row.name = item.name;
    return row;
  }).filter(function (item) {
    return item != null;
  });
  return normalized.length > 0 ? normalized : undefined;
}
function safeFormat(value, fmt) {
  if (value === undefined || value === null) return undefined;
  var d = dayjs(value);
  if (!d.isValid()) return undefined;
  return d.format(fmt);
}

/** booking 协议 start_time / end_time：统一 HH:mm（不带秒）。 */
function normalizeTimeString(value) {
  if (value === undefined || value === null) return undefined;
  if (typeof value === 'string') {
    var t = value.trim();
    var hhmmFromHhmmss = t.match(/^(\d{1,2}:\d{2}):\d{2}$/);
    if (hhmmFromHhmmss) return hhmmFromHhmmss[1];
    if (/^\d{1,2}:\d{2}$/.test(t)) return t;
  }
  var d = dayjs(value);
  if (d.isValid()) return d.format('HH:mm');
  return undefined;
}
function resolveDurationMinutes(value) {
  if (typeof value === 'number' && Number.isFinite(value)) return value;
  if (typeof value !== 'string') return undefined;
  if (flexibleObj.isFlexible(value)) return flexibleObj.getValue(value);
  var n = Number(value);
  return Number.isNaN(n) ? undefined : n;
}

/**
 * cacheItem._extend.resource 形如 `{ [form_id]: [{ relation_id, form_id, like_status, metadata, children }] }`。
 * 这里扁平化为符合协议的 resources[] 数组；id=0 的「无资源」占位行**保留**（与 info2 业务等价；协议 `relation_id=0` 合法）。
 *
 * 顶层 resources[].capacity 与 info2 `checkResourcesFormat` 一致：Σ capacity[].value（不含 quantity）。
 */
function flattenResources(cacheItem) {
  var _cacheItem$_extend;
  var resourceMap = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.resource) || {};
  var topLevelCapacity = getSumCapacity(cacheItem, false);
  var result = [];
  Object.values(resourceMap).forEach(function (arr) {
    if (!Array.isArray(arr)) return;
    arr.forEach(function (r) {
      var item = {
        form_id: r === null || r === void 0 ? void 0 : r.form_id,
        relation_type: (r === null || r === void 0 ? void 0 : r.relation_type) || 'form',
        relation_id: r === null || r === void 0 ? void 0 : r.relation_id,
        capacity: topLevelCapacity
      };
      item.like_status = (r === null || r === void 0 ? void 0 : r.like_status) || 'common';
      if ((r === null || r === void 0 ? void 0 : r.metadata) !== undefined) {
        // 协议允许 metadata 自由透传；为了与 info2 行为等价，把 form_name / resource_name / combined_resource 一并保留。
        item.metadata = _objectSpread({}, r.metadata);
      }
      if ((r === null || r === void 0 ? void 0 : r.children) !== undefined) item.children = r.children;
      result.push(item);
    });
  });
  return result;
}

/**
 * 从 cacheItem 中派生 metadata.resource_select_type；优先级：
 *   1. cacheItem._data.resources[0].select_type.type
 *   2. cacheItem.product_resource.resources[0].select_type.type
 *   3. 默认 undefined（由 OS / 后端兜底）。
 */
function deriveResourceSelectType(cacheItem) {
  var _cacheItem$_data, _cacheItem$product_re;
  var localFirst = cacheItem === null || cacheItem === void 0 || (_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data.resources) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data[0]) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data.select_type) === null || _cacheItem$_data === void 0 ? void 0 : _cacheItem$_data.type;
  if (localFirst) return localFirst;
  var productFirst = cacheItem === null || cacheItem === void 0 || (_cacheItem$product_re = cacheItem.product_resource) === null || _cacheItem$product_re === void 0 || (_cacheItem$product_re = _cacheItem$product_re.resources) === null || _cacheItem$product_re === void 0 || (_cacheItem$product_re = _cacheItem$product_re[0]) === null || _cacheItem$product_re === void 0 || (_cacheItem$product_re = _cacheItem$product_re.select_type) === null || _cacheItem$product_re === void 0 ? void 0 : _cacheItem$product_re.type;
  if (productFirst) return productFirst;
  return undefined;
}

/**
 * 主入口。
 */
export function cacheItemToBookingInput(cacheItem, options) {
  var _ext$other, _options$bookingConfi;
  if (!cacheItem) return {
    metadata: {
      holder_id: null
    }
  };
  var ext = cacheItem._extend || {};
  var isMultiDay = isMultiDayProduct(cacheItem) || ext.is_all === 1 || ext.sub_type === 'days';
  var isSession = isSessionProduct(cacheItem);
  var result = {};

  // ──── 日期 / 时间 ───────────────────────────────────────────────
  if (isSession && ext !== null && ext !== void 0 && (_ext$other = ext.other) !== null && _ext$other !== void 0 && _ext$other.session) {
    var session = ext.other.session;
    // 优先 _extend 上已按顶部 date 对齐过的起止（catalog cartDetailValue.session → applySessionTimesToExtend）
    result.start_date = safeFormat(ext.start_date || ext.startDate || session.start_at, 'YYYY-MM-DD');
    result.start_time = normalizeTimeString(ext.start_time) || normalizeTimeString(session.start_time) || safeFormat(session.start_at, 'HH:mm');
    result.end_date = safeFormat(ext.end_date || ext.endDate || session.end_at, 'YYYY-MM-DD');
    result.end_time = normalizeTimeString(ext.end_time) || normalizeTimeString(session.end_time) || safeFormat(session.end_at, 'HH:mm');
  } else {
    result.start_date = safeFormat(ext.start_date || ext.startDate, 'YYYY-MM-DD');
    result.start_time = normalizeTimeString(ext.start_time) || safeFormat(ext.startDate, 'HH:mm');
    result.end_date = safeFormat(ext.end_date || ext.endDate, 'YYYY-MM-DD');
    result.end_time = normalizeTimeString(ext.end_time) || safeFormat(ext.endDate, 'HH:mm');
  }

  // ──── duration / sub_type / is_all ──────────────────────────────
  if (isMultiDay) {
    result.is_all = 1;
    result.sub_type = 'days';
    result.duration = Number(ext.duration) || getDays(cacheItem, 'days');
    // 全天选择日期 = 起始日
    if (result.start_date) result.select_date = result.start_date;
    // 跨日结束时刻与开始一致（如 11:24），避免 endDate 仅日期落为 00:00
    if (result.start_time && (!result.end_time || result.end_time === '00:00')) {
      result.end_time = result.start_time;
    }
  } else {
    result.is_all = 0;
    result.sub_type = ext.sub_type || 'minutes';
    var duration = resolveDurationMinutes(ext.duration);
    if (duration !== undefined) result.duration = duration;
  }

  // ──── number（人数/容量占用） ───────────────────────────────────
  result.number = getSumCapacity(cacheItem, true);

  // ──── resources ─────────────────────────────────────────────────
  result.resources = flattenResources(cacheItem);

  // ──── holder / relation_forms / like_status / schedule_event_id  ──
  if (ext.holder !== undefined) result.holder = ext.holder;
  if (Array.isArray(ext.relation_forms)) result.relation_forms = ext.relation_forms;
  // 与 info2 booking/components/footer/utils formatBooking 一致：默认 common
  result.like_status = ext.like_status || 'common';
  if (cacheItem.schedule_event_id !== undefined) {
    result.schedule_event_id = cacheItem.schedule_event_id;
  }

  // ──── metadata（严格白名单） ────────────────────────────────────
  var metadata = {
    holder_id: null
  };
  if (ext.holder_id !== undefined && ext.holder_id !== null) {
    metadata.holder_id = ext.holder_id;
  }
  if (ext.collect_pax !== undefined) metadata.collect_pax = ext.collect_pax;
  // 与 info2 formatMetaData 一致：优先写入完整人数维度数组，供编辑回显 / 详情回灌。
  var extendCapacity = normalizeExtendCapacityForMetadata(ext.capacity);
  if (extendCapacity) {
    metadata.capacity = extendCapacity;
  } else if (ext.capacity_snapshot !== undefined) {
    metadata.capacity = ext.capacity_snapshot;
  }
  var selectType = deriveResourceSelectType(cacheItem) || (options === null || options === void 0 || (_options$bookingConfi = options.bookingConfig) === null || _options$bookingConfi === void 0 ? void 0 : _options$bookingConfi.resource_select_type);
  if (selectType) metadata.resource_select_type = selectType;
  // unique_identification_number 不在这里生成（由 OS createLinkedProductAndBooking 统一写）。
  result.metadata = metadata;

  // ──── booking root 占位字段（与 TEMP_ORDER_FIELDS_SUMMARY 一致） ──
  result.schedule_id = 0;
  result.relation_id = 0;
  result.form_id = 0;
  result.relation_type = '';
  return result;
}