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/Voucher/index.tsx
var Voucher_exports = {};
__export(Voucher_exports, {
  default: () => Voucher_default
});
module.exports = __toCommonJS(Voucher_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_materials = require("@pisell/materials");
var import_Sales = require("../../../Sales");
var import_Voucher = __toESM(require("./components/Voucher"));
var import_locales = __toESM(require("./components/locales"));
var import_hooks = require("./hooks");
var import_utils2 = require("../../../booking/utils");
var ShopDiscountHooks = {
  onDiscountListChange: "shopDiscount:eventBooking:onDiscountListChange",
  onLoadPrepareCalcResult: "shopDiscount:eventBooking:onLoadPrepareCalcResult"
};
var VoucherCard = () => {
  var _a, _b, _c;
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const pisellos = (0, import_useEngineContext.usePisellOS)();
  import_utils.locales.init(import_locales.default, ((_b = utils == null ? void 0 : utils.storage) == null ? void 0 : _b.get("umi_locale")) || "en");
  const shopDiscount = (0, import_hooks.useShopDiscount)();
  const { cartData, updateCartItem } = (0, import_Sales.useCart)();
  const { isLogin, openLoginModal, getUserInfo } = (0, import_Sales.useCustomer)();
  const [showDetail, setShowDetail] = (0, import_react.useState)(false);
  const [code, setCode] = (0, import_react.useState)("");
  const [discountList, setDisCountList] = (0, import_react.useState)([]);
  const { getCartItemProductsWithQuotation } = (0, import_hooks.useVoucherLogin)();
  const currentUser = getUserInfo() || {};
  const cartUnique = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return (_b2 = (_a2 = cartData == null ? void 0 : cartData.cartItems) == null ? void 0 : _a2.map((item) => {
      const { _id, holder, product } = (item == null ? void 0 : item._originData) || {};
      const { discount_list, ...rest } = product || {};
      return JSON.stringify({ _id, product: rest, holder });
    })) == null ? void 0 : _b2.join("-");
  }, [cartData.cartItems]);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (isLogin() && (currentUser == null ? void 0 : currentUser.id)) {
      (_a2 = shopDiscount == null ? void 0 : shopDiscount.setCustomer) == null ? void 0 : _a2.call(shopDiscount, currentUser);
    }
  }, [currentUser == null ? void 0 : currentUser.id, isLogin, shopDiscount]);
  (0, import_react.useEffect)(() => {
    shopDiscount.setProductList((cartData == null ? void 0 : cartData.cartItems) || []);
  }, [cartUnique, shopDiscount]);
  const batchUpdateCart = (productList) => {
    if (!(productList == null ? void 0 : productList.length)) return;
    productList.forEach((product) => {
      updateCartItem(product, "deposit");
    });
  };
  (0, import_react.useEffect)(() => {
    const onDiscountListChange = (discount) => {
      console.log("onDiscountListChange: ", discount);
      setDisCountList(discount);
    };
    const onLoadPrepareCalcResult = (result) => {
      var _a2;
      console.log("onLoadPrepareCalcResult: ", result);
      if (!((_a2 = result == null ? void 0 : result.productList) == null ? void 0 : _a2.length)) {
        return;
      }
      batchUpdateCart(result == null ? void 0 : result.productList);
    };
    pisellos.effects.on(
      ShopDiscountHooks.onLoadPrepareCalcResult,
      onLoadPrepareCalcResult
    );
    pisellos.effects.on(
      ShopDiscountHooks.onDiscountListChange,
      onDiscountListChange
    );
    return () => {
      pisellos.effects.off(
        ShopDiscountHooks.onLoadPrepareCalcResult,
        onLoadPrepareCalcResult
      );
      pisellos.effects.off(
        ShopDiscountHooks.onDiscountListChange,
        onDiscountListChange
      );
    };
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2;
    (_a2 = shopDiscount == null ? void 0 : shopDiscount.setBookingSubject) == null ? void 0 : _a2.call(shopDiscount, { type: "form" });
    const val = shopDiscount.calcDiscount((cartData == null ? void 0 : cartData.cartItems) || []);
    if (val == null ? void 0 : val.productList) {
      batchUpdateCart(val.productList);
    }
  }, [cartUnique]);
  const availableData = (0, import_react.useMemo)(() => {
    return discountList.filter((item) => !!item.isAvailable).map((discount) => {
      return {
        ...discount,
        isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
        savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
      };
    });
  }, [discountList, shopDiscount]);
  const onScanCode = async () => {
    if (!shopDiscount) {
      (0, import_materials.PisellToast)({
        content: import_utils.locales.getText("pisell2.voucher.code-invalid")
      });
      return;
    }
    const val = await shopDiscount.scanCode(code, currentUser.id);
    console.log("scanCodeValue: ", val);
    if (val == null ? void 0 : val.isAvailable) {
      batchUpdateCart(val.productList);
      setCode("");
    } else {
      const message = (0, import_utils2.showDiscountScanFailMessage)(val, "voucher", import_utils.locales);
      (0, import_materials.PisellToast)({ content: message });
    }
  };
  const mixedSort = (val) => {
    return [...val].sort((a, b) => {
      return Number(b == null ? void 0 : b.isSelected) - Number(a == null ? void 0 : a.isSelected);
    });
  };
  const handleLoginClick = () => {
    openLoginModal({
      callback: async (status) => {
        if (status === "success") {
          await getCartItemProductsWithQuotation();
        }
      }
    });
  };
  const handleDiscountChange = (val) => {
    if (!shopDiscount) return;
    const detail = shopDiscount.setDiscountSelected({
      discountId: val.id,
      isSelected: val.isSelected
    });
    console.log("Set discount selected:", detail);
    if (detail == null ? void 0 : detail.productList) {
      batchUpdateCart(detail.productList);
    }
  };
  const handleToggleDetail = () => {
    setShowDetail(!showDetail);
  };
  if (!((_c = cartData.cartItems) == null ? void 0 : _c.length)) return null;
  return /* @__PURE__ */ import_react.default.createElement(
    import_Voucher.default,
    {
      showDetail,
      onToggleDetail: handleToggleDetail,
      isLogin: isLogin(),
      onLoginClick: handleLoginClick,
      availableData,
      onDiscountChange: handleDiscountChange,
      mixedSort,
      code,
      onCodeChange: setCode,
      onApplyCode: onScanCode,
      codeDisabled: !code
    }
  );
};
var Voucher_default = VoucherCard;
