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 _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 _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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
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 { StrategyEngine } from "../../engine";
import { ItemRuleAdapter } from "./adapter";
import { ITEM_RULE_ACTION_TYPES } from "./type";

/**
 * ItemRule 评估器
 *
 * 组合 StrategyEngine + ItemRuleAdapter，提供面向业务的高层 API。
 * 支持批量评估多条 item_rule 策略配置，聚合数量校验和预填购物车结果。
 */
export var ItemRuleEvaluator = /*#__PURE__*/function () {
  function ItemRuleEvaluator() {
    _classCallCheck(this, ItemRuleEvaluator);
    _defineProperty(this, "engine", void 0);
    _defineProperty(this, "adapter", void 0);
    _defineProperty(this, "strategyConfigs", []);
    this.engine = new StrategyEngine({
      debug: false,
      enableTrace: false
    });
    this.adapter = new ItemRuleAdapter();
  }

  /**
   * 设置策略配置列表
   * 自动过滤 metadata.type === 'item_rule' 的配置
   */
  _createClass(ItemRuleEvaluator, [{
    key: "setStrategyConfigs",
    value: function setStrategyConfigs(configs) {
      this.strategyConfigs = configs.filter(function (c) {
        return c.metadata.type === 'item_rule';
      });
    }
  }, {
    key: "getStrategyConfigs",
    value: function getStrategyConfigs() {
      return this.strategyConfigs;
    }

    /**
     * 完整评估：数量校验 + 预填购物车
     */
  }, {
    key: "evaluate",
    value: function evaluate(businessData) {
      var configs = businessData.strategyConfigs ? businessData.strategyConfigs.filter(function (c) {
        return c.metadata.type === 'item_rule';
      }) : this.strategyConfigs;
      var allQuantityChecks = [];
      var allPrefillItems = [];
      var rawResults = [];
      var context = this.adapter.prepareContext(businessData);
      var _iterator = _createForOfIteratorHelper(configs),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var config = _step.value;
          var evalResult = this.engine.evaluate(config, context);
          rawResults.push(evalResult);
          var _this$adapter$transfo = this.adapter.transformResult(evalResult, businessData),
            quantityChecks = _this$adapter$transfo.quantityChecks,
            prefillItems = _this$adapter$transfo.prefillItems;
          allQuantityChecks.push.apply(allQuantityChecks, _toConsumableArray(quantityChecks));
          allPrefillItems.push.apply(allPrefillItems, _toConsumableArray(prefillItems));
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      var failedChecks = allQuantityChecks.filter(function (c) {
        return !c.passed;
      });
      return {
        quantityChecks: allQuantityChecks,
        prefillItems: allPrefillItems,
        allPassed: failedChecks.length === 0,
        failedChecks: failedChecks,
        rawResults: rawResults
      };
    }

    /**
     * 获取当前配置中各商品的数量限制
     *
     * 不做购物车校验，仅从策略配置中提取 QUANTITY_CHECK 规则的
     * min / max / exact / mustInclude 限制值。
     * 会评估条件是否满足、根据 scope + submissionIndex 过滤。
     */
  }, {
    key: "getQuantityLimits",
    value: function getQuantityLimits(businessData) {
      var configs = businessData.strategyConfigs ? businessData.strategyConfigs.filter(function (c) {
        return c.metadata.type === 'item_rule';
      }) : this.strategyConfigs;
      var results = [];
      var context = this.adapter.prepareContext(businessData);
      var _iterator2 = _createForOfIteratorHelper(configs),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var config = _step2.value;
          var evalResult = this.engine.evaluate(config, context);
          if (!evalResult.applicable) continue;
          var _iterator3 = _createForOfIteratorHelper(evalResult.matchedActions),
            _step3;
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var action = _step3.value;
              if (action.type !== ITEM_RULE_ACTION_TYPES.QUANTITY_CHECK) continue;
              var limit = this.adapter.extractQuantityLimits(action, businessData);
              if (limit) {
                results.push(limit);
              }
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      return results;
    }

    /**
     * 便捷方法：仅做数量校验，返回是否全部通过及失败详情
     */
  }, {
    key: "validateCart",
    value: function validateCart(businessData) {
      var result = this.evaluate(businessData);
      return {
        passed: result.allPassed,
        failures: result.failedChecks
      };
    }

    /**
     * 便捷方法：仅获取需要预填到购物车的商品
     */
  }, {
    key: "getPrefillItems",
    value: function getPrefillItems(businessData) {
      var result = this.evaluate(businessData);
      return result.prefillItems;
    }
  }]);
  return ItemRuleEvaluator;
}();