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); }
import { ItemRuleEvaluator } from "./evaluator";
import { ITEM_RULE_ACTION_TYPES } from "./type";
// ============================================
// 示例 1：每人至少一份小料 (Minimum Per Person)
// ============================================

/**
 * 场景：火锅店扫码点餐，要求小料数量 >= 成人人数，自动添加到购物车
 *
 * WHEN: Always active
 * THEN:
 *   - Quantity Check: 小料最少数量 = Adult Pax
 *   - Prefill Cart: 自动添加小料 x Adult Pax
 */
export var MIN_CONDIMENT_PER_PERSON_STRATEGY = {
  metadata: {
    id: 'RULE_MIN_CONDIMENT_PER_PERSON',
    name: {
      'zh-CN': '每人至少一份小料',
      en: 'Min 1 Condiment per person'
    },
    type: 'item_rule',
    description: {
      'zh-CN': '火锅小料数量不少于成人人数，自动添加',
      en: 'Condiment count must be at least adult pax, auto-added to cart'
    }
  },
  conditions: {
    operator: 'and',
    rules: [],
    actionIds: ['quantity_check_condiment', 'prefill_condiment']
  },
  actions: [{
    id: 'quantity_check_condiment',
    type: ITEM_RULE_ACTION_TYPES.QUANTITY_CHECK,
    value: null,
    target: 'cart',
    priority: 10,
    config: {
      targetType: 'product',
      targets: [{
        product_id: 10001
      }, {
        product_id: 10002
      }],
      quantityRules: [{
        comparison: 'minimum',
        source: 'total_pax'
      }],
      scope: 'first_submission_only',
      validationMessage: {
        'zh-CN': '小料至少需要 {min} 份（每位成人一份）',
        en: 'Condiment requires at least {min} items (one per adult)'
      }
    }
  }, {
    id: 'prefill_condiment',
    type: ITEM_RULE_ACTION_TYPES.PREFILL_CART,
    value: null,
    target: 'cart',
    priority: 5,
    config: {
      products: [{
        product_id: 10001,
        quantityFrom: 'total_pax'
      }]
    }
  }]
};

// ============================================
// 示例 2：每桌限量3份包子 (Maximum Per Table)
// ============================================

/**
 * 场景：包子限量供应，每桌最多3份（含加单累计），肉包和菜包合计
 *
 * WHEN: Always active
 * THEN:
 *   - Quantity Check: 肉包 + 菜包 合计 <= 3，scope=cumulative
 */
export var MAX_BUNS_PER_TABLE_STRATEGY = {
  metadata: {
    id: 'RULE_MAX_BUNS_PER_TABLE',
    name: {
      'zh-CN': '每桌限量供应3份包子',
      en: '3 Buns limit per table'
    },
    type: 'item_rule',
    description: {
      'zh-CN': '肉包和菜包合计每桌不超过3份，含加单累计',
      en: 'Max 3 buns per table (pork + veggie combined, cumulative)'
    }
  },
  conditions: {
    operator: 'and',
    rules: [],
    actionIds: ['quantity_check_buns']
  },
  actions: [{
    id: 'quantity_check_buns',
    type: ITEM_RULE_ACTION_TYPES.QUANTITY_CHECK,
    value: null,
    target: 'cart',
    priority: 10,
    config: {
      targetType: 'product',
      targets: [{
        product_id: 20001
      }, {
        product_id: 20002
      }],
      quantityRules: [{
        comparison: 'maximum',
        source: 'fixed',
        value: 3
      }],
      scope: 'cumulative',
      validationMessage: {
        'zh-CN': '包子每桌限量 {max} 份（含加单累计）',
        en: 'Buns are limited to {max} per table (cumulative)'
      }
    }
  }]
};

// ============================================
// 示例 3：锅底必选 (Must Include - Conditional)
// ============================================

