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); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
import { getCustomer } from "../components/appointmentBooking/utils";

/** ProductCard Time 组件所需的 holder 展示字段 */

/**
 * holder_config 是否已开启。
 * status 非 enable（如 disable）时，required、resource_id 视为脏数据，不参与校验与展示。
 */
export var isHolderConfigEnabled = function isHolderConfigEnabled(holderConfig) {
  return (holderConfig === null || holderConfig === void 0 ? void 0 : holderConfig.status) === 'enable';
};
var toHolderRecordId = function toHolderRecordId(value) {
  if (value == null || value === '') return undefined;
  var id = Number(value);
  return Number.isNaN(id) ? undefined : id;
};

/**
 * 从 _origin.holder 解析 form_record_id。
 * form_record 可能是 number、number[]；不能假定一定是数组下标 [0]。
 */
var resolveOriginHolderId = function resolveOriginHolderId(holder) {
  var formRecord = holder === null || holder === void 0 ? void 0 : holder.form_record;
  if (Array.isArray(formRecord)) {
    var _iterator = _createForOfIteratorHelper(formRecord),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var _value = _step.value;
        var id = toHolderRecordId(_value);
        if (id != null) return id;
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
  } else {
    var _id = toHolderRecordId(formRecord);
    if (_id != null) return _id;
  }
  return toHolderRecordId(holder === null || holder === void 0 ? void 0 : holder.form_record_id);
};

/**
 * 从购物车行解析当前选中的 holder form_record_id。
 *
 * venueBooking：以 _origin.holder 为准（SDK 会原地更新 form_record）；
 * 顶层 item.holder_id 可能是上一轮 UI 注入或 SDK 回灌的滞后值，不能优先于 _origin.holder。
 */
export var resolveCartItemHolderId = function resolveCartItemHolderId(item) {
  var _item$_origin;
  var originHolder = item === null || item === void 0 || (_item$_origin = item._origin) === null || _item$_origin === void 0 ? void 0 : _item$_origin.holder;
  if (originHolder && _typeof(originHolder) === 'object') {
    return resolveOriginHolderId(originHolder);
  }
  return toHolderRecordId(item === null || item === void 0 ? void 0 : item.holder_id);
};
var getCurrentCustomerId = function getCurrentCustomerId(utils) {
  var _getCustomer;
  return (_getCustomer = getCustomer(utils)) === null || _getCustomer === void 0 ? void 0 : _getCustomer.id;
};
var createCartHolderOption = function createCartHolderOption(holder, customerId) {
  return {
    key: holder === null || holder === void 0 ? void 0 : holder.form_record_id,
    id: holder === null || holder === void 0 ? void 0 : holder.form_record_id,
    label: holder === null || holder === void 0 ? void 0 : holder.main_field,
    name: holder === null || holder === void 0 ? void 0 : holder.main_field,
    username: holder === null || holder === void 0 ? void 0 : holder.main_field,
    type: 'holder',
    _origin: _objectSpread(_objectSpread({}, holder), {}, {
      customer_id: customerId
    })
  };
};

/**
 * 构建 ProductCard Holder 组件使用的单条 holder 数据。
 * 输出字段需要与购物车 ProductCard 消费格式保持一致。
 */
export var buildCartHolderOption = function buildCartHolderOption(holder, utils) {
  if (!holder) return {};
  return createCartHolderOption(holder, getCurrentCustomerId(utils));
};
var buildCartHolderOptions = function buildCartHolderOptions(records, utils) {
  var customerId = getCurrentCustomerId(utils);
  return records.map(function (record) {
    return createCartHolderOption(record, customerId);
  });
};
var getCartHolderTitle = function getCartHolderTitle(records, holderId) {
  var _records$find;
  if (!holderId) return '';
  return (_records$find = records.find(function (record) {
    return Number(record === null || record === void 0 ? void 0 : record.form_record_id) === holderId;
  })) === null || _records$find === void 0 ? void 0 : _records$find.main_field;
};

/**
 * 根据 holderMap 与购物车行数据，构建 ProductCard 所需的 holder 展示字段。
 * 供 appointmentBooking、venueBooking 等购物车场景复用。
 */
export var buildCartHolderParams = function buildCartHolderParams(_ref) {
  var _formData$form;
  var item = _ref.item,
    _ref$holderConfig = _ref.holderConfig,
    holderConfig = _ref$holderConfig === void 0 ? {} : _ref$holderConfig,
    formData = _ref.formData,
    translation = _ref.translation,
    _ref$enabled = _ref.enabled,
    enabled = _ref$enabled === void 0 ? true : _ref$enabled,
    utils = _ref.utils;
  if (!enabled || !isHolderConfigEnabled(holderConfig)) {
    return {
      isShowChangeHolder: false,
      holders: []
    };
  }
  var records = (formData === null || formData === void 0 ? void 0 : formData.records) || [];
  var holderId = resolveCartItemHolderId(item);
  return {
    holder_id: holderId,
    isErrorHolder: !!(!holderId && holderConfig !== null && holderConfig !== void 0 && holderConfig.required),
    isShowChangeHolder: true,
    addHolderButtonText: translation(formData === null || formData === void 0 || (_formData$form = formData.form) === null || _formData$form === void 0 || (_formData$form = _formData$form.form) === null || _formData$form === void 0 || (_formData$form = _formData$form.setting) === null || _formData$form === void 0 ? void 0 : _formData$form.title),
    holder_title: getCartHolderTitle(records, holderId),
    holders: buildCartHolderOptions(records, utils)
  };
};

