var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/modules/Quotation/index.ts
var Quotation_exports = {};
__export(Quotation_exports, {
  QuotationModule: () => QuotationModule
});
module.exports = __toCommonJS(Quotation_exports);
var import_BaseModule = require("../BaseModule");
var import_getDateIsInSchedule = require("../Schedule/getDateIsInSchedule");
var QuotationModule = class extends import_BaseModule.BaseModule {
  constructor(name, version) {
    super(name, version);
    this.defaultName = "quotation";
    this.defaultVersion = "1.0.0";
    this.store = { list: [] };
  }
  async initialize(core, options) {
    this.core = core;
    this.request = core.getPlugin("request");
    if (!this.request)
      throw new Error("QuotationModule 需要 request 插件支持");
    this.store = { list: [] };
  }
  async loadQuotations(params) {
    var _a;
    const query = {};
    if (params == null ? void 0 : params.channel)
      query.channel = params.channel;
    if (params == null ? void 0 : params.customer_id)
      query.customer_id = String(params.customer_id);
    if ((params == null ? void 0 : params.channel) === "online_store") {
      query.channel = "online-store";
    }
    const res = await this.request.get(
      "/quotation/available",
      query,
      { useCache: false }
    );
    const list = this.filterQuotationsByCustomer(
      ((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.list) || (res == null ? void 0 : res.list) || [],
      params == null ? void 0 : params.customer_id
    );
    list.sort((a, b) => a.sort - b.sort);
    this.store.list = list;
  }
  getQuotationList() {
    return this.store.list;
  }
  /**
   * Look up the quotation price for a specific product (+ optional variant) at a given datetime.
   * Returns the price as a string (e.g. "300.00"), or null if no quotation applies.
   *
   * Priority: iterates quotations already sorted by `sort` ascending (lowest = highest priority).
   * First matching quotation whose schedule covers `datetime` and whose product_data contains
   * the requested productId wins.
   */
  getPriceForProduct(params) {
    const { productId, variantId, datetime, customer_id } = params;
    for (const quotation of this.store.list) {
      const visible = this.isQuotationVisibleForCustomer(quotation, customer_id);
      if (!visible)
        continue;
      const active = this.isQuotationActiveAt(quotation, datetime);
      if (!active)
        continue;
      const match = this.findProductData(quotation.product_data, productId, variantId);
      if (!match)
        continue;
      if (match.value === 0)
        continue;
      return String(match.value);
    }
    return null;
  }
  getQuotationShelfId(params) {
    const { productId, variantId, datetime, customer_id } = params;
    for (const quotation of this.store.list) {
      if (!this.isQuotationVisibleForCustomer(quotation, customer_id))
        continue;
      if (!this.isQuotationActiveAt(quotation, datetime))
        continue;
      const match = this.findProductData(quotation.product_data, productId, variantId);
      if (!match || match.value === 0)
        continue;
      return quotation.id;
    }
    return 0;
  }
  /**
   * Batch pre-compute quotation prices for a set of products across multiple time points.
   * Key format: `${productId}:${timePoint}`
   * This avoids repeated schedule matching when the same product appears in multiple resource rows.
   */
  buildProductPriceMap(params) {
    const map = /* @__PURE__ */ new Map();
    if (!this.store.list.length)
      return map;
    for (const productId of params.productIds) {
      for (const timePoint of params.timePoints) {
        const key = `${productId}:${timePoint}`;
        const price = this.getPriceForProduct({
          productId,
          datetime: timePoint,
          customer_id: params.customer_id
        });
        if (price !== null) {
          map.set(key, price);
        }
      }
    }
    return map;
  }
  setScheduleResolver(resolver) {
    this.scheduleResolver = resolver;
  }
  filterQuotationsByCustomer(list, customerId) {
    return list.filter((quotation) => this.isQuotationVisibleForCustomer(quotation, customerId));
  }
  isQuotationVisibleForCustomer(quotation, customerId) {
    const customers = quotation.customer || [];
    if (customers.length === 0)
      return true;
    if (!this.hasValidCustomerId(customerId))
      return false;
    return customers.some((customer) => String(customer.id) === String(customerId));
  }
  hasValidCustomerId(customerId) {
    if (customerId === void 0 || customerId === null || customerId === "")
      return false;
    return Number(customerId) > 0;
  }
  isQuotationActiveAt(quotation, datetime) {
    var _a;
    if (!((_a = quotation.schedule) == null ? void 0 : _a.length))
      return false;
    const scheduleItems = [];
    quotation.schedule.forEach((s) => {
      var _a2;
      const full = (_a2 = this.scheduleResolver) == null ? void 0 : _a2.call(this, s.id);
      if (full) {
        scheduleItems.push(full);
        return;
      }
      if (this.scheduleResolver) {
        return;
      }
      const fallbackSchedule = {
        ...s,
        repeat_type: s.repeat_type || "none",
        repeat_rule: s.repeat_rule || null,
        time_slot: s.time_slot || []
      };
      scheduleItems.push(fallbackSchedule);
    });
    if (!scheduleItems.length)
      return false;
    return (0, import_getDateIsInSchedule.getDateIsInSchedule)(datetime, scheduleItems);
  }
  findProductData(productData, productId, variantId) {
    if (variantId && variantId !== 0) {
      const variantMatch = productData.find(
        (p) => p.product_id === productId && p.variant_id === variantId
      );
      if (variantMatch)
        return variantMatch;
    }
    return productData.find(
      (p) => p.product_id === productId && p.variant_id === 0
    );
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  QuotationModule
});
