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/pisellSalesManagement/hooks/useSalesGridData.ts
var useSalesGridData_exports = {};
__export(useSalesGridData_exports, {
  useSalesGridData: () => useSalesGridData
});
module.exports = __toCommonJS(useSalesGridData_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_booking = require("../config/booking");
var import_serve = require("../../pisellSalesGrid/serve");
function getDefaultSearchParams(perspective) {
  if (perspective === "monitor") {
    return {
      filter: {
        values: {
          order_payment_status: import_booking.defaultPaymentStatusKeys,
          booking_time_start_between: [
            (0, import_dayjs.default)().startOf("day"),
            (0, import_dayjs.default)().endOf("day")
          ]
        }
      }
    };
  }
  return {
    filter: {
      values: {
        payment_status: import_booking.defaultPaymentStatusKeys,
        orderDate: [(0, import_dayjs.default)(), (0, import_dayjs.default)()]
      }
    },
    sort: "created_at:desc"
  };
}
function resolveSalesGridRowKey(perspective, record) {
  if (perspective === "handle") {
    return (record == null ? void 0 : record.order_id) || (record == null ? void 0 : record.id);
  }
  return (record == null ? void 0 : record.id) ?? "";
}
function useSalesGridData(params) {
  var _a, _b, _c, _d, _e;
  const { perspective, extParams } = params;
  const engineContext = (0, import_useEngineContext.default)();
  const { action } = ((_a = engineContext == null ? void 0 : engineContext.appHelper) == null ? void 0 : _a.utils) || {};
  const [pagination, setPagination] = (0, import_react.useState)({ pageNumber: 1, pageSize: 50 });
  const [searchParams, setSearchParams] = (0, import_react.useState)(
    () => getDefaultSearchParams(perspective)
  );
  const [selectedKeys, setSelectedKeys] = (0, import_react.useState)([]);
  const [selectedRows, setSelectedRows] = (0, import_react.useState)([]);
  const orderSubscriberIdRef = (0, import_react.useRef)((0, import_utils.getUniqueId)());
  const bookingSubscriberIdRef = (0, import_react.useRef)((0, import_utils.getUniqueId)());
  const orderMutateRef = (0, import_react.useRef)(null);
  const bookingMutateRef = (0, import_react.useRef)(null);
  const requestParams = (0, import_react.useMemo)(() => {
    const { keyword, filter, sort } = searchParams;
    const filterVals = (filter == null ? void 0 : filter.values) || {};
    return {
      keyword,
      sort,
      ...filterVals,
      skip: pagination.pageNumber,
      num: pagination.pageSize
    };
  }, [searchParams, pagination.pageNumber, pagination.pageSize]);
  const normalizeRealtimePayload = (0, import_ahooks.useMemoizedFn)((res) => {
    return (res == null ? void 0 : res.data) ?? res;
  });
  const fetchOrderList = (0, import_ahooks.useMemoizedFn)(async (query) => {
    return (0, import_serve.getOrderList)(query, {
      osServer: true,
      subscriberId: orderSubscriberIdRef.current,
      callback: (res) => {
        var _a2;
        const payload = normalizeRealtimePayload(res);
        if (payload == null || !Array.isArray(payload.list)) return;
        if (payload.list.length === 0) return;
        (_a2 = orderMutateRef.current) == null ? void 0 : _a2.call(orderMutateRef, payload);
      }
    });
  });
  const fetchBookingList = (0, import_ahooks.useMemoizedFn)(async (query) => {
    return (0, import_serve.getBookingList)(query, {
      osServer: true,
      subscriberId: bookingSubscriberIdRef.current,
      callback: (res) => {
        var _a2;
        const payload = normalizeRealtimePayload(res);
        if (payload == null || !Array.isArray(payload.list)) return;
        if (payload.list.length === 0) return;
        (_a2 = bookingMutateRef.current) == null ? void 0 : _a2.call(bookingMutateRef, (0, import_serve.formatBookingResult)(payload));
      }
    });
  });
  const _getOrderList = (0, import_ahooks.useRequest)(fetchOrderList, { manual: true });
  const _getBookingList = (0, import_ahooks.useRequest)(fetchBookingList, { manual: true });
  orderMutateRef.current = _getOrderList.mutate;
  bookingMutateRef.current = _getBookingList.mutate;
  const runListParams = (0, import_react.useMemo)(
    () => ({ ...requestParams, ...(extParams == null ? void 0 : extParams.list) || {} }),
    [requestParams, extParams == null ? void 0 : extParams.list]
  );
  (0, import_react.useEffect)(() => {
    if (perspective === "monitor") {
      _getBookingList.run(runListParams);
    } else {
      _getOrderList.run(runListParams);
    }
  }, [perspective, runListParams]);
  (0, import_react.useEffect)(() => {
    setSearchParams(getDefaultSearchParams(perspective));
    setPagination((p) => ({ ...p, pageNumber: 1 }));
    setSelectedKeys([]);
    setSelectedRows([]);
  }, [perspective]);
  const onPageChange = (0, import_react.useCallback)((pageNumber, pageSize) => {
    if (pageNumber < 1 || pageSize < 1) return;
    setPagination({ pageNumber, pageSize });
  }, []);
  const onSearch = (0, import_react.useCallback)((params2) => {
    setSearchParams(params2 || {});
    setPagination((prev) => ({ ...prev, pageNumber: 1 }));
  }, []);
  const onReset = (0, import_react.useCallback)(() => {
    setSearchParams(getDefaultSearchParams(perspective));
    setPagination((prev) => ({ ...prev, pageNumber: 1 }));
  }, [perspective]);
  const onSelectionChange = (0, import_react.useCallback)((keys, rows) => {
    setSelectedKeys(keys);
    setSelectedRows(rows);
  }, []);
  const onRefresh = (0, import_react.useCallback)((keys) => {
    if (perspective === "monitor") {
      _getBookingList.run(runListParams);
    } else {
      _getOrderList.run(runListParams);
    }
    if (keys && keys.length > 0) {
      action({
        type: "webpos.updateLocalOrdersApi",
        data: {
          order_ids: keys
        }
      });
    }
  }, [perspective, runListParams, _getBookingList, _getOrderList]);
  const refreshAsync = (0, import_react.useCallback)(() => {
    if (perspective === "monitor") {
      return _getBookingList.runAsync(runListParams);
    }
    return _getOrderList.runAsync(runListParams);
  }, [perspective, runListParams, _getBookingList, _getOrderList]);
  (0, import_react.useEffect)(() => {
    if (perspective === "monitor") {
      void (0, import_serve.unsubscribeOrderQuery)(orderSubscriberIdRef.current);
      return;
    }
    void (0, import_serve.unsubscribeBookingQuery)(bookingSubscriberIdRef.current);
  }, [perspective]);
  (0, import_react.useEffect)(() => {
    return () => {
      void (0, import_serve.unsubscribeOrderQuery)(orderSubscriberIdRef.current);
      void (0, import_serve.unsubscribeBookingQuery)(bookingSubscriberIdRef.current);
    };
  }, []);
  const data = perspective === "monitor" ? ((_b = _getBookingList.data) == null ? void 0 : _b.list) ?? [] : ((_c = _getOrderList.data) == null ? void 0 : _c.list) ?? [];
  const loading = perspective === "monitor" ? _getBookingList.loading : _getOrderList.loading;
  const total = perspective === "monitor" ? ((_d = _getBookingList.data) == null ? void 0 : _d.count) ?? 0 : ((_e = _getOrderList.data) == null ? void 0 : _e.count) ?? 0;
  const rowKey = (0, import_react.useMemo)(
    () => (record) => resolveSalesGridRowKey(perspective, record),
    [perspective]
  );
  return {
    data,
    loading,
    total,
    pagination,
    onPageChange,
    searchParams,
    onSearch,
    onReset,
    selectedKeys,
    selectedRows,
    onSelectionChange,
    rowKey,
    onRefresh,
    refreshAsync
  };
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useSalesGridData
});
