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/pisellSalesGrid/PisellSalesGrid.tsx
var PisellSalesGrid_exports = {};
__export(PisellSalesGrid_exports, {
  default: () => PisellSalesGrid_default
});
module.exports = __toCommonJS(PisellSalesGrid_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_ahooks = require("ahooks");
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("../../utils");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_useActions = __toESM(require("./hooks/useActions"));
var import_booking = require("../pisellSalesManagement/config/booking");
var import_serve = require("./serve");
var import_PisellSalesGrid = require("./PisellSalesGrid.less");
function getCurrentPerspectiveConfig(perspectives, currentPerspective) {
  const found = perspectives.find((p) => p.key === currentPerspective);
  if (found) return found;
  if (perspectives.length > 0) return perspectives[0];
  return void 0;
}
function getDefaultSearchParams(currentPerspective) {
  if (currentPerspective === "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"
  };
}
var SEARCH_PARAMS_STORAGE_PREFIX = "pisell_sales_grid_search_params_";
function serializeSearchParams(params) {
  return JSON.stringify(params, (key, value) => {
    if (import_dayjs.default.isDayjs(value)) {
      return { __isDayjs: true, value: value.toISOString() };
    }
    return value;
  });
}
function deserializeSearchParams(str) {
  return JSON.parse(str, (key, value) => {
    if (value && typeof value === "object" && value.__isDayjs) {
      return (0, import_dayjs.default)(value.value);
    }
    return value;
  });
}
function normalizeFilterForStorage(filter) {
  if (!filter || typeof filter !== "object") return filter;
  return {
    values: filter.values ?? {},
    quickFilter: Array.isArray(filter.quickFilter) ? filter.quickFilter : []
  };
}
var PERSIST_FILTER_BY_DEFAULT = false;
function normalizeRestoredSearchParams(params) {
  if (!params || typeof params !== "object") return params;
  const filter = params.filter;
  if (!filter || typeof filter !== "object") return params;
  return {
    ...params,
    filter: normalizeFilterForStorage(filter)
  };
}
function getStoredSearchParams(id) {
  try {
    const stored = sessionStorage.getItem(
      `${SEARCH_PARAMS_STORAGE_PREFIX}${id}`
    );
    if (stored) {
      const parsed = deserializeSearchParams(stored);
      const normalized = PERSIST_FILTER_BY_DEFAULT ? normalizeRestoredSearchParams(parsed) : parsed;
      if (!PERSIST_FILTER_BY_DEFAULT && normalized && typeof normalized === "object") {
        const { filter: _f, ...rest } = normalized;
        return rest;
      }
      return normalized;
    }
  } catch (e) {
    console.warn("Failed to get stored search params:", e);
  }
  return null;
}
function saveSearchParams(id, params) {
  try {
    let toStore;
    if (PERSIST_FILTER_BY_DEFAULT) {
      toStore = {
        ...params,
        filter: params.filter ? normalizeFilterForStorage(params.filter) : params.filter
      };
    } else {
      const { filter: _f, ...rest } = params;
      toStore = rest;
    }
    sessionStorage.setItem(
      `${SEARCH_PARAMS_STORAGE_PREFIX}${id}`,
      serializeSearchParams(toStore)
    );
  } catch (e) {
    console.warn("Failed to save search params:", e);
  }
}
function mergeColumnRenderersIntoGrid(gridConfig, columnRenderers) {
  if (!(columnRenderers == null ? void 0 : columnRenderers.length) || !Array.isArray(gridConfig.columns)) {
    return gridConfig;
  }
  const byType = new Map(
    columnRenderers.map((r) => [r.type, r.render])
  );
  return {
    ...gridConfig,
    columns: gridConfig.columns.map((col) => {
      const t = col == null ? void 0 : col.type;
      if (t != null && byType.has(t)) {
        const renderCell = byType.get(t);
        return {
          ...col,
          render: (value, record, index) => renderCell(value, record, index)
        };
      }
      return col;
    })
  };
}
var PisellSalesGrid = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
  const {
    perspectives,
    currentPerspective,
    className,
    style,
    extParams,
    __id,
    data: propsData,
    loading: propsLoading,
    total: propsTotal,
    pagination: propsPagination,
    onPageChange: propsOnPageChange,
    searchParams: propsSearchParams,
    onSearch: propsOnSearch,
    onReset: propsOnReset,
    selectedKeys: propsSelectedKeys,
    selectedRows: propsSelectedRows,
    onSelectionChange: propsOnSelectionChange,
    rowKey: propsRowKey,
    onRefresh: propsOnRefresh,
    refreshAsync: propsRefreshAsync,
    columnRenderers
  } = props;
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  import_utils.request.setRequest(utils == null ? void 0 : utils.request);
  const isControlledData = propsData !== void 0;
  const [selectedKeys, setSelectedKeys] = (0, import_react.useState)([]);
  const [selectedRows, setSelectedRows] = (0, import_react.useState)([]);
  const [pagination, setPagination] = (0, import_react.useState)({
    pageNumber: 1,
    pageSize: 50
  });
  const [searchParams, setSearchParams] = (0, import_react.useState)(() => {
    const defaultParams = getDefaultSearchParams(currentPerspective);
    if (__id) {
      const stored = getStoredSearchParams(__id);
      if (stored) {
        return { ...defaultParams, ...stored };
      }
    }
    return defaultParams;
  });
  const onSelectionChange = (0, import_react.useCallback)((keys, rows) => {
    setSelectedKeys(keys);
    setSelectedRows(rows);
  }, []);
  const onPageChange = (0, import_react.useCallback)((pageNumber, pageSize) => {
    if (pageNumber < 1 || pageSize < 1) return;
    setPagination({ pageNumber, pageSize });
  }, []);
  const onSearch = (0, import_react.useCallback)((params) => {
    setSearchParams(params || {});
    setPagination((prev) => ({ ...prev, pageNumber: 1 }));
  }, []);
  const onReset = (0, import_react.useCallback)(() => {
    setSearchParams(getDefaultSearchParams(currentPerspective));
    setPagination((prev) => ({ ...prev, pageNumber: 1 }));
  }, [currentPerspective]);
  (0, import_react.useEffect)(() => {
    if (__id) {
      saveSearchParams(__id, searchParams);
    }
  }, [__id, searchParams]);
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  const _getBookingList = (0, import_ahooks.useRequest)(import_serve.getBookingList, {
    manual: true
  });
  const _getOrderList = (0, import_ahooks.useRequest)(import_serve.getOrderList, {
    manual: true
  });
  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 initLoad = (0, import_react.useCallback)(() => {
    if (currentPerspective === "monitor") {
      _getBookingList.run({ ...requestParams, ...(extParams == null ? void 0 : extParams.list) || {} });
      return;
    }
    _getOrderList.run({
      ...requestParams,
      ...(extParams == null ? void 0 : extParams.list) || {}
    });
  }, [currentPerspective, requestParams, _getBookingList, _getOrderList]);
  const onClearSelection = (0, import_react.useCallback)(() => {
    setSelectedKeys([]);
    setSelectedRows([]);
  }, []);
  const actions = (0, import_useActions.default)({
    onRefresh: initLoad,
    onClearSelection
  });
  const batchActionConfig = (0, import_react.useMemo)(() => {
    return {
      actions
    };
  }, [actions]);
  (0, import_react.useEffect)(() => {
    if (isControlledData) return;
    if (currentPerspective === "monitor") {
      _getBookingList.run({ ...requestParams, ...(extParams == null ? void 0 : extParams.list) || {} });
    } else {
      _getOrderList.run({
        ...requestParams,
        ...(extParams == null ? void 0 : extParams.list) || {}
      });
    }
  }, [
    isControlledData,
    currentPerspective,
    requestParams,
    extParams == null ? void 0 : extParams.list,
    _getBookingList,
    _getOrderList
  ]);
  const runtimeContext = (0, import_react.useMemo)(() => {
    if (isControlledData && propsOnRefresh) {
      return {
        refresh: propsOnRefresh,
        refreshAsync: propsRefreshAsync ?? (() => Promise.resolve()),
        currentPerspective
      };
    }
    return {
      refresh: currentPerspective === "monitor" ? () => _getBookingList.run({
        ...requestParams,
        ...(extParams == null ? void 0 : extParams.list) || {}
      }) : () => _getOrderList.run({
        ...requestParams,
        ...(extParams == null ? void 0 : extParams.list) || {}
      }),
      refreshAsync: currentPerspective === "monitor" ? () => _getBookingList.runAsync({
        ...requestParams,
        ...(extParams == null ? void 0 : extParams.list) || {}
      }) : () => _getOrderList.runAsync({
        ...requestParams,
        ...(extParams == null ? void 0 : extParams.list) || {}
      }),
      currentPerspective
    };
  }, [
    isControlledData,
    propsOnRefresh,
    propsRefreshAsync,
    currentPerspective,
    _getBookingList,
    _getOrderList,
    requestParams,
    extParams
  ]);
  const currentConfig = (0, import_react.useMemo)(() => {
    const raw = getCurrentPerspectiveConfig(perspectives, currentPerspective);
    if (!raw) return void 0;
    if (typeof raw.getChildComponentProps === "function") {
      return {
        ...raw,
        childComponentProps: raw.getChildComponentProps(runtimeContext)
      };
    }
    return raw;
  }, [perspectives, currentPerspective, runtimeContext]);
  const recordBoardGridProps = (0, import_react.useMemo)(() => {
    var _a2;
    const gridConfig = mergeColumnRenderersIntoGrid(
      ((_a2 = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _a2.grid) ?? {},
      columnRenderers
    );
    const keys = isControlledData && propsSelectedKeys !== void 0 ? propsSelectedKeys : selectedKeys;
    const rows = isControlledData && propsSelectedRows !== void 0 ? propsSelectedRows : selectedRows;
    const onSel = isControlledData && propsOnSelectionChange ? propsOnSelectionChange : onSelectionChange;
    return {
      ...gridConfig,
      selectedKeys: keys,
      selectedRows: rows,
      onSelectionChange: onSel
    };
  }, [
    currentConfig,
    isControlledData,
    propsSelectedKeys,
    propsSelectedRows,
    propsOnSelectionChange,
    selectedKeys,
    selectedRows,
    onSelectionChange,
    columnRenderers
  ]);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: `pisell-sales-grid ${className ?? ""}`.trim(),
      style: {
        height: "100%",
        minHeight: 0,
        display: "flex",
        flexDirection: "column",
        ...style
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellRecordBoard,
      {
        key: currentPerspective,
        __id,
        layoutType: "grid",
        rowKey: propsRowKey ?? "id",
        data: isControlledData ? propsData ?? [] : currentPerspective === "monitor" ? ((_b = _getBookingList.data) == null ? void 0 : _b.list) || [] : ((_c = _getOrderList.data) == null ? void 0 : _c.list) || [],
        loading: isControlledData ? propsLoading ?? false : currentPerspective === "monitor" ? _getBookingList.loading : _getOrderList.loading,
        total: isControlledData ? propsTotal ?? 0 : currentPerspective === "monitor" ? ((_d = _getBookingList.data) == null ? void 0 : _d.count) || 0 : ((_e = _getOrderList.data) == null ? void 0 : _e.count) || 0,
        pagination: isControlledData && propsPagination ? propsPagination : pagination,
        onPageChange: isControlledData && propsOnPageChange ? propsOnPageChange : onPageChange,
        searchParams: isControlledData && propsSearchParams !== void 0 ? propsSearchParams : searchParams,
        onSearch: isControlledData && propsOnSearch ? propsOnSearch : onSearch,
        onReset: isControlledData && propsOnReset ? propsOnReset : onReset,
        fillHeight: ((_f = recordBoardGridProps.scroll) == null ? void 0 : _f.autoCalc) ?? true,
        grid: recordBoardGridProps,
        toolBar: (_g = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _g.toolBar,
        search: (_h = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _h.search,
        batchActionBar: {
          ...batchActionConfig,
          ...(_i = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _i.batchActionBar
        },
        floorMap: (_j = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _j.floorMap,
        defaultBodyView: (_k = currentConfig == null ? void 0 : currentConfig.childComponentProps) == null ? void 0 : _k.defaultBodyView
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.ShellFrame, null, /* @__PURE__ */ import_react.default.createElement(import_materials.PisellRecordBoard.GridLayout, null))
    )
  );
};
PisellSalesGrid.displayName = "PisellSalesGrid";
var PisellSalesGrid_default = PisellSalesGrid;
