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_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_index = require("./index.less");
function Check() {
  const { viewModel, runModuleAction, refreshViewModel, tableName, entryMode, clearStepCache } = (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 utils = (0, import_hooks.contextUtils)();
  const [dineInConfig, setDineInConfig] = (0, import_react.useState)(null);
  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);
  }, [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 showCheckStepEmptyCartTip = () => {
    import_antd.message.error(import_utils.locales.getText("pisell2.scan.order.check.cart.empty.tip") || "Please go back to add products");
  };
  const doSubmit = async () => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    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);
      clearStepCache();
      if ((dineInConfig == null ? void 0 : dineInConfig["sale.require_payment_on_submit"]) && !isAdditionalOrder) {
        try {
          await runModuleAction("restoreOrder");
        } catch (error) {
          console.warn("[scanOrder] restoreOrder after payment failed", error);
        }
        utils.action({
          type: "pisell1.payment",
          data: {
            order_id: (_a = res == null ? void 0 : res.data) == null ? void 0 : _a.order_id,
            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: "table-order"
            // TODO 因为渠道问题，现在只能先写死，等 2.0 有支付和渠道统一规划以后可以做动态
          },
          callback: async (_e2) => {
          }
        });
      } else {
        if ((_d = res == null ? void 0 : res.data) == null ? void 0 : _d.order_id) {
          try {
            await runModuleAction("restoreOrder");
          } catch (error) {
            console.warn("[scanOrder] restoreOrder before redirect failed", error);
          }
          const link = `/order/details?id=${(_e = res == null ? void 0 : res.data) == null ? void 0 : _e.order_id}`;
          const app = (_f = utils == null ? void 0 : utils.getApp) == null ? void 0 : _f.call(utils);
          if ((_g = app == null ? void 0 : app.history) == null ? void 0 : _g.replace) {
            app.history.replace(link);
          } else if ((_h = app == null ? void 0 : app.history) == null ? void 0 : _h.push) {
            app.history.push(link);
          } else {
            location.replace(link);
          }
        }
      }
      await refreshViewModel();
    } catch (error) {
      console.error("[scanOrder] submitScanOrder failed", error);
      import_antd.message.error((error == null ? void 0 : error.message) || "Submit order failed");
    } finally {
      setSubmitting(false);
    }
  };
  const handleSubmit = async () => {
    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);
      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 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
    }
  ));
}
