var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/Discount/index.ts
var Discount_exports = {};
__export(Discount_exports, {
  DiscountModule: () => DiscountModule
});
module.exports = __toCommonJS(Discount_exports);
var import_utils = require("../../solution/ShopDiscount/utils");
var import_BaseModule = require("../BaseModule");
var import_types = require("./types");
var import_decimal = __toESM(require("decimal.js"));
var DiscountModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "discount";
    this.defaultVersion = "1.0.0";
    this.openCache = false;
  }
  async initialize(core, options) {
    var _a, _b, _c, _d;
    this.core = core;
    this.store = options == null ? void 0 : options.store;
    if (Array.isArray((_a = options == null ? void 0 : options.initialState) == null ? void 0 : _a.discountList)) {
      this.store.discountList = options == null ? void 0 : options.initialState.discountList;
    } else {
      this.store.discountList = [];
    }
    if (Array.isArray((_b = options == null ? void 0 : options.initialState) == null ? void 0 : _b.originalDiscountList)) {
      this.store.originalDiscountList = options == null ? void 0 : options.initialState.originalDiscountList;
    } else {
      this.store.originalDiscountList = [];
    }
    if ((_c = options == null ? void 0 : options.otherParams) == null ? void 0 : _c.cacheId) {
      this.openCache = options.otherParams.openCache;
      this.cacheId = options.otherParams.cacheId;
    }
    if ((_d = options == null ? void 0 : options.otherParams) == null ? void 0 : _d.fatherModule) {
      this.fatherModule = options.otherParams.fatherModule;
    }
    this.request = core.getPlugin("request");
    this.window = core.getPlugin("window");
    if (!this.request) {
      throw new Error("discount模块需要 request 插件支持");
    }
    if (!this.window) {
      throw new Error("discount模块需要 window 插件支持");
    }
  }
  async setDiscountList(discountList) {
    this.store.discountList = discountList;
    await this.core.effects.emit(
      import_types.DiscountHooks.OnDiscountListChange,
      discountList
    );
  }
  getDiscountList() {
    return this.store.discountList;
  }
  // 设置原始优惠券列表
  async setOriginalDiscountList(originalDiscountList) {
    this.store.originalDiscountList = originalDiscountList;
  }
  // 获取原始优惠券列表
  getOriginalDiscountList() {
    return this.store.originalDiscountList || [];
  }
  async loadPrepareConfig(params) {
    var _a, _b;
    const prepareConfig = await this.request.post(
      `/order/prepare/config`,
      params
    );
    const rawDiscountList = [
      ...((_a = prepareConfig == null ? void 0 : prepareConfig.data) == null ? void 0 : _a.good_pass_list) || [],
      ...((_b = prepareConfig == null ? void 0 : prepareConfig.data) == null ? void 0 : _b.discount_card_list) || []
    ];
    const goodPassList = this.filterEnabledDiscountList(
      rawDiscountList
    ) || [];
    return goodPassList;
  }
  async batchSearch(code, options) {
    const { customerId, orderId } = options || {};
    const result = await this.request.get(`/machinecode/batch-search`, {
      code,
      translate_flag: 1,
      tags: ["good_pass", "product_discount_card"],
      // available: 1,
      relation_product: 1,
      with: ["extensionData", "customScheduleSnapshot", "holder.detail"],
      order_behavior_count: 1,
      order_behavior_count_customer_id: customerId || 1,
      ...orderId ? { order_behavior_count_order_id: orderId } : {},
      unified_status_info_flag: 1,
      request_timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
    });
    const resultDiscountWithReason = this.filterEnabledDiscountListWithReason((result == null ? void 0 : result.data) || []) || [];
    return resultDiscountWithReason;
  }
  filterEnabledDiscountList(discountList) {
    return discountList.filter(
      (discount) => discount.limit_status === "enable" && new import_decimal.default((discount == null ? void 0 : discount.par_value) || 0).minus(new import_decimal.default((discount == null ? void 0 : discount.used_par_value) || 0)).greaterThan(0) && this.checkUsageCreditsLimit(discount)
    );
  }
  // 检查使用次数限制
  checkUsageCreditsLimit(discount) {
    if (!discount.extension_data || discount.extension_data.length === 0) {
      return true;
    }
    const usageCreditsData = discount.extension_data.find(
      (data) => data.field_key === "usage_credits"
    );
    if (!usageCreditsData) {
      return true;
    }
    const value = usageCreditsData.value;
    if (value.total_credits && value.total_credits > 0) {
      if ((discount.total_order_behavior_count || 0) >= value.total_credits) {
        return false;
      }
    }
    if (value.per_user_limit && value.per_user_limit > 0) {
      if ((discount.customer_order_behavior_count || 0) >= value.per_user_limit) {
        return false;
      }
    }
    if (value.max_per_day && value.max_per_day > 0) {
      if ((discount.today_order_behavior_count || 0) >= value.max_per_day) {
        return false;
      }
    }
    if (value.max_per_week && value.max_per_week > 0) {
      if ((discount.week_order_behavior_count || 0) >= value.max_per_week) {
        return false;
      }
    }
    if (value.max_per_month && value.max_per_month > 0) {
      if ((discount.month_order_behavior_count || 0) >= value.max_per_month) {
        return false;
      }
    }
    return true;
  }
  // 过滤启用且可用的优惠券，并返回校验失败原因
  filterEnabledDiscountListWithReason(discountList) {
    let lists = discountList.filter((discount) => discount.limit_status === "enable").filter((discount) => {
      const remaining = new import_decimal.default((discount == null ? void 0 : discount.par_value) || 0).minus(new import_decimal.default((discount == null ? void 0 : discount.used_par_value) || 0)).greaterThan(0);
      return remaining;
    }).map((discount) => {
      const limitFailKey = this.checkUsageCreditsLimitWithFailKey(discount);
      return {
        ...discount,
        usageLimitFailKey: limitFailKey
      };
    });
    const availableLists = lists.filter((item) => !item.usageLimitFailKey && item.unified_available_status !== 0);
    const currentFailDiscount = lists.find((item) => item.usageLimitFailKey);
    return {
      discountList: availableLists,
      unavailableReasonKey: currentFailDiscount == null ? void 0 : currentFailDiscount.usageLimitFailKey
    };
  }
  // 检查使用次数限制，并返回校验失败原因
  checkUsageCreditsLimitWithFailKey(discount) {
    if (!discount.extension_data || discount.extension_data.length === 0) {
      return null;
    }
    const usageCreditsData = discount.extension_data.find(
      (data) => data.field_key === "usage_credits"
    );
    if (!usageCreditsData) {
      return null;
    }
    const value = usageCreditsData.value;
    if (value.total_credits && value.total_credits > 0) {
      if ((discount.total_order_behavior_count || 0) >= value.total_credits) {
        return "total_credits";
      }
    }
    if (value.per_user_limit && value.per_user_limit > 0) {
      if ((discount.customer_order_behavior_count || 0) >= value.per_user_limit) {
        return "per_user_limit";
      }
    }
    if (value.max_per_day && value.max_per_day > 0) {
      if ((discount.today_order_behavior_count || 0) >= value.max_per_day) {
        return "max_per_day";
      }
    }
    if (value.max_per_week && value.max_per_week > 0) {
      if ((discount.week_order_behavior_count || 0) >= value.max_per_week) {
        return "max_per_week";
      }
    }
    if (value.max_per_month && value.max_per_month > 0) {
      if ((discount.month_order_behavior_count || 0) >= value.max_per_month) {
        return "max_per_month";
      }
    }
    return null;
  }
  // 根据productIds去重
  uniqueByProductId(discountList) {
    return (0, import_utils.uniqueById)(discountList, "product_id");
  }
  filterDiscountListByProductIds(discountList, productIds) {
    return discountList.filter((discount) => {
      const applicableProductIds = discount.applicableProductIds || [];
      return applicableProductIds.some((id) => productIds.includes(id));
    });
  }
  calcDiscountApplicableProductTotalPrice(discount) {
    if (discount == null ? void 0 : discount.savedAmount) {
      return (discount == null ? void 0 : discount.savedAmount) || 0;
    }
    if (discount.appliedProductDetails) {
      return discount.appliedProductDetails.reduce((total, product) => {
        var _a, _b;
        const price = new import_decimal.default(((_a = product == null ? void 0 : product.discount) == null ? void 0 : _a.fixed_amount) || 0).mul((product == null ? void 0 : product._num) || 1);
        return new import_decimal.default(total).plus(price).add(((_b = product == null ? void 0 : product.metadata) == null ? void 0 : _b.product_discount_difference) || 0).toNumber();
      }, 0);
    }
  }
  async destroy() {
    this.store.discountList = [];
    this.core.effects.offByModuleDestroy(this.name);
    await this.core.effects.emit(`${this.name}:onDestroy`, {});
    console.log("[Discount] 已销毁");
  }
  async clear() {
    this.store.discountList = [];
    this.store.originalDiscountList = [];
    console.log("[Discount] clear");
  }
  storeChange() {
    if (this.openCache) {
      this.checkSaveCache({
        cacheId: this.cacheId,
        fatherModule: this.fatherModule,
        store: this.store,
        cacheKey: ["discountList"]
      });
    }
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DiscountModule
});
