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/eventBooking/components/Provider/Cart/ContinueButton/index.tsx
var ContinueButton_exports = {};
__export(ContinueButton_exports, {
  default: () => ContinueButton_default
});
module.exports = __toCommonJS(ContinueButton_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_Sales = require("../../../../../Sales");
var import_utils2 = require("../../../../../Sales/Checkout/utils");
var import_OrderProductModal = __toESM(require("../../OrderProductModal/index"));
var import_EmptyHolderModal = __toESM(require("../../EmptyHolderModal"));
var import_serve = require("../../../../../Sales/Event/serve");
var import_ahooks = require("ahooks");
var import_useEngineContext = __toESM(require("../../../../../../hooks/useEngineContext"));
var import_index = require("./index.less");
var import_utils3 = require("../../../../../appointmentBooking/utils");
var ContinueButton = () => {
  var _a, _b, _c, _d, _e;
  const hasSubscribedRef = (0, import_react.useRef)(false);
  const { data } = (0, import_Sales.useSales)();
  const { onHolderOpen } = (0, import_Sales.useHolder)();
  const { checkHolder, onCloseCart, cartData, getWithoutCartItemsHolderNames } = (0, import_Sales.useCart)();
  const { currentStepData, nextStep, isLastStep } = (0, import_Sales.useStep)();
  const {
    onCheckout,
    createBooking,
    onCheckBeforeBooking,
    checkBeforeBooking,
    freePay
  } = (0, import_Sales.useCheckout)();
  const { openLoginModal, isLogin } = (0, import_Sales.useCustomer)();
  const { deposit, isAgreeDepositPolicy } = (0, import_Sales.useSummary)();
  const [openCheckout, setOpenCheckout] = (0, import_react.useState)(false);
  const [checkedNumber, setCheckedNumber] = (0, import_react.useState)(0);
  const [openEmptyHolder, setOpenEmptyHolder] = (0, import_react.useState)(false);
  const { setData, removeSessionStorage } = (0, import_Sales.useSales)();
  const context = (0, import_useEngineContext.default)();
  const config = ((_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.constants) == null ? void 0 : _b.config) || {};
  const utils = ((_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils) || {};
  const { pubsub } = context.appHelper.utils;
  const { store, action, getStore } = ((_d = context.appHelper) == null ? void 0 : _d.utils) || {};
  const handleCheckout = async () => {
    const params = (0, import_utils2.getFormParams)(data);
    action == null ? void 0 : action({
      type: "pisell1.goProductForm",
      data: params,
      callback: async (e) => {
        var _a2, _b2, _c2;
        if ((e == null ? void 0 : e.type) === "close") {
          return;
        }
        const value = (0, import_utils2.formatValues)({
          state: data,
          platform: (_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.constants) == null ? void 0 : _b2.platform,
          excludeDisabled: false,
          extra: {
            relation_forms: e
          }
        });
        const result = await onCheckout(value);
        if (result == null ? void 0 : result.success) {
          removeSessionStorage();
        } else {
          (0, import_materials.PisellToast)({
            content: ((_c2 = result == null ? void 0 : result.err) == null ? void 0 : _c2.message) || ""
          });
        }
      }
    });
  };
  const _getProductPrice = (0, import_ahooks.useRequest)(import_serve.getProductPrice, {
    manual: true,
    onSuccess: (res) => {
      const list = res.data || [];
      const productById = list.reduce((pre, cur) => {
        pre[cur.id] = cur;
        return pre;
      }, {});
      console.log("start update price");
      const newCartItems = cartData.cartItems.map((item) => {
        var _a2;
        const { product } = item._originData || {};
        let newProduct = productById[product.product_id];
        let _totalPrice = Number(newProduct.price);
        if (!(item == null ? void 0 : item._productDetail)) {
          item.price = _totalPrice;
          item.total = _totalPrice;
          return item;
        }
        const { bundle = [], options } = item._productDetail;
        if (
          // 1. 套餐商品
          Array.isArray(product == null ? void 0 : product.product_bundle) && product.product_bundle.length > 0
        ) {
          const { bundle_group = [] } = newProduct;
          for (let i = 0; i < product.product_bundle.length; i++) {
            const pbItem = product.product_bundle[i];
            const { bundle_group_id, bundle_id, option } = pbItem;
            const _originBundleItemInfo = bundle.find(
              (bi) => bi.id === bundle_id
            );
            const _targetBundleGroup = bundle_group.find(
              (bg) => bg.id === bundle_group_id
            );
            if ((_a2 = _targetBundleGroup == null ? void 0 : _targetBundleGroup.bundle_item) == null ? void 0 : _a2.length) {
              let _newBundleItemInfo = _targetBundleGroup.bundle_item.find(
                (bi) => bi.id === bundle_id
              );
              if ((_originBundleItemInfo == null ? void 0 : _originBundleItemInfo._bundle_product_id) === (_newBundleItemInfo == null ? void 0 : _newBundleItemInfo.bundle_product_id)) {
                const {
                  price_type,
                  num = 1,
                  option: _originBundleItemOptions
                } = _originBundleItemInfo;
                const _bundleItemPrice = Number(_newBundleItemInfo.price);
                if (price_type === "markup") {
                  _totalPrice += _bundleItemPrice * num;
                } else if (price_type === "markdown") {
                  _totalPrice -= _bundleItemPrice * num;
                } else {
                  _totalPrice += _bundleItemPrice * num;
                }
                if (Array.isArray(option) && (option == null ? void 0 : option.length) > 0) {
                  for (let j = 0; j < option.length; j++) {
                    const { option_group_item_id } = option[j];
                    const _originOptionItem = _originBundleItemOptions.find(
                      (op) => op.product_option_item_id === option_group_item_id
                    );
                    if (_originOptionItem) {
                      const { price, num: _optionNum = 1 } = _originOptionItem;
                      _totalPrice += Number(price) * _optionNum;
                    }
                  }
                }
              }
            }
          }
        } else {
          if (product == null ? void 0 : product.product_variant_id) {
            const { variant = [] } = newProduct;
            const _variant = variant.find(
              (v) => v.id === product.product_variant_id
            );
            if (_variant) {
              _totalPrice = Number(_variant.price);
            }
          }
          if (Array.isArray(product == null ? void 0 : product.product_option_item) && product.product_option_item.length > 0) {
            for (let i = 0; i < product.product_option_item.length; i++) {
              const { option_group_item_id } = product.product_option_item[i];
              const _originOptionItem = options.find(
                (op) => op.product_option_item_id === option_group_item_id
              );
              if (_originOptionItem) {
                const { price, num = 1 } = _originOptionItem;
                _totalPrice += Number(price) * num;
              }
            }
          }
        }
        item.price = _totalPrice;
        item.total = _totalPrice;
        return item;
      });
      console.log("new cart data", newCartItems);
      setData({
        cartData: {
          ...cartData,
          cartItems: newCartItems
        }
      });
    }
  });
  const getCartItemProductsWithQuotation = async () => {
    var _a2, _b2;
    const ids = cartData.cartItems.map((item) => {
      const { product = {} } = item._originData || {};
      const { product_id } = product;
      return product_id;
    }).filter((id) => !!id);
    const store2 = getStore();
    const customer = (_b2 = (_a2 = store2 == null ? void 0 : store2.getState()) == null ? void 0 : _a2.global) == null ? void 0 : _b2.userInfo;
    if (!(ids == null ? void 0 : ids.length)) return;
    _getProductPrice.run({
      ids,
      customer_id: customer == null ? void 0 : customer.id
      // open_quotation: 1,
    });
  };
  const handleNextStep = async () => {
    onCloseCart();
    setOpenEmptyHolder(false);
    if (isLastStep) {
      return handleCheckout();
    }
    nextStep();
  };
  const handleHolder = () => {
    const isHolder = checkHolder();
    if (!isHolder) {
      onHolderOpen();
      return;
    }
    const emptyHolders = getWithoutCartItemsHolderNames();
    if ((emptyHolders == null ? void 0 : emptyHolders.length) > 0) {
      return setOpenEmptyHolder(true);
    }
    handleNextStep();
  };
  const handleContinue = async () => {
    var _a2, _b2, _c2;
    if (isLastStep) {
      const value = (0, import_utils2.formatValues)({
        state: data,
        platform: (_b2 = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.constants) == null ? void 0 : _b2.platform
      });
      if ((deposit == null ? void 0 : deposit.hasDeposit) && ((_c2 = deposit == null ? void 0 : deposit.protocols) == null ? void 0 : _c2.length) > 0 && !isAgreeDepositPolicy) {
        (0, import_utils3.Toast)(import_utils.locales.getText("pisell2.appointment.deposit.agree.policy"));
        return;
      }
      const checkRes = await onCheckBeforeBooking(value);
      if ((checkRes == null ? void 0 : checkRes.result) === false) {
        setCheckedNumber(checkRes == null ? void 0 : checkRes.num);
        setOpenCheckout(true);
        return;
      }
      const emptyHolders = getWithoutCartItemsHolderNames();
      if ((emptyHolders == null ? void 0 : emptyHolders.length) > 0) {
        return setOpenEmptyHolder(true);
      }
      onCloseCart();
      return handleCheckout();
    }
    if (!isLogin()) {
      onCloseCart();
      return openLoginModal({
        callback: async (status) => {
          if (status === "success") {
            await getCartItemProductsWithQuotation();
            handleHolder();
          }
        }
      });
    }
    handleHolder();
  };
  const handleSubmit = () => {
    var _a2, _b2, _c2, _d2;
    if ((_b2 = (_a2 = utils == null ? void 0 : utils.businessUtils) == null ? void 0 : _a2.isGuestUser) == null ? void 0 : _b2.call(_a2)) {
      if (!hasSubscribedRef.current) {
        pubsub.subscribe("bind.guest.user", handleContinue);
        hasSubscribedRef.current = true;
      }
      (_d2 = (_c2 = utils == null ? void 0 : utils.businessUtils) == null ? void 0 : _c2.openRegisterModal) == null ? void 0 : _d2.call(_c2, true);
      return;
    }
    handleContinue();
  };
  (0, import_react.useEffect)(() => {
    return () => {
      pubsub.unsubscribe("bind.guest.user", handleContinue);
      hasSubscribedRef.current = false;
    };
  }, []);
  const continueText = (0, import_react.useMemo)(() => {
    if (isLastStep) {
      return import_utils.locales.getText("pisell2.event.checkout");
    } else {
      return import_utils.locales.getText("pisell2.event.close.continue");
    }
  }, [currentStepData == null ? void 0 : currentStepData.key]);
  const confirmLoading = (0, import_react.useMemo)(() => {
    if (!isLastStep) return false;
    return (createBooking == null ? void 0 : createBooking.loading) || (checkBeforeBooking == null ? void 0 : checkBeforeBooking.loading) || (freePay == null ? void 0 : freePay.loading);
  }, [
    isLastStep,
    createBooking == null ? void 0 : createBooking.loading,
    checkBeforeBooking == null ? void 0 : checkBeforeBooking.loading,
    freePay == null ? void 0 : freePay.loading
  ]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.Button,
    {
      disabled: !((_e = cartData == null ? void 0 : cartData.cartItems) == null ? void 0 : _e.length),
      size: "large",
      type: "primary",
      onClick: () => isLastStep ? handleSubmit() : handleContinue(),
      loading: confirmLoading
    },
    continueText
  ), /* @__PURE__ */ import_react.default.createElement(
    import_OrderProductModal.default,
    {
      open: openCheckout,
      type: "checkout",
      onCancel: () => setOpenCheckout(false)
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_EmptyHolderModal.default,
    {
      open: openEmptyHolder,
      lists: getWithoutCartItemsHolderNames(),
      onCancel: () => setOpenEmptyHolder(false),
      onOk: () => handleNextStep()
    }
  ));
};
var ContinueButton_default = ContinueButton;
