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/components/scanOrder/components/Check/index.tsx
var Check_exports = {};
__export(Check_exports, {
  default: () => Check
});
module.exports = __toCommonJS(Check_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_Cart = __toESM(require("../Cart"));
var import_FulfillmentMode = __toESM(require("../FulfillmentMode"));
var import_ManualPickupRefModal = __toESM(require("../ManualPickupRefModal"));
var import_context = require("../../context");
var import_hooks = require("../../hooks");
var import_utils2 = require("@pisell/utils");
var import_dayjs = __toESM(require("dayjs"));
var import_index = require("./index.less");
function Check() {
  const { viewModel, runModuleAction, refreshViewModel, tableName, entryMode, clearStepCache, entryContext } = (0, import_context.useScanOrderContext)();
  const isAdditionalOrder = entryMode === "additional_order";
  const [submitting, setSubmitting] = (0, import_react.useState)(false);
  const [note, setNote] = (0, import_react.useState)((viewModel == null ? void 0 : viewModel.note) || "");
  const [pickupRefOpen, setPickupRefOpen] = (0, import_react.useState)(false);
  const [addOnConfirmOpen, setAddOnConfirmOpen] = (0, import_react.useState)(false);
  const utils = (0, import_hooks.contextUtils)();
  const [dineInConfig, setDineInConfig] = (0, import_react.useState)(null);
  const [channel, setChannel] = (0, import_react.useState)("");
  const getConfig = (0, import_react.useCallback)(async () => {
    const otherParams = await runModuleAction("getOtherParams");
    console.log("otherParams >>>>> ", otherParams);
    const dineInConfig2 = (otherParams == null ? void 0 : otherParams.dineInConfig) ?? {};
    setDineInConfig(dineInConfig2);
    setChannel((otherParams == null ? void 0 : otherParams.channel) ?? "");
  }, [runModuleAction]);
  (0, import_react.useEffect)(() => {
    getConfig();
  }, []);
  const isShowOrderNote = (0, import_react.useMemo)(() => {
    return dineInConfig == null ? void 0 : dineInConfig["sale.allow_order_notes"];
  }, [dineInConfig]);
  const noteTitle = (0, import_react.useMemo)(() => {
    return String(
      import_utils.locales.getText("pisell2.text.order-notes") || import_utils.locales.getText("pisell2.scan.order.note.title") || "备注"
    );
  }, []);
  const notePlaceholder = (0, import_react.useMemo)(() => {
    return String(
      import_utils.locales.getText("pisell2.text.add-order-notes") || import_utils.locales.getText("pisell2.scan.order.note.placeholder") || "请输入备注"
    );
  }, []);
  const currentTableText = (0, import_react.useMemo)(
    () => String(
      import_utils.locales.getText("pisell2.scan.order.current.table") || "Current table"
    ),
    []
  );
  const productsTitle = (0, import_react.useMemo)(
    () => String(import_utils.locales.getText("pisell2.scan.order.products.title") || "Products"),
    []
  );
  const addOnConfirmTitle = (0, import_react.useMemo)(
    () => String(
      import_utils.locales.getText("pisell2.scan.order.add.on.confirm.title") || "This table has already started ordering"
    ),
    []
  );
  const addOnConfirmDescription = (0, import_react.useMemo)(
    () => String(
      import_utils.locales.getText("pisell2.scan.order.add.on.confirm.description") || "Someone at your table has placed the order. This will be submitted as an add-on order."
    ),
    []
  );
  const addOnConfirmButtonText = (0, import_react.useMemo)(
    () => String(
      import_utils.locales.getText("pisell2.scan.order.add.on.confirm.button") || "Confirm Add-on Order"
    ),
    []
  );
  const addOnReturnButtonText = (0, import_react.useMemo)(
    () => String(
      import_utils.locales.getText("pisell2.scan.order.add.on.return.button") || "Return to Cart"
    ),
    []
  );
  const showCheckStepEmptyCartTip = () => {
    import_antd.message.error(import_utils.locales.getText("pisell2.scan.order.check.cart.empty.tip") || "Please go back to add products");
  };
  const showSubmitFailedTip = (0, import_react.useCallback)((tip) => {
    const content = String(tip || import_utils.locales.getText("pisell2.scan.order.submit.failed") || "Submit order failed");
    (0, import_materials.PisellToast)({ content });
  }, []);
  const showInventoryInsufficientModal = (0, import_react.useCallback)((error) => {
    var _a;
    setSubmitting(false);
    const unavailableProducts = Array.isArray((_a = error == null ? void 0 : error.data) == null ? void 0 : _a.unavailable_products) ? error.data.unavailable_products : [];
    const productNames = unavailableProducts.map((product) => String((product == null ? void 0 : product.title) || (product == null ? void 0 : product.product_id) || "").trim()).filter(Boolean);
    const title = String(
      import_utils.locales.getText("pisell2.scan.order.inventory.insufficient.title") || "Insufficient inventory"
    );
    const description = String(
      import_utils.locales.getText("pisell2.scan.order.inventory.insufficient.description") || "The following items are out of stock or do not have enough inventory. Please adjust your cart and try again."
    );
    const productsLabel = String(
      import_utils.locales.getText("pisell2.scan.order.inventory.insufficient.products.label") || "Unavailable products:"
    );
    const fallbackMessage = String((error == null ? void 0 : error.message) || description);
    import_antd.Modal.info({
      title,
      content: /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", null, description), /* @__PURE__ */ import_react.default.createElement("div", null, productsLabel), productNames.length > 0 ? /* @__PURE__ */ import_react.default.createElement("ul", null, productNames.map((name, index) => /* @__PURE__ */ import_react.default.createElement("li", { key: `${name}-${index}` }, name))) : /* @__PURE__ */ import_react.default.createElement("div", null, fallbackMessage)),
      okText: String(import_utils.locales.getText("pisell2.event.confirm") || "OK"),
      maskClosable: false
    });
  }, []);
  const doSubmit = async () => {
    var _a, _b, _c, _d, _e;
    const items = (viewModel == null ? void 0 : viewModel.cartItems) || [];
    if (items.length === 0) {
      showCheckStepEmptyCartTip();
      setSubmitting(false);
      return;
    }
    try {
      setSubmitting(true);
      await runModuleAction("updateTempOrderNote", note);
      const res = await runModuleAction("submitScanOrder");
      console.log("submitScanOrder >>>>> ", res);
      if ((res == null ? void 0 : res.status) === false) {
        if ((res == null ? void 0 : res.code) === 6008) {
          showInventoryInsufficientModal(res);
          return;
        }
        setSubmitting(false);
        showSubmitFailedTip(res == null ? void 0 : res.message);
        return;
      }
      const orderId = (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.order_id;
      const shouldPayOnSubmit = (dineInConfig == null ? void 0 : dineInConfig["sale.require_payment_on_submit"]) && !isAdditionalOrder;
      if (!orderId) {
        showSubmitFailedTip(res == null ? void 0 : res.message);
        return;
      }
      clearStepCache();
      const channelMap = {
        "scan_to_order": "table-order",
        "scan_to_order_2": "mobile_order",
        "scan_to_order_3": "scantoorder3"
      };
      const saleChannel = channelMap[channel] || channel;
      if (shouldPayOnSubmit) {
        setSubmitting(false);
        utils.action({
          type: "pisell1.payment",
          data: {
            order_id: orderId,
            total_amount: ((_b = res == null ? void 0 : res.data) == null ? void 0 : _b.order_wait_pay_amount) || ((_c = viewModel == null ? void 0 : viewModel.summary) == null ? void 0 : _c.total_amount),
            sale_channel: saleChannel
          },
          callback: async (_e2) => {
            try {
              await runModuleAction("restoreOrder");
            } catch (error) {
              console.warn("[scanOrder] restoreOrder after payment failed", error);
            }
          }
        });
      } else {
        try {
          await runModuleAction("restoreOrder");
        } catch (error) {
          console.warn("[scanOrder] restoreOrder before redirect failed", error);
        }
        const link = `/order/details?id=${orderId}`;
        if ((_d = utils == null ? void 0 : utils.history) == null ? void 0 : _d.replace) {
          utils.history.replace(link);
        } else if ((_e = utils == null ? void 0 : utils.history) == null ? void 0 : _e.push) {
          utils.history.push(link);
        } else {
          location.replace(link);
        }
        try {
          await runModuleAction("restoreOrder");
        } catch (error) {
          console.warn("[scanOrder] restoreOrder after payment failed", error);
        }
      }
      await refreshViewModel();
    } catch (error) {
      console.error("[scanOrder] submitScanOrder failed", error);
      if ((error == null ? void 0 : error.code) === 670005) {
        setSubmitting(false);
        showSubmitFailedTip(
          String(import_utils.locales.getText("pisell2.scan.order.settled.cannot.add.tip") || "")
        );
      } else if ((error == null ? void 0 : error.code) === 670007 && (entryContext == null ? void 0 : entryContext.resource_id)) {
        const reservationResourceSelectType = await runModuleAction("getReservationResourceSelectType");
        const allowAddItems = await runModuleAction("checkAllowAddItems");
        const res = await runModuleAction("syncAdditionalOrderFromResource", entryContext == null ? void 0 : entryContext.resource_id);
        if (reservationResourceSelectType.resourceSelectType === "single" && (allowAddItems == null ? void 0 : allowAddItems.enabled) && (res == null ? void 0 : res.matched)) {
          setSubmitting(false);
          setAddOnConfirmOpen(true);
        } else {
          setSubmitting(false);
          showSubmitFailedTip(error == null ? void 0 : error.message);
        }
      } else if ((error == null ? void 0 : error.code) === 6008) {
        showInventoryInsufficientModal(error);
      } else {
        setSubmitting(false);
        showSubmitFailedTip(error == null ? void 0 : error.message);
      }
    } finally {
    }
  };
  const handleSubmit = async () => {
    (0, import_utils2.sendWarningLog)({
      title: "新版扫码点餐下单",
      content: [
        {
          key: "路径",
          value: window.location.href
        },
        {
          key: "下单时间",
          value: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
        },
        {
          key: "前置字段",
          value: `submitting: ${submitting}, isAdditionalOrder: ${isAdditionalOrder}`
        },
        {
          key: "cartItems",
          value: JSON.stringify(viewModel == null ? void 0 : viewModel.cartItems)
        }
      ]
    });
    if (submitting) return;
    const cartItems = (viewModel == null ? void 0 : viewModel.cartItems) || [];
    if (cartItems.length === 0) {
      showCheckStepEmptyCartTip();
      return;
    }
    if (isAdditionalOrder) {
      await doSubmit();
      return;
    }
    try {
      setSubmitting(true);
      const manualPickup = await runModuleAction("checkManualPickupRef");
      if (manualPickup == null ? void 0 : manualPickup.enabled) {
        setPickupRefOpen(true);
        setSubmitting(false);
        return;
      }
    } catch (error) {
      console.error("[scanOrder] checkManualPickupRef failed", error);
      import_antd.message.error((error == null ? void 0 : error.message) || "Submit order failed");
      setSubmitting(false);
      (0, import_utils2.sendWarningLog)({
        title: "新版扫码点餐下单报错",
        content: [
          {
            key: "错误信息",
            value: error == null ? void 0 : error.message
          }
        ]
      });
      return;
    }
    await doSubmit();
  };
  const handlePickupRefConfirm = async (value) => {
    try {
      setSubmitting(true);
      await runModuleAction("setPickupRef", value);
    } catch (error) {
      console.error("[scanOrder] setPickupRef failed", error);
      import_antd.message.error((error == null ? void 0 : error.message) || "Submit order failed");
      setSubmitting(false);
      return;
    }
    setPickupRefOpen(false);
    await doSubmit();
  };
  const handlePickupRefCancel = () => {
    if (submitting) return;
    setPickupRefOpen(false);
  };
  const handleAddOnConfirm = async () => {
    if (submitting) return;
    setAddOnConfirmOpen(false);
    await doSubmit();
  };
  const handleAddOnReturn = () => {
    if (submitting) return;
    setAddOnConfirmOpen(false);
  };
  const noteContent = /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-note" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-note-title" }, noteTitle), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Input.TextArea,
    {
      value: note,
      placeholder: notePlaceholder,
      autoSize: { minRows: 4 },
      allowClear: true,
      onChange: (event) => {
        var _a;
        return setNote(((_a = event == null ? void 0 : event.target) == null ? void 0 : _a.value) || "");
      }
    }
  ));
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check" }, tableName ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-current-table" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-scan-order-check-current-table-label" }, currentTableText), /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-scan-order-check-current-table-value" }, tableName)) : null, !isAdditionalOrder ? /* @__PURE__ */ import_react.default.createElement(import_FulfillmentMode.default, null) : null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-products-title" }, productsTitle), /* @__PURE__ */ import_react.default.createElement(
    import_Cart.default,
    {
      embedded: true,
      open: true,
      onCancel: () => {
      },
      onNext: handleSubmit,
      items: (viewModel == null ? void 0 : viewModel.cartItems) || [],
      summary: (viewModel == null ? void 0 : viewModel.summary) || {},
      confirmLoading: submitting,
      extraContent: !isAdditionalOrder && isShowOrderNote ? noteContent : void 0
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_ManualPickupRefModal.default,
    {
      open: pickupRefOpen,
      confirmLoading: submitting,
      onCancel: handlePickupRefCancel,
      onConfirm: handlePickupRefConfirm
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Modal,
    {
      open: addOnConfirmOpen,
      footer: null,
      onCancel: handleAddOnReturn,
      maskClosable: false,
      destroyOnClose: true,
      centered: true,
      className: "pisell-scan-order-add-on-confirm-modal"
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-add-on-confirm-body" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-add-on-confirm-title" }, addOnConfirmTitle), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-add-on-confirm-desc" }, addOnConfirmDescription), /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "primary",
        block: true,
        size: "large",
        loading: submitting,
        onClick: handleAddOnConfirm
      },
      addOnConfirmButtonText
    ), /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        block: true,
        size: "large",
        disabled: submitting,
        onClick: handleAddOnReturn
      },
      addOnReturnButtonText
    ))
  ), submitting ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-loading-mask" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-loading-panel" }, /* @__PURE__ */ import_react.default.createElement(import_materials.PisellLoading, { loading: true, mask: { backgroundColor: "transparent", width: 64, height: 64 } }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-scan-order-check-loading-placeholder" })))) : null);
}