/**
 * 场景：堂食必须选择一个锅底（按商品匹配），自动预填默认锅底
 *
 * WHEN: Service Type = Dine-in
 * THEN:
 *   - Quantity Check: 指定锅底商品精确1份
 *   - Prefill Cart: 自动添加默认锅底 x 1
 */
export var HOTPOT_BASE_REQUIRED_STRATEGY = {
  metadata: {
    id: 'RULE_HOTPOT_BASE_REQUIRED',
    name: {
      'zh-CN': '锅底必选',
      en: 'Hotpot base required'
    },
    type: 'item_rule',
    description: {
      'zh-CN': '堂食必须选择一个锅底',
      en: 'Hotpot base is mandatory for dine-in'
    }
  },
  conditions: {
    operator: 'and',
    rules: [{
      type: 'operator',
      dimension: 'context',
      field: 'serviceType',
      operator: '=',
      value: 'dine-in'
    }],
    actionIds: ['quantity_check_base', 'prefill_base']
  },
  actions: [{
    id: 'quantity_check_base',
    type: ITEM_RULE_ACTION_TYPES.QUANTITY_CHECK,
    value: null,
    target: 'cart',
    priority: 10,
    config: {
      targetType: 'product',
      targets: [{
        product_id: 30001
      }],
      quantityRules: [{
        comparison: 'exact',
        source: 'fixed',
        value: 1
      }],
      scope: 'first_submission_only',
      validationMessage: {
        'zh-CN': '请选择 {exact} 个锅底',
        en: 'Please select exactly {exact} hotpot base'
      }
    }
  }, {
    id: 'prefill_base',
    type: ITEM_RULE_ACTION_TYPES.PREFILL_CART,
    value: null,
    target: 'cart',
    priority: 5,
    config: {
      products: [{
        product_id: 30001,
        quantityFrom: 'fixed',
        quantity: 1
      }]
    }
  }]
};

// ============================================
// 示例 4：锅底四选一（Multi-target OR 组至少 1 份）
// ============================================

/**
 * 场景：4 款锅底里任选至少 1 款，不自动预填，不限制多选上限
 *
 * WHEN: Always active
 * THEN:
 *   - Quantity Check: 4 个锅底商品合计数量 >= 1 （OR 组语义）
 *
 * 说明：
 *   - targets 里放多个 product_id 时，ItemRuleAdapter 会把它们视为 OR 组，
 *     仅校验「合计数量」，不会要求每款各自满足 min。
 *   - ScanOrder 工具层 buildQuantityLimitIndex 会跳过多目标规则的
 *     单品索引，避免 UI 把组级 min 误当作每张商品卡的减号下限，
 *     锁死用户切换锅底的操作。
 */
export var HOTPOT_BASE_PICK_ONE_STRATEGY = {
  metadata: {
    id: 'RULE_HOTPOT_BASE_PICK_ONE',
    name: {
      'zh-CN': '锅底必选（四选一）',
      en: 'Hotpot base required (pick any)'
    },
    type: 'item_rule',
    description: {
      'zh-CN': '4 款锅底任选至少 1 份',
      en: 'Pick at least 1 hotpot base from the available options'
    }
  },
  conditions: {
    operator: 'and',
    rules: [],
    actionIds: ['quantity_check_hotpot_base_group']
  },
  actions: [{
    id: 'quantity_check_hotpot_base_group',
    type: ITEM_RULE_ACTION_TYPES.QUANTITY_CHECK,
    value: null,
    target: 'cart',
    priority: 10,
    config: {
      targetType: 'product',
      targets: [{
        product_id: 30001
      }, {
        product_id: 30002
      }, {
        product_id: 30003
      }, {
        product_id: 30004
      }],
      quantityRules: [{
        comparison: 'minimum',
        source: 'fixed',
        value: 1
      }],
      scope: 'first_submission_only',
      validationMessage: {
        'zh-CN': '请至少选择 {min} 款锅底',
        en: 'Please select at least {min} hotpot base'
      }
    }
  }]
};

