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/saleDetail/hooks/useSaleDetailActions.ts
var useSaleDetailActions_exports = {};
__export(useSaleDetailActions_exports, {
  useCancelActionItem: () => useCancelActionItem,
  useCheckoutActionItem: () => useCheckoutActionItem,
  useEditActionItem: () => useEditActionItem,
  usePrintReceiptsActionItem: () => usePrintReceiptsActionItem,
  useSaleDetailActions: () => useSaleDetailActions
});
module.exports = __toCommonJS(useSaleDetailActions_exports);
var import_react = require("react");
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_selectors = require("../../salesSdk/selectors");
var DEFAULT_SALE_DETAIL_ACTIONS = ["checkout"];
var DEFAULT_ACTION_CONFIG = {
  checkout: {
    row: 1,
    order: 10,
    buttonProps: {
      size: "large"
    }
  },
  edit: {
    row: 2,
    order: 20,
    buttonProps: {
      size: "large"
    }
  },
  "print-receipts": {
    row: 2,
    order: 30,
    buttonProps: {
      size: "large"
    }
  },
  cancel: {
    row: 2,
    order: 40,
    buttonProps: {
      size: "large"
    }
  }
};
function toButtonGroupList(items) {
  const actionRows = items.filter((item) => !item.hidden).sort((prev, next) => (prev.order ?? 0) - (next.order ?? 0)).reduce((rows, item) => {
    const row = item.row ?? 1;
    rows[row] = rows[row] || [];
    rows[row].push(item);
    return rows;
  }, {});
  return Object.keys(actionRows).map(Number).sort((prev, next) => prev - next).map((row) => actionRows[row]).filter((rowItems) => rowItems.length > 0);
}
function getActionKey(action) {
  return typeof action === "string" ? action : action.name;
}
function getActionConfig(action) {
  return typeof action === "string" ? {} : action;
}
function mergeActionItem(item, config) {
  return {
    ...item,
    ...config,
    buttonProps: {
      ...item.buttonProps,
      ...config.buttonProps
    }
  };
}
function resolveSaleDetailOrderId(dataSource) {
  var _a, _b, _c;
  const id = ((_a = dataSource.sales.tempOrder) == null ? void 0 : _a.order_id) ?? ((_c = (_b = dataSource.sales.salesDetail) == null ? void 0 : _b.header) == null ? void 0 : _c.order_id);
  if (id == null || id === "") return void 0;
  if (typeof id === "number" && Number.isFinite(id)) return id;
  const value = String(id).trim();
  if (!value) return void 0;
  const numericId = Number(value);
  return Number.isFinite(numericId) && String(numericId) === value ? numericId : value;
}
function getSalesHostModule(pisellos) {
  var _a;
  return (_a = pisellos == null ? void 0 : pisellos.getModule) == null ? void 0 : _a.call(
    pisellos,
    "sales"
  );
}
function updateLocalOrder(action, orderId) {
  if (orderId == null || typeof action !== "function") return;
  action({
    type: "webpos.updateLocalOrderApi",
    data: {
      order_id: orderId
    }
  });
}
function useEditActionItem({
  dataSource
}) {
  var _a, _b, _c, _d;
  const context = (0, import_useEngineContext.default)();
  const action = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.action;
  const orderId = resolveSaleDetailOrderId(dataSource);
  const { disabledEdit } = (0, import_selectors.deriveDisabledEdit)(
    (_c = dataSource.sales.salesDetail) == null ? void 0 : _c.rootBooking,
    (_d = dataSource.sales.salesDetail) == null ? void 0 : _d.header
  );
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await dataSource.sales.refreshSalesDetail();
  }, [dataSource.sales, orderId]);
  const handleEdit = (0, import_react.useCallback)(() => {
    if (typeof action !== "function" || orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    action({
      type: "pisell1.handleOpenCachedEditBooking",
      data: {
        order_id: orderId
      },
      callback: () => {
        void refreshSaleDetail();
      }
    });
  }, [action, orderId, refreshSaleDetail]);
  return (0, import_react.useMemo)(
    () => ({
      id: "edit",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.edit"),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--edit",
        disabled: disabledEdit || orderId == null,
        icon: (0, import_react.createElement)(import_icons.EditOutlined),
        onClick: handleEdit
      }
    }),
    [disabledEdit, handleEdit, orderId]
  );
}
function usePrintReceiptsActionItem({
  dataSource
}) {
  var _a, _b, _c;
  const context = (0, import_useEngineContext.default)();
  const action = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.action;
  const printableData = ((_c = dataSource.sales.salesDetail) == null ? void 0 : _c.raw) ?? dataSource.sales.tempOrder;
  const handlePrintReceipts = (0, import_react.useCallback)(() => {
    if (typeof action !== "function" || !printableData) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    action({
      type: "webpos.handlePrint",
      data: {
        data: printableData,
        type: "0"
      },
      callback: () => {
      }
    });
  }, [action, printableData]);
  return (0, import_react.useMemo)(
    () => ({
      id: "print-receipts",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.print-receipts"),
        className: "pisell-sale-detail-button-actions__button",
        disabled: !printableData,
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
        onClick: handlePrintReceipts
      }
    }),
    [handlePrintReceipts, printableData]
  );
}
function useCancelActionItem({
  dataSource
}) {
  var _a, _b, _c, _d;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const context = (0, import_useEngineContext.default)();
  const action = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.action;
  const pisellos = (_d = (_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.pisellos;
  const orderId = resolveSaleDetailOrderId(dataSource);
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await dataSource.sales.refreshSalesDetail();
  }, [dataSource.sales, orderId]);
  const handleCancel = (0, import_react.useCallback)(() => {
    if (loading) return;
    import_antd.Modal.confirm({
      title: import_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-title"),
      okText: import_utils.locales.getText("pisell2.sale-detail.action.cancel-confirm-ok"),
      cancelText: import_utils.locales.getText(
        "pisell2.sale-detail.action.cancel-confirm-cancel"
      ),
      centered: true,
      okButtonProps: {
        danger: true
      },
      onOk: async () => {
        if (orderId == null) {
          import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
          return;
        }
        const salesModule = getSalesHostModule(pisellos);
        const cancelOrder = salesModule == null ? void 0 : salesModule.cancelOrder;
        if (typeof cancelOrder !== "function") {
          import_antd.message.error(
            import_utils.locales.getText("pisell2.sale-detail.cancel-order-unavailable")
          );
          return;
        }
        try {
          setLoading(true);
          await cancelOrder.call(salesModule, [orderId]);
          updateLocalOrder(action, orderId);
          await refreshSaleDetail();
          import_antd.message.success(
            import_utils.locales.getText("pisell2.sale-detail.cancel-order-success")
          );
        } catch (error) {
          import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
        } finally {
          setLoading(false);
        }
      }
    });
  }, [action, loading, orderId, pisellos, refreshSaleDetail]);
  return (0, import_react.useMemo)(
    () => ({
      id: "cancel",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.cancel"),
        className: "pisell-sale-detail-button-actions__button",
        danger: true,
        disabled: orderId == null,
        icon: (0, import_react.createElement)(import_icons.CloseCircleOutlined),
        loading,
        onClick: handleCancel
      }
    }),
    [handleCancel, loading, orderId]
  );
}
function useCheckoutActionItem({
  dataSource
}) {
  var _a;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const tempOrder = dataSource.sales.tempOrder;
  const orderId = resolveSaleDetailOrderId(dataSource);
  const summary = (_a = dataSource.summary) == null ? void 0 : _a.summary;
  const isPaid = (tempOrder == null ? void 0 : tempOrder.payment_status) === "paid";
  const checkoutDisabledByAmount = summary ? Number(summary.total_refund_amount) > 0 || Number(summary.total_amount) <= 0 || Number(summary.expect_amount) <= 0 : false;
  const refreshSaleDetail = (0, import_react.useCallback)(async () => {
    await dataSource.sales.refreshSalesDetail();
  }, [dataSource.sales, orderId]);
  const handleCheckout = (0, import_react.useCallback)(async () => {
    setLoading(true);
    try {
      await dataSource.sales.openCheckout();
      await refreshSaleDetail();
    } finally {
      setLoading(false);
    }
  }, [dataSource.sales, refreshSaleDetail]);
  return (0, import_react.useMemo)(
    () => ({
      id: "checkout",
      hidden: isPaid,
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.text.checkout"),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--primary",
        type: "primary",
        loading,
        disabled: !dataSource.sales.isReady || loading || checkoutDisabledByAmount,
        icon: (0, import_react.createElement)(import_materials.Iconfont, { type: "pisell2-coins-hand" }),
        onClick: handleCheckout
      }
    }),
    [
      checkoutDisabledByAmount,
      dataSource.sales.isReady,
      handleCheckout,
      isPaid,
      loading
    ]
  );
}
function useSaleDetailActions({
  dataSource,
  actions = DEFAULT_SALE_DETAIL_ACTIONS
}) {
  var _a;
  const editAction = useEditActionItem({ dataSource });
  const printReceiptsAction = usePrintReceiptsActionItem({ dataSource });
  const cancelAction = useCancelActionItem({ dataSource });
  const checkoutAction = useCheckoutActionItem({ dataSource });
  const isCancelled = ((_a = dataSource.sales.tempOrder) == null ? void 0 : _a.status) === "cancelled";
  return (0, import_react.useMemo)(() => {
    if (isCancelled) return [];
    const actionItemMap = {
      edit: editAction,
      "print-receipts": printReceiptsAction,
      cancel: cancelAction,
      checkout: checkoutAction
    };
    const saleDetailActions = actions.map((action) => {
      const actionKey = getActionKey(action);
      const config = {
        ...DEFAULT_ACTION_CONFIG[actionKey],
        ...getActionConfig(action),
        buttonProps: {
          ...DEFAULT_ACTION_CONFIG[actionKey].buttonProps,
          ...getActionConfig(action).buttonProps
        }
      };
      return mergeActionItem(actionItemMap[actionKey], config);
    });
    return toButtonGroupList(saleDetailActions);
  }, [
    actions,
    cancelAction,
    checkoutAction,
    editAction,
    isCancelled,
    printReceiptsAction
  ]);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useCancelActionItem,
  useCheckoutActionItem,
  useEditActionItem,
  usePrintReceiptsActionItem,
  useSaleDetailActions
});
