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; }
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 _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 "../../index";
import { processVouchers as _processVouchers, recalculateVouchers as _recalculateVouchers, getApplicableProductIds, getMainProductPrice, getBundleItemPrice, getProductQuantity, getBundleItemIsOriginalPrice } from "./utils";
import { locales } from "./locales";
import Decimal from 'decimal.js';
var defaultStrategyMetadataCustom = {
  maxDeductionAmount: 99999,
  maxUsagePerOrder: 0,
  allowCrossProduct: true,
  applicableProductLimit: 0,
  deductTaxAndFee: true
};

/**
 * Wallet Pass 评估器
 * 用于评估哪些 voucher 可以在当前订单中使用
 */
export var WalletPassEvaluator = /*#__PURE__*/function () {
  function WalletPassEvaluator() {
    _classCallCheck(this, WalletPassEvaluator);
    _defineProperty(this, "engine", void 0);
    _defineProperty(this, "strategyConfigs", []);
    _defineProperty(this, "locale", 'en');
    this.engine = new StrategyEngine({
      debug: false,
      enableTrace: false
    });
  }
  _createClass(WalletPassEvaluator, [{
    key: "setStrategyConfigs",
    value: function setStrategyConfigs(strategyConfigs) {
      this.strategyConfigs = strategyConfigs;
    }
  }, {
    key: "getStrategyConfigs",
    value: function getStrategyConfigs() {
      return this.strategyConfigs;
    }
  }, {
    key: "setLocale",
    value: function setLocale(locale) {
      this.locale = locale;
    }
  }, {
    key: "getText",
    value: function getText(key) {
      var _locales$this$locale;
      return locales === null || locales === void 0 || (_locales$this$locale = locales[this.locale]) === null || _locales$this$locale === void 0 ? void 0 : _locales$this$locale[key];
    }

    /**
     * 搜索券的格式
     * @param input 输入
     * @returns 返回搜索券的格式
     */
  }, {
    key: "searchVoucherFormat",
    value: function searchVoucherFormat(input) {
      var results = this.evaluate(input);
      return results.map(function (item) {
        if (item.isApplicable) {
          var _item$strategyResult;
          return _objectSpread(_objectSpread({}, item.voucher), {}, {
            config: _objectSpread({}, item === null || item === void 0 || (_item$strategyResult = item.strategyResult) === null || _item$strategyResult === void 0 ? void 0 : _item$strategyResult.config.metadata.custom)
          });
        } else {
          var _item$strategyResult2;
          return _objectSpread(_objectSpread({}, item.voucher), {}, {
            config: _objectSpread({}, item === null || item === void 0 || (_item$strategyResult2 = item.strategyResult) === null || _item$strategyResult2 === void 0 ? void 0 : _item$strategyResult2.config.metadata.custom),
            _unified_available_status: 0,
            reason: item.reason,
            reasonCode: item.reasonCode
          });
        }
      });
    }

    /**
     * 评估可用的 vouchers
     */
  }, {
    key: "evaluate",
    value: function evaluate(input) {
      var orderTotalAmount = input.orderTotalAmount,
        products = input.products,
        vouchers = input.vouchers,
        strategyConfigs = input.strategyConfigs;

      // 提取订单中的商品ID
      var productIds = products.map(function (p) {
        return p.product_id;
      });
      var results = [];

      // 遍历每个 voucher 进行评估
      var _iterator = _createForOfIteratorHelper(vouchers),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var _strategy$metadata$cu, _strategy$metadata, _businessConfig$deduc;
          var voucher = _step.value;
          // 查找适用此 voucher 的策略配置
          var applicableStrategies = this.findApplicableStrategies(voucher, strategyConfigs || this.strategyConfigs);
          if (applicableStrategies.length === 0) {
            // 没有匹配的策略 默认可用
            results.push({
              voucher: voucher,
              isApplicable: true,
              canUseCount: 0,
              maxDeduction: 0,
              deductTaxAndFee: true,
              applicableProductIds: [],
              reason: '',
              reasonCode: '',
              strategyResult: {
                config: {
                  metadata: {
                    custom: _objectSpread({}, defaultStrategyMetadataCustom)
                  }
                }
              }
            });
            continue;
          }

          // 对每个策略进行评估（取第一个匹配的策略）
          var strategy = applicableStrategies[0];

          // 从 voucher 中获取适用商品ID
          var applicableProductIds = getApplicableProductIds(voucher);

          // 计算适用商品的总金额和数量
          var _this$calculateApplic = this.calculateApplicableProducts(products, applicableProductIds, (_strategy$metadata$cu = strategy === null || strategy === void 0 || (_strategy$metadata = strategy.metadata) === null || _strategy$metadata === void 0 || (_strategy$metadata = _strategy$metadata.custom) === null || _strategy$metadata === void 0 ? void 0 : _strategy$metadata.deductTaxAndFee) !== null && _strategy$metadata$cu !== void 0 ? _strategy$metadata$cu : true),
            applicableTotal = _this$calculateApplic.applicableTotal,
            applicableCount = _this$calculateApplic.applicableCount;

          // 准备运行时上下文
          var context = {
            entities: {
              voucher: voucher,
              products: products,
              order: {
                orderTotalAmount: orderTotalAmount,
                products: products
              }
            },
            attributes: {
              orderTotalAmount: orderTotalAmount,
              applicableProductTotalAmount: applicableTotal,
              applicableProductCount: applicableCount,
              voucherProductId: voucher.product_id,
              productIds: productIds
            },
            metadata: {
              timestamp: Date.now()
            }
          };

          // 执行策略评估
          var evaluationResult = this.engine.evaluate(strategy, context);

          // 从策略配置中获取业务配置
          var businessConfig = strategy.metadata.custom || {};
          var maxDeduction = businessConfig.maxDeductionAmount || 0;
          var canUseCount = businessConfig.maxUsagePerOrder || 0;
          var deductTaxAndFee = (_businessConfig$deduc = businessConfig.deductTaxAndFee) !== null && _businessConfig$deduc !== void 0 ? _businessConfig$deduc : true;
          if (evaluationResult.applicable) {
            results.push({
              voucher: voucher,
              isApplicable: true,
              canUseCount: canUseCount,
              maxDeduction: maxDeduction,
              deductTaxAndFee: deductTaxAndFee,
              applicableProductIds: applicableProductIds || [],
              strategyResult: evaluationResult
            });
          } else {
            // 根据策略评估结果的 code 映射到 locales 中的原因
            var reasonCode = 'not_meet_the_required_conditions'; // 默认原因

            // 根据策略引擎返回的 code 映射到本地化的 reasonCode
            if (evaluationResult.code) {
              // 可以根据具体的 code 映射到不同的原因
              // 例如：如果是金额不足、使用次数限制等
              var codeMapping = {
                INSUFFICIENT_AMOUNT: 'not_meet_the_required_conditions',
                USAGE_LIMIT_EXCEEDED: 'usage_limit_reached',
                CHANNEL_NOT_ALLOWED: 'not_available_for_this_channel',
                ORDER_TYPE_NOT_ALLOWED: 'not_valid_for_this_order_type',
                DEDUCTION_LIMIT_EXCEEDED: 'exceeds_the_maximum_deduction_limit'
              };
              reasonCode = codeMapping[evaluationResult.code] || 'not_meet_the_required_conditions';
            }
            results.push({
              voucher: voucher,
              isApplicable: false,
              canUseCount: 0,
              maxDeduction: 0,
              deductTaxAndFee: false,
              applicableProductIds: [],
              reason: this.getText(reasonCode),
              reasonCode: reasonCode,
              strategyResult: evaluationResult
            });
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return results;
    }

    /** 检查代金券/折扣卡是否可用 并返回config */
  }, {
    key: "checkVoucherAvailability",
    value: function checkVoucherAvailability(input) {
      var _results$, _results$2;
      var orderTotalAmount = input.orderTotalAmount,
        products = input.products,
        vouchers = input.vouchers;
      var results = this.evaluate(input);
      var isAvailable = ((_results$ = results[0]) === null || _results$ === void 0 ? void 0 : _results$.isApplicable) || false;
      return {
        isAvailable: isAvailable,
        config: _objectSpread({}, (_results$2 = results[0]) === null || _results$2 === void 0 || (_results$2 = _results$2.strategyResult) === null || _results$2 === void 0 || (_results$2 = _results$2.config) === null || _results$2 === void 0 || (_results$2 = _results$2.metadata) === null || _results$2 === void 0 ? void 0 : _results$2.custom)
      };
    }

    /**
     * 获取推荐券
     * @param input 输入
     * @returns 返回推荐券列表
     */
  }, {
    key: "getRecommendedVouchers",
    value: function getRecommendedVouchers(input) {
      var orderTotalAmount = input.orderTotalAmount,
        products = input.products,
        vouchers = input.vouchers;
      // 基于后端返回的状态不可用券
      var noApplicableVoucher = [];
      // 基于后端返回的状态可用券
      var applicableVoucher = [];
      vouchers.forEach(function (voucher) {
        if (voucher.unified_available_status === 1) {
          applicableVoucher.push(voucher);
        } else {
          noApplicableVoucher.push(voucher);
        }
      });
      var results = this.evaluate(_objectSpread(_objectSpread({}, input), {}, {
        vouchers: applicableVoucher
      }));
      var newVouchers = [];
      results.forEach(function (item) {
        if (item.isApplicable) {
          var _item$strategyResult3;
          newVouchers.push(_objectSpread(_objectSpread({}, item.voucher), {}, {
            config: _objectSpread(_objectSpread({}, defaultStrategyMetadataCustom), (item === null || item === void 0 || (_item$strategyResult3 = item.strategyResult) === null || _item$strategyResult3 === void 0 || (_item$strategyResult3 = _item$strategyResult3.config) === null || _item$strategyResult3 === void 0 || (_item$strategyResult3 = _item$strategyResult3.metadata) === null || _item$strategyResult3 === void 0 ? void 0 : _item$strategyResult3.custom) || {})
          }));
        } else {
          // 不可用的券，添加原因信息
          noApplicableVoucher.push(_objectSpread(_objectSpread({}, item.voucher), {}, {
            _unified_available_status: 0,
            reason: item.reason,
            reasonCode: item.reasonCode
          }));
        }
      });
      var _this$processVouchers = this.processVouchers(newVouchers, orderTotalAmount, products),
        recommended = _this$processVouchers.recommended,
        transformList = _this$processVouchers.transformList;
      var recommendedAmount = recommended.reduce(function (sum, item) {
        return new Decimal(sum).add(item._available_max_amount || 0).toNumber();
      }, 0);
      return {
        // 推荐券总金额
        recommendedAmount: recommendedAmount,
        // 推荐券列表
        recommended: recommended,
        // 格式化后的可用券列表
        transformList: transformList,
        // 后端不可用券列表 和前端基于策略返回的 不可用列表 合并
        noApplicableVoucher: noApplicableVoucher
      };
    }
  }, {
    key: "enhanceWithReason",
    value: function enhanceWithReason(voucher) {
      if (voucher._unified_available_status === 0 && voucher.reasonCode) {
        return _objectSpread(_objectSpread({}, voucher), {}, {
          reason: this.getText(voucher.reasonCode)
        });
      }
      return voucher;
    }

    /**
     * 优惠券处理函数
     * @param applicableVouchers 可用的券列表
     * @param orderTotalAmount 订单总金额
     * @param products 订单商品列表
     * @returns 返回推荐券列表和全部列表，每个券包含 _available_max_amount 和 _unified_available_status
     */
  }, {
    key: "processVouchers",
    value: function processVouchers(vouchers, orderTotalAmount, products) {
      var _this = this;
      var result = _processVouchers(vouchers, orderTotalAmount, products);
      return {
        recommended: result.recommended.map(function (item) {
          return _this.enhanceWithReason(item);
        }),
        transformList: result.transformList.map(function (item) {
          return _this.enhanceWithReason(item);
        })
      };
    }

    /**
     * 重新计算优惠券状态（基于已选券的增量计算）
     * @param allVouchers 所有原始券列表
     * @param selectedVouchers 已选中的券列表（按选中顺序）
     * @param orderTotalAmount 订单总金额
     * @param products 订单商品列表
     * @returns 返回更新后的所有券列表和已选券的详细抵扣信息
     */
  }, {
    key: "recalculateVouchers",
    value: function recalculateVouchers(allVouchers, selectedVouchers, orderTotalAmount, products) {
      var _this2 = this;
      var result = _recalculateVouchers(allVouchers, selectedVouchers, orderTotalAmount, products);
      return {
        allWithUpdatedStatus: result.allWithUpdatedStatus.map(function (item) {
          return _this2.enhanceWithReason(item);
        }),
        selectedWithDetails: result.selectedWithDetails.map(function (item) {
          return _this2.enhanceWithReason(item);
        })
      };
    }

    /**
     * 查找适用于指定 voucher 的策略配置
     */
  }, {
    key: "findApplicableStrategies",
    value: function findApplicableStrategies(voucher, strategyConfigs) {
      var _this3 = this;
      return strategyConfigs.filter(function (config) {
        // 检查策略的 conditions 中是否包含匹配此 voucher 的规则
        return _this3.checkVoucherInStrategy(voucher.product_id, config);
      });
    }

    /**
     * 检查策略中是否包含指定的 voucher ID
     */
  }, {
    key: "checkVoucherInStrategy",
    value: function checkVoucherInStrategy(voucherProductId, config) {
      var rules = config.conditions.rules;
      var _iterator2 = _createForOfIteratorHelper(rules),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var rule = _step2.value;
          // 如果是条件组，递归检查
          if ('operator' in rule && 'rules' in rule) {
            if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
              return true;
            }
          } else {
            // 检查是否是 voucherProductId 字段的规则
            var conditionRule = rule;
            if (conditionRule.field === 'voucherProductId' && conditionRule.operator === 'in' && Array.isArray(conditionRule.value)) {
              if (conditionRule.value.includes(voucherProductId)) {
                return true;
              }
            }
            // 支持等于判断
            if (conditionRule.field === 'voucherProductId' && (conditionRule.operator === '=' || conditionRule.operator === '==')) {
              if (conditionRule.value === voucherProductId) {
                return true;
              }
            }
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      return false;
    }

    /**
     * 递归检查条件组中是否包含 voucher ID
     */
  }, {
    key: "checkVoucherInConditionGroup",
    value: function checkVoucherInConditionGroup(voucherProductId, group) {
      var _iterator3 = _createForOfIteratorHelper(group.rules),
        _step3;
      try {
        for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
          var rule = _step3.value;
          if ('operator' in rule && 'rules' in rule) {
            if (this.checkVoucherInConditionGroup(voucherProductId, rule)) {
              return true;
            }
          } else {
            if (rule.field === 'voucherProductId' && rule.operator === 'in' && Array.isArray(rule.value)) {
              if (rule.value.includes(voucherProductId)) {
                return true;
              }
            }
            if (rule.field === 'voucherProductId' && (rule.operator === '=' || rule.operator === '==')) {
              if (rule.value === voucherProductId) {
                return true;
              }
            }
          }
        }
      } catch (err) {
        _iterator3.e(err);
      } finally {
        _iterator3.f();
      }
      return false;
    }

    /**
     * 计算适用商品的总金额和数量
     */
  }, {
    key: "calculateApplicableProducts",
    value: function calculateApplicableProducts(products, applicableProductIds, deductTaxAndFee) {
      var total = 0;
      var count = 0;

      // 如果为空数组，不适用任何商品
      if (applicableProductIds !== null && applicableProductIds.length === 0) {
        return {
          applicableTotal: 0,
          applicableCount: 0
        };
      }
      products.forEach(function (product) {
        var productQuantity = getProductQuantity(product);

        // 检查主商品是否适用
        var isMainProductApplicable = applicableProductIds === null || applicableProductIds.includes(product.product_id);
        if (isMainProductApplicable) {
          // 计算主商品价格（包含加减价子商品）
          total += getMainProductPrice(product, deductTaxAndFee) * productQuantity;
          count += productQuantity;
        }

        // 检查原价子商品（需要单独判断适用性）
        if (product.product_bundle && product.product_bundle.length > 0) {
          product.product_bundle.forEach(function (bundleItem) {
            // 只处理原价子商品，加减价子商品已包含在主商品价格中
            if (getBundleItemIsOriginalPrice(bundleItem)) {
              // 检查子商品是否适用
              var isBundleItemApplicable = applicableProductIds === null || applicableProductIds.includes(bundleItem.bundle_product_id);
              if (isBundleItemApplicable) {
                // 计算原价子商品价格
                var bundleItemQuantity = bundleItem.num * productQuantity;
                total += getBundleItemPrice(bundleItem, productQuantity, deductTaxAndFee);
                count += bundleItemQuantity;
              }
            }
          });
        }
      });
      return {
        applicableTotal: total,
        applicableCount: count
      };
    }
  }]);
  return WalletPassEvaluator;
}();