// ============================================
// 示例 5：ItemRuleEvaluator 用法（简洁调用 + 完整 Demo）
// ============================================

/**
 * ItemRuleEvaluator 简洁调用示例
 *
 * 覆盖方法：
 * - setStrategyConfigs
 * - getStrategyConfigs
 * - evaluate
 * - getQuantityLimits
 * - validateCart
 * - getPrefillItems
 */
export function quickUseItemRuleEvaluator() {
  var evaluator = new ItemRuleEvaluator();
  evaluator.setStrategyConfigs([MIN_CONDIMENT_PER_PERSON_STRATEGY, MAX_BUNS_PER_TABLE_STRATEGY, HOTPOT_BASE_REQUIRED_STRATEGY]);
  var businessData = {
    pax: {
      total: 3,
      adult: 3,
      child: 0
    },
    serviceType: 'dine-in',
    cartItems: [{
      product_id: 10001,
      quantity: 1
    }, {
      product_id: 20001,
      quantity: 2
    }, {
      product_id: 20002,
      quantity: 1
    }],
    historicalItems: [{
      product_id: 20001,
      quantity: 1
    }],
    submissionIndex: 0
  };
  return {
    configCount: evaluator.getStrategyConfigs().length,
    evaluation: evaluator.evaluate(businessData),
    quantityLimits: evaluator.getQuantityLimits(businessData),
    validation: evaluator.validateCart(businessData),
    prefillItems: evaluator.getPrefillItems(businessData)
  };
}

/**
 * ItemRuleEvaluator 完整可运行 Demo
 *
 * 说明：
 * 1) 首次提交：触发 first_submission_only + cumulative + 条件规则
 * 2) 追加提交：演示 first_submission_only 不再触发
 * 3) 覆盖 strategyConfigs 临时传入：演示按需仅评估部分规则
 */
export function runItemRuleEvaluatorDemo() {
  var evaluator = new ItemRuleEvaluator();
  evaluator.setStrategyConfigs([MIN_CONDIMENT_PER_PERSON_STRATEGY
  // MAX_BUNS_PER_TABLE_STRATEGY,
  // HOTPOT_BASE_REQUIRED_STRATEGY,
  ]);
  var firstSubmissionData = {
    pax: {
      total: 4,
      adult: 3,
      child: 1
    },
    serviceType: 'dine-in',
    submissionIndex: 0,
    cartItems: [{
      product_id: 10001,
      quantity: 3
    }
    // { product_id: 20001, quantity: 2 },
    // { product_id: 20002, quantity: 1 },
    ],
    historicalItems: [{
      product_id: 20001,
      quantity: 1
    }]
  };
  var additionalSubmissionData = _objectSpread(_objectSpread({}, firstSubmissionData), {}, {
    submissionIndex: 1
  });
  var firstEvaluation = evaluator.evaluate(firstSubmissionData);
  var additionalEvaluation = evaluator.evaluate(additionalSubmissionData);
  var quantityLimits = evaluator.getQuantityLimits(firstSubmissionData);
  var validateResult = evaluator.validateCart(firstSubmissionData);
  var prefillItems = evaluator.getPrefillItems(firstSubmissionData);

  // 按需覆盖策略：仅评估“锅底必选”规则
  var baseOnlyEvaluation = evaluator.evaluate(_objectSpread(_objectSpread({}, firstSubmissionData), {}, {
    strategyConfigs: [HOTPOT_BASE_REQUIRED_STRATEGY]
  }));
  return {
    // configuredRuleIds: evaluator
    //   .getStrategyConfigs()
    //   .map((config) => config.metadata.id),
    firstEvaluation: firstEvaluation,
    // additionalEvaluation,
    // quantityLimits,
    validateResult: validateResult,
    prefillItems: prefillItems
    // baseOnlyEvaluation,
  };
}