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/plus/pisellGlobalSearch/api/searchService.ts
var searchService_exports = {};
__export(searchService_exports, {
  SALES_SEARCH_WITH: () => SALES_SEARCH_WITH,
  getSalesOrderId: () => getSalesOrderId,
  mapGridFiltersToEs: () => mapGridFiltersToEs,
  parseSortKey: () => parseSortKey,
  searchAggregateSales: () => searchAggregateSales,
  searchModeFromMode: () => searchModeFromMode,
  searchSalesModule: () => searchSalesModule,
  unsubscribeAggregateSalesSearch: () => unsubscribeAggregateSalesSearch,
  unsubscribeSalesSearch: () => unsubscribeSalesSearch
});
module.exports = __toCommonJS(searchService_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("../../../utils");
var SALES_SEARCH_WITH = [
  "bookings",
  "products",
  "payments",
  "vouchers",
  "surcharges",
  "discount_list",
  "relation_forms",
  "contacts_info",
  "holder",
  "summary",
  "customer"
];
var searchModeFromMode = (mode) => mode === "admin" ? "fuzzy" : "identifier";
function buildSalesPaginationBody(params) {
  const { filters, sort, page = 1, perPage = 20 } = params;
  return {
    page,
    per_page: perPage,
    ...filters && Object.keys(filters).length ? { filters } : {},
    ...sort && sort.length ? { sort } : {}
  };
}
function buildSalesQueryBody(params) {
  return {
    search_mode: params.searchMode,
    with: SALES_SEARCH_WITH,
    ...buildSalesPaginationBody(params),
    keyword: params.keyword
  };
}
function normalizeSalesResult(data, page, perPage) {
  const items = Array.isArray(data == null ? void 0 : data.list) ? data.list : [];
  const total = Number((data == null ? void 0 : data.count) ?? items.length) || 0;
  const resolvedPage = Number((data == null ? void 0 : data.skip) ?? page) || page;
  const resolvedPerPage = Number((data == null ? void 0 : data.size) ?? perPage) || perPage;
  return {
    items,
    total,
    page: resolvedPage,
    perPage: resolvedPerPage,
    // 文档未返回 has_more：由「当前页范围 < 总数」推导。
    hasMore: resolvedPage * resolvedPerPage < total
  };
}
async function searchSalesModule(params) {
  const {
    page = 1,
    perPage = 20,
    signal,
    subscriberId,
    callback,
    resetVisibleOrderIds
  } = params;
  const body = buildSalesQueryBody(params);
  const res = await import_utils.request.getRequest().post("/shop/es/search/sales", body, {
    fullResult: true,
    isShopApi: true,
    osServer: true,
    signal,
    subscriberId,
    callback,
    resetVisibleOrderIds
  });
  return normalizeSalesResult(res == null ? void 0 : res.data, page, perPage);
}
async function searchAggregateSales(params) {
  var _a;
  const {
    page = 1,
    perPage = 20,
    signal,
    subscriberId,
    callback,
    resetVisibleOrderIds
  } = params;
  const body = {
    search_mode: params.searchMode,
    with: SALES_SEARCH_WITH,
    keyword: params.keyword,
    modules: [{ module: "sales", data: buildSalesPaginationBody(params) }]
  };
  const res = await import_utils.request.getRequest().post("/shop/es/search", body, {
    fullResult: true,
    isShopApi: true,
    osServer: true,
    signal,
    subscriberId,
    callback,
    resetVisibleOrderIds
  });
  const results = (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.results;
  const salesGroup = Array.isArray(results) ? results.find((r) => (r == null ? void 0 : r.module) === "sales") : void 0;
  return normalizeSalesResult(salesGroup, page, perPage);
}
async function unsubscribeSalesSearch(subscriberId) {
  await (0, import_utils.unsubscribeOsQuery)("/shop/es/search/sales/unsubscribe", subscriberId, {
    fullResult: true
  });
}
async function unsubscribeAggregateSalesSearch(subscriberId) {
  await (0, import_utils.unsubscribeOsQuery)("/shop/es/search/unsubscribe", subscriberId, {
    fullResult: true
  });
}
var getSalesOrderId = (item) => {
  const raw = (item == null ? void 0 : item.order_id) ?? (item == null ? void 0 : item.id);
  if (raw === void 0 || raw === null) return void 0;
  const n = Number(raw);
  return Number.isFinite(n) ? n : void 0;
};
var parseSortKey = (sort) => {
  if (!sort || typeof sort !== "string") return void 0;
  const [field, dir] = sort.split(":");
  if (!field) return void 0;
  return [{ field, direction: dir === "asc" ? "asc" : "desc" }];
};
var mapGridFiltersToEs = (values) => {
  const out = {};
  if (!values || typeof values !== "object") return out;
  for (const [key, val] of Object.entries(values)) {
    if (val === void 0 || val === null || val === "") continue;
    if (Array.isArray(val) && val.length === 0) continue;
    if (key === "orderDate") {
      const [start, end] = Array.isArray(val) ? val : [];
      const range = {};
      if (start) {
        range.from = (0, import_dayjs.default)(start).startOf("day").format("YYYY-MM-DD HH:mm:ss");
      }
      if (end) {
        range.to = (0, import_dayjs.default)(end).endOf("day").format("YYYY-MM-DD HH:mm:ss");
      }
      if (range.from || range.to) out.created_at = range;
      continue;
    }
    if (key === "total_amount" && typeof val === "object" && !Array.isArray(val)) {
      const range = {};
      if (val.min !== void 0 && val.min !== null && val.min !== "") {
        range.gte = Number(val.min);
      }
      if (val.max !== void 0 && val.max !== null && val.max !== "") {
        range.lte = Number(val.max);
      }
      if (Object.keys(range).length) out.total_amount = range;
      continue;
    }
    out[key] = val;
  }
  return out;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SALES_SEARCH_WITH,
  getSalesOrderId,
  mapGridFiltersToEs,
  parseSortKey,
  searchAggregateSales,
  searchModeFromMode,
  searchSalesModule,
  unsubscribeAggregateSalesSearch,
  unsubscribeSalesSearch
});