/**
 * 从 appointmentBooking 购物车行读取 holder_config
 */
export var getAppointmentCartHolderConfig = function getAppointmentCartHolderConfig(item) {
  var _item$_productInit;
  return (item === null || item === void 0 || (_item$_productInit = item._productInit) === null || _item$_productInit === void 0 ? void 0 : _item$_productInit.holder_config) || {};
};

/**
 * 从 venueBooking 购物车行读取 holder_config
 */
export var getVenueCartHolderConfig = function getVenueCartHolderConfig(item) {
  var _item$_origin2;
  return (item === null || item === void 0 || (_item$_origin2 = item._origin) === null || _item$_origin2 === void 0 || (_item$_origin2 = _item$_origin2.product) === null || _item$_origin2 === void 0 ? void 0 : _item$_origin2.holder_config) || {};
};
/**
 * 校验购物车中 holder_config.required 的行是否已选择 holder。
 */
export var validateRequiredCartHolders = function validateRequiredCartHolders(_ref2) {
  var _ref2$items = _ref2.items,
    items = _ref2$items === void 0 ? [] : _ref2$items,
    _ref2$getHolderConfig = _ref2.getHolderConfig,
    getHolderConfig = _ref2$getHolderConfig === void 0 ? getVenueCartHolderConfig : _ref2$getHolderConfig;
  console.log(items, 'items1111');
  var invalidItems = items.filter(function (item) {
    var holderConfig = getHolderConfig(item);
    if (!isHolderConfigEnabled(holderConfig) || !(holderConfig !== null && holderConfig !== void 0 && holderConfig.required)) {
      return false;
    }
    return !resolveCartItemHolderId(item);
  });
  return {
    hasError: invalidItems.length > 0,
    invalidItems: invalidItems
  };
};
/**
 * 从 holderMap 解析 minors 表单关联的 sku 关系表单 ID（form_to_form 隐藏字段的 linkedTable）。
 */
export var getSkuRelationFormId = function getSkuRelationFormId(holderMap, formId) {
  var _formData$form2, _formData$form3, _detail$setting;
  if (!formId) return 0;
  var formData = holderMap === null || holderMap === void 0 ? void 0 : holderMap[formId];
  if ((formData === null || formData === void 0 || (_formData$form2 = formData.form) === null || _formData$form2 === void 0 || (_formData$form2 = _formData$form2.form) === null || _formData$form2 === void 0 ? void 0 : _formData$form2.form_type) !== 'minors') return 0;
  var detail = formData === null || formData === void 0 || (_formData$form3 = formData.form) === null || _formData$form3 === void 0 || (_formData$form3 = _formData$form3.field) === null || _formData$form3 === void 0 ? void 0 : _formData$form3.find(function (item) {
    return (item === null || item === void 0 ? void 0 : item.filed_type) === 'form_to_form' && (item === null || item === void 0 ? void 0 : item.status) === 'hide';
  });
  return (detail === null || detail === void 0 || (_detail$setting = detail.setting) === null || _detail$setting === void 0 ? void 0 : _detail$setting.linkedTable) || 0;
};

/**
 * 从 form_to_form_value 中取最新创建的 form_record_id。
 */
export var getSkuRelationFormRecordId = function getSkuRelationFormRecordId(res) {
  var _res$values;
  var formToFormValue = res === null || res === void 0 || (_res$values = res.values) === null || _res$values === void 0 || (_res$values = _res$values.form_to_form_value) === null || _res$values === void 0 ? void 0 : _res$values[0];
  var formDataValue = (formToFormValue === null || formToFormValue === void 0 ? void 0 : formToFormValue.form_data_value) || [];
  return formDataValue[formDataValue.length - 1];
};

/**
 * 处理购物车添加 holder 表单提交成功后的公共逻辑。
 * - minors 关联表单：刷新 holder 列表，取 form_to_form_value 中的 record id
 * - 普通表单：appendFormRecord 并直接使用 form_record_id
 */
export var handleCartHolderFormSuccess = function handleCartHolderFormSuccess(_ref3) {
  var _res$values2, _res$values3, _res$values4;
  var res = _ref3.res,
    formId = _ref3.formId,
    skuRelationFormId = _ref3.skuRelationFormId,
    utils = _ref3.utils,
    module = _ref3.module;
  var formRecordId = res === null || res === void 0 || (_res$values2 = res.values) === null || _res$values2 === void 0 ? void 0 : _res$values2.form_record_id;
  var resolvedFormId = res === null || res === void 0 || (_res$values3 = res.values) === null || _res$values3 === void 0 ? void 0 : _res$values3.form_id;
  if (formId && skuRelationFormId) {
    var _module$refreshAllHol;
    var customer = getCustomer(utils);
    module === null || module === void 0 || (_module$refreshAllHol = module.refreshAllHolderFormRecords) === null || _module$refreshAllHol === void 0 || _module$refreshAllHol.call(module, {
      customer_id: customer === null || customer === void 0 ? void 0 : customer.id
    });
    formRecordId = getSkuRelationFormRecordId(res);
    resolvedFormId = formId;
  } else if (formId) {
    var _module$appendFormRec;
    module === null || module === void 0 || (_module$appendFormRec = module.appendFormRecord) === null || _module$appendFormRec === void 0 || _module$appendFormRec.call(module, {
      record: res === null || res === void 0 ? void 0 : res.values
    });
  }
  return {
    formRecordId: formRecordId,
    mainField: res === null || res === void 0 || (_res$values4 = res.values) === null || _res$values4 === void 0 ? void 0 : _res$values4.main_field,
    formId: resolvedFormId
  };
};