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,
  useMachineCodePrintActionItems: () => useMachineCodePrintActionItems,
  useMoreActionItem: () => useMoreActionItem,
  usePrintActionItem: () => usePrintActionItem,
  usePrintAllActionItem: () => usePrintAllActionItem,
  usePrintProductVoucherActionItem: () => usePrintProductVoucherActionItem,
  usePrintReceiptsActionItem: () => usePrintReceiptsActionItem,
  usePrintWristbandActionItem: () => usePrintWristbandActionItem,
  useRefundActionItem: () => useRefundActionItem,
  useReturnActionItem: () => useReturnActionItem,
  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_serve = require("../serve");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_selectors = require("../../salesSdk/selectors");
var PisellAmount = import_materials.PisellText.Amount;
var WRISTBAND_TAGS = ["ticket", "product_package_ticket", "appointment_ticket", "session_ticket"];
var DEFAULT_SALE_DETAIL_ACTIONS = ["checkout"];
var DEFAULT_ACTION_CONFIG = {
  checkout: {
    row: 2,
    order: 20,
    buttonProps: {
      size: "large"
    }
  },
  refund: {
    row: 1,
    order: 10,
    buttonProps: {
      size: "large"
    }
  },
  return: {
    row: 1,
    order: 20,
    buttonProps: {
      size: "large"
    }
  },
  edit: {
    row: 1,
    order: 30,
    buttonProps: {
      size: "large"
    }
  },
  print: {
    row: 1,
    order: 20,
    buttonProps: {
      size: "large"
    }
  },
  "print-product-voucher": {
    row: 3,
    order: 10,
    buttonProps: {
      size: "large"
    }
  },
  "print-receipts": {
    row: 3,
    order: 30,
    buttonProps: {
      size: "large"
    }
  },
  "print-wristband": {
    row: 3,
    order: 20,
    buttonProps: {
      size: "large"
    }
  },
  "print-all": {
    row: 3,
    order: 40,
    buttonProps: {
      size: "large"
    }
  },
  cancel: {
    row: 3,
    order: 30,
    buttonProps: {
      size: "large"
    }
  },
  more: {
    row: 2,
    order: 10,
    buttonProps: {
      size: "large"
    }
  }
};
var WRISTBAND_PRINT_TAGS = [
  "ticket",
  "product_package_ticket",
  "appointment_ticket",
  "session_ticket"
];
function hasWristbandVoucher(dataSource) {
  var _a;
  const vouchers = (_a = dataSource.sales.tempOrder) == null ? void 0 : _a.vouchers;
  return Array.isArray(vouchers) ? vouchers.some(
    (voucher) => WRISTBAND_PRINT_TAGS.includes(String((voucher == null ? void 0 : voucher.tag) || ""))
  ) : false;
}
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 toDropdownMenuItem(item) {
  const { buttonProps } = item;
  return {
    key: item.id,
    label: buttonProps == null ? void 0 : buttonProps.children,
    icon: buttonProps == null ? void 0 : buttonProps.icon,
    danger: buttonProps == null ? void 0 : buttonProps.danger,
    disabled: Boolean((buttonProps == null ? void 0 : buttonProps.disabled) || (buttonProps == null ? void 0 : buttonProps.loading)),
    onClick: buttonProps == null ? void 0 : buttonProps.onClick,
    children: item.isMore ? item.menuData : void 0
  };
}
function getSortedVisibleActionItems(items) {
  return items.filter((item) => !item.hidden).sort((prev, next) => (prev.order ?? 0) - (next.order ?? 0));
}
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 hasOwnValue(record, key) {
  return record[key] !== void 0 && record[key] !== null;
}
function getSaleDetailPrintSource(dataSource) {
  var _a;
  return ((_a = dataSource.sales.salesDetail) == null ? void 0 : _a.raw) ?? dataSource.sales.tempOrder ?? {};
}
function getArrayValue(record, key) {
  const value = record[key];
  return Array.isArray(value) ? value : void 0;
}
function buildSaleDetailPrintData(dataSource, orderId) {
  const source = getSaleDetailPrintSource(dataSource);
  const paymentInfo = source.payment_info;
  const printData = {
    order_id: orderId
  };
  if (hasOwnValue(source, "machine_code_print_info")) {
    printData.machine_code_print_info = source.machine_code_print_info;
  }
  if (hasOwnValue(source, "machine_code_print_info_v2")) {
    printData.machine_code_print_info_v2 = source.machine_code_print_info_v2;
  }
  if (hasOwnValue(source, "small_ticket_data")) {
    printData.small_ticket_data = source.small_ticket_data;
  } else if (paymentInfo && hasOwnValue(paymentInfo, "small_ticket_data")) {
    printData.small_ticket_data = paymentInfo.small_ticket_data;
  }
  if (hasOwnValue(source, "voucher_ids")) {
    printData.voucher_ids = source.voucher_ids;
  }
  return printData;
}
function buildSaleDetailWristbandPrintData(dataSource, orderId) {
  const source = getSaleDetailPrintSource(dataSource);
  const machineCodePrintInfoV2 = getArrayValue(
    source,
    "machine_code_print_info_v2"
  );
  const voucherIds = getArrayValue(source, "voucher_ids");
  const printData = {
    order_id: orderId
  };
  if (voucherIds == null ? void 0 : voucherIds.length) {
    printData.voucher_ids = voucherIds;
    return printData;
  }
  const wristbandPrintInfo = machineCodePrintInfoV2 == null ? void 0 : machineCodePrintInfoV2.filter(
    (item) => WRISTBAND_PRINT_TAGS.includes(String((item == null ? void 0 : item.tag) || ""))
  );
  if (wristbandPrintInfo == null ? void 0 : wristbandPrintInfo.length) {
    printData.machine_code_print_info_v2 = wristbandPrintInfo;
  }
  return printData;
}
function isPrintSuccessful(result) {
  return (result == null ? void 0 : result.status) === "success" || (result == null ? void 0 : result.result) === true;
}
function useEditBookingAction({
  dataSource,
  getRemotePrintActionsData
}) {
  var _a, _b, _c, _d, _e, _f, _g;
  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 businessCode = ((_c = dataSource.sales.tempOrder) == null ? void 0 : _c.business_code) || ((_e = (_d = dataSource.sales.salesDetail) == null ? void 0 : _d.raw) == null ? void 0 : _e.business_code);
  const { disabledEdit } = (0, import_selectors.deriveDisabledEdit)(
    (_f = dataSource.sales.salesDetail) == null ? void 0 : _f.rootBooking,
    (_g = dataSource.sales.salesDetail) == null ? void 0 : _g.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.handleOpenCachedBigSale",
      data: {
        order_id: orderId,
        business_code: businessCode
      },
      callback: () => {
        void refreshSaleDetail();
        void (getRemotePrintActionsData == null ? void 0 : getRemotePrintActionsData());
      }
    });
  }, [action, getRemotePrintActionsData, orderId, refreshSaleDetail]);
  return {
    disabled: disabledEdit || orderId == null,
    handleEdit
  };
}
function useEditActionItem({
  dataSource,
  getRemotePrintActionsData
}) {
  const { disabled, handleEdit } = useEditBookingAction({
    dataSource,
    getRemotePrintActionsData
  });
  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,
        icon: (0, import_react.createElement)(import_icons.EditOutlined),
        onClick: handleEdit
      }
    }),
    [disabled, handleEdit]
  );
}
function useReturnActionItem({
  dataSource,
  getRemotePrintActionsData
}) {
  const { disabled, handleEdit } = useEditBookingAction({
    dataSource,
    getRemotePrintActionsData
  });
  return (0, import_react.useMemo)(
    () => ({
      id: "return",
      buttonProps: {
        block: true,
        children: (0, import_react.createElement)(
          "span",
          { className: "pisell-sale-detail-button-actions__return-label" },
          import_utils.locales.getText("pisell2.sale-detail.action.return-item")
        ),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--return",
        disabled,
        icon: (0, import_react.createElement)(import_icons.RollbackOutlined),
        onClick: handleEdit
      }
    }),
    [disabled, handleEdit]
  );
}
function useRefundActionItem({
  dataSource
}) {
  var _a, _b;
  const context = (0, import_useEngineContext.default)();
  const NativePage = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.NativePage;
  const orderId = resolveSaleDetailOrderId(dataSource);
  const handleRefund = (0, import_react.useCallback)(() => {
    if (orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
      return;
    }
    const nativePage = typeof NativePage === "function" ? NativePage() : void 0;
    if (typeof (nativePage == null ? void 0 : nativePage.open) !== "function") {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    nativePage.open({
      page: "/native/order/refund",
      params: {
        order_id: orderId
      }
    });
  }, [NativePage, orderId]);
  return (0, import_react.useMemo)(
    () => ({
      id: "refund",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.refund"),
        className: "pisell-sale-detail-button-actions__button",
        disabled: orderId == null || typeof NativePage !== "function",
        icon: (0, import_react.createElement)(import_icons.UndoOutlined),
        onClick: handleRefund
      }
    }),
    [NativePage, handleRefund, orderId]
  );
}
function useSaleDetailPrintAction(dataSource, printType, buildPrintData = buildSaleDetailPrintData) {
  var _a, _b;
  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 orderId = resolveSaleDetailOrderId(dataSource);
  const handlePrint = (0, import_react.useCallback)(() => {
    if (loading) return;
    if (orderId == null) {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.missing-order-id"));
      return;
    }
    if (typeof action !== "function") {
      import_antd.message.error(import_utils.locales.getText("pisell2.sale-detail.action-unavailable"));
      return;
    }
    setLoading(true);
    try {
      action({
        type: "webpos.handlePrint",
        data: {
          type: printType,
          data: buildPrintData(dataSource, orderId)
        },
        callback: (result) => {
          setLoading(false);
          if (isPrintSuccessful(result)) return;
        }
      });
    } catch {
      setLoading(false);
    }
  }, [action, buildPrintData, dataSource, loading, orderId, printType]);
  return {
    disabled: orderId == null || typeof action !== "function" || loading,
    handlePrint,
    loading
  };
}
function usePrintReceiptsActionItem({
  dataSource
}) {
  const { disabled, handlePrint, loading } = useSaleDetailPrintAction(
    dataSource,
    "INVOICE" /* INVOICE */
  );
  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,
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
        loading,
        onClick: handlePrint
      }
    }),
    [disabled, handlePrint, loading]
  );
}
function usePrintActionItem() {
  return (0, import_react.useMemo)(
    () => ({
      id: "print",
      isMore: true,
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.print"),
        className: "pisell-sale-detail-button-actions__button",
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined)
      }
    }),
    []
  );
}
function usePrintProductVoucherActionItem({
  dataSource
}) {
  const { disabled, handlePrint, loading } = useSaleDetailPrintAction(
    dataSource,
    "WALLET" /* WALLET */
  );
  return (0, import_react.useMemo)(
    () => ({
      id: "print-product-voucher",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText(
          "pisell2.sale-detail.action.print-product-voucher"
        ),
        className: "pisell-sale-detail-button-actions__button",
        disabled,
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
        loading,
        onClick: handlePrint
      }
    }),
    [disabled, handlePrint, loading]
  );
}
function useMachineCodePrintActionItems({
  dataSource,
  machineCodePrintActions = []
}) {
  var _a, _b, _c, _d;
  const [loadingTag, setLoadingTag] = (0, import_react.useState)();
  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 getData = (_d = (_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.getData;
  const orderId = resolveSaleDetailOrderId(dataSource);
  const handlePrintMachineCode = (0, import_react.useCallback)(
    async (printAction) => {
      const tag = String(printAction.tag || "").trim();
      console.log(printAction, "printAction xxxxx");
      if (!tag || loadingTag) return;
      if (orderId == null) {
        return;
      }
      if (typeof action !== "function" || typeof getData !== "function") {
        return;
      }
      setLoadingTag(tag);
      try {
        action({
          type: "webpos.handlePrint",
          data: {
            type: "WALLET" /* WALLET */,
            data: {
              order_id: orderId,
              machine_code_print_info_v2: [printAction]
            }
          },
          callback: () => {
            setLoadingTag(void 0);
          }
        });
      } catch (error) {
        setLoadingTag(void 0);
        import_antd.message.error(String((error == null ? void 0 : error.message) ?? error));
      }
    },
    [action, getData, loadingTag, orderId]
  );
  return (0, import_react.useMemo)(
    () => machineCodePrintActions.map((printAction, index) => {
      const tag = String((printAction == null ? void 0 : printAction.tag) || "").trim();
      if (!tag || WRISTBAND_TAGS.includes(tag)) return void 0;
      return {
        id: `print-machine-code-${tag}-${index}`,
        order: 10 + index,
        buttonProps: {
          block: true,
          children: printAction.name || import_utils.locales.getText(
            "pisell2.sale-detail.action.print-product-voucher"
          ),
          className: "pisell-sale-detail-button-actions__button",
          disabled: orderId == null || typeof action !== "function" || typeof getData !== "function" || Boolean(loadingTag && loadingTag !== tag),
          icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
          loading: loadingTag === tag,
          onClick: () => {
            void handlePrintMachineCode(printAction);
          }
        }
      };
    }).filter(Boolean),
    [
      action,
      getData,
      handlePrintMachineCode,
      loadingTag,
      machineCodePrintActions,
      orderId
    ]
  );
}
function usePrintWristbandActionItem({
  dataSource
}) {
  var _a, _b;
  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 getData = context.appHelper.utils.getData;
  const { disabled, loading } = useSaleDetailPrintAction(
    dataSource,
    "WRISTBAND" /* WRISTBAND */,
    buildSaleDetailWristbandPrintData
  );
  const orderId = resolveSaleDetailOrderId(dataSource);
  const shouldShowWristbandPrint = hasWristbandVoucher(dataSource);
  const handlePrintWristband = (0, import_react.useCallback)(async () => {
    const res = await (0, import_serve.getWristbandList)(
      { order_id: orderId },
      { headers: { "Shop-Id": getData("shop_id") } }
    );
    const voucherIds = Array.isArray(res.list) ? res.list.map((item) => item.id) : [];
    action({
      type: "webpos.handlePrint",
      data: {
        type: "WRISTBAND" /* WRISTBAND */,
        data: {
          order_id: orderId,
          voucher_ids: voucherIds
        }
      }
    });
  }, [action, getData, orderId]);
  return (0, import_react.useMemo)(
    () => ({
      id: "print-wristband",
      hidden: !shouldShowWristbandPrint,
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.print-wristband"),
        className: "pisell-sale-detail-button-actions__button",
        disabled,
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
        loading,
        onClick: handlePrintWristband
      }
    }),
    [disabled, handlePrintWristband, loading, shouldShowWristbandPrint]
  );
}
function usePrintAllActionItem({
  dataSource
}) {
  const { disabled, handlePrint, loading } = useSaleDetailPrintAction(
    dataSource,
    "PRINT_ALL" /* PRINT_ALL */
  );
  return (0, import_react.useMemo)(
    () => ({
      id: "print-all",
      buttonProps: {
        block: true,
        children: import_utils.locales.getText("pisell2.sale-detail.action.print-all"),
        className: "pisell-sale-detail-button-actions__button",
        disabled,
        icon: (0, import_react.createElement)(import_icons.PrinterOutlined),
        loading,
        onClick: handlePrint
      }
    }),
    [disabled, handlePrint, loading]
  );
}
function useMoreActionItem({
  printReceiptsAction,
  printWristbandAction,
  cancelAction
}) {
  return (0, import_react.useMemo)(
    () => ({
      id: "more",
      isMore: true,
      buttonProps: {
        block: true,
        className: "pisell-sale-detail-button-actions__button"
      },
      menuData: [
        toDropdownMenuItem(printReceiptsAction),
        toDropdownMenuItem(printWristbandAction),
        toDropdownMenuItem(cancelAction)
      ]
    }),
    [cancelAction, printReceiptsAction, printWristbandAction]
  );
}
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 amountGap = (summary == null ? void 0 : summary.amount_gap) ?? 0;
  const expectAmount = (summary == null ? void 0 : summary.expect_amount) ?? 0;
  const orderPaidAmount = Number((summary == null ? void 0 : summary.order_paid_amount) ?? 0);
  const amountDue = orderPaidAmount > 0 ? amountGap : expectAmount;
  const shouldShowCheckout = Number(amountDue) > 0;
  const isPaid = (tempOrder == null ? void 0 : tempOrder.payment_status) === "paid";
  const orderStatus = tempOrder == null ? void 0 : tempOrder.status;
  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: !shouldShowCheckout,
      buttonProps: {
        block: true,
        children: (0, import_react.createElement)(
          "span",
          { className: "pisell-sale-detail-button-actions__checkout-content" },
          (0, import_react.createElement)(
            "span",
            { className: "pisell-sale-detail-button-actions__checkout-title" },
            import_utils.locales.getText("pisell2.sale-detail.action.collect-money")
          ),
          (0, import_react.createElement)(
            "span",
            { className: "pisell-sale-detail-button-actions__checkout-amount" },
            import_utils.locales.getText("pisell2.sale-detail.action.amount-due"),
            " ",
            (0, import_react.createElement)(PisellAmount, { value: amountDue })
          )
        ),
        className: "pisell-sale-detail-button-actions__button pisell-sale-detail-button-actions__button--primary",
        type: "primary",
        loading,
        disabled: orderId == null || loading || checkoutDisabledByAmount || isPaid || orderStatus === "cancelled",
        // icon: createElement(Iconfont, { type: 'pisell2-coins-hand' }),
        onClick: handleCheckout
      }
    }),
    [
      amountDue,
      checkoutDisabledByAmount,
      handleCheckout,
      isPaid,
      loading,
      orderId,
      orderStatus,
      shouldShowCheckout
    ]
  );
}
function useSaleDetailActions({
  dataSource,
  actions = DEFAULT_SALE_DETAIL_ACTIONS,
  machineCodePrintActions = [],
  getRemotePrintActionsData
}) {
  var _a;
  const editAction = useEditActionItem({
    dataSource,
    getRemotePrintActionsData
  });
  const refundAction = useRefundActionItem({ dataSource });
  const returnAction = useReturnActionItem({
    dataSource,
    getRemotePrintActionsData
  });
  const printAction = usePrintActionItem();
  const printProductVoucherAction = usePrintProductVoucherActionItem({
    dataSource
  });
  const machineCodePrintActionItems = useMachineCodePrintActionItems({
    dataSource,
    machineCodePrintActions
  });
  const printReceiptsAction = usePrintReceiptsActionItem({ dataSource });
  const printWristbandAction = usePrintWristbandActionItem({ dataSource });
  const printAllAction = usePrintAllActionItem({ dataSource });
  const cancelAction = useCancelActionItem({ dataSource });
  const checkoutAction = useCheckoutActionItem({ dataSource });
  const moreAction = useMoreActionItem({
    printReceiptsAction,
    printWristbandAction,
    cancelAction
  });
  const isCancelled = ((_a = dataSource.sales.tempOrder) == null ? void 0 : _a.status) === "cancelled";
  return (0, import_react.useMemo)(() => {
    if (isCancelled) return [];
    const actionItemMap = {
      edit: editAction,
      refund: refundAction,
      return: returnAction,
      print: printAction,
      "print-product-voucher": printProductVoucherAction,
      "print-receipts": printReceiptsAction,
      "print-wristband": printWristbandAction,
      "print-all": printAllAction,
      cancel: cancelAction,
      checkout: checkoutAction,
      more: moreAction
    };
    const resolveActionItem = (action) => {
      var _a2;
      const actionKey = getActionKey(action);
      const actionConfig = getActionConfig(action);
      const config = {
        ...DEFAULT_ACTION_CONFIG[actionKey],
        ...actionConfig,
        buttonProps: {
          ...DEFAULT_ACTION_CONFIG[actionKey].buttonProps,
          ...actionConfig.buttonProps
        }
      };
      const actionItem = mergeActionItem(actionItemMap[actionKey], config);
      if (!((_a2 = config.items) == null ? void 0 : _a2.length)) return actionItem;
      const nestedActionItems = getSortedVisibleActionItems([
        ...actionKey === "print" ? machineCodePrintActionItems : [],
        ...config.items.map(resolveActionItem)
      ]);
      if (nestedActionItems.length === 1) {
        return {
          ...nestedActionItems[0],
          row: actionItem.row,
          order: actionItem.order
        };
      }
      const menuData = nestedActionItems.map(toDropdownMenuItem);
      return {
        ...actionItem,
        isMore: true,
        menuData
      };
    };
    const saleDetailActions = actions.map(resolveActionItem);
    return toButtonGroupList(saleDetailActions);
  }, [
    actions,
    cancelAction,
    checkoutAction,
    editAction,
    isCancelled,
    machineCodePrintActionItems,
    machineCodePrintActions,
    moreAction,
    printAction,
    printAllAction,
    printProductVoucherAction,
    printReceiptsAction,
    printWristbandAction,
    refundAction,
    returnAction
  ]);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useCancelActionItem,
  useCheckoutActionItem,
  useEditActionItem,
  useMachineCodePrintActionItems,
  useMoreActionItem,
  usePrintActionItem,
  usePrintAllActionItem,
  usePrintProductVoucherActionItem,
  usePrintReceiptsActionItem,
  usePrintWristbandActionItem,
  useRefundActionItem,
  useReturnActionItem,
  useSaleDetailActions
});
