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/appointmentBooking/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_ChevronDown = __toESM(require("@pisell/icon/es/ChevronDown"));
var import_UserCircle = __toESM(require("@pisell/icon/es/UserCircle"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_materials = require("@pisell/materials");
var import_hooks = require("../../hooks");
var import_voucher = require("../../../booking/components/voucher/index.less");
var import_utils2 = require("../../../booking/utils");
var import_index = require("./index.less");
var import_ahooks = require("ahooks");
var import_context = require("../../context");
var ShopDiscountHooks = {
  onInited: "shopDiscount:onInited",
  onDestroy: "shopDiscount:onDestroy",
  onLoadDiscountList: "shopDiscount:onLoadDiscountList",
  onCustomerChange: "shopDiscount:onCustomerChange",
  onDiscountListChange: "shopDiscount:onDiscountListChange",
  onRulesListChange: "shopDiscount:onRulesListChange",
  onLoadPrepareCalcResult: "shopDiscount:onLoadPrepareCalcResult"
};
var VoucherCard = (props) => {
  var _a, _b;
  const { products, currentUser } = props;
  const context = (0, import_useEngineContext.default)();
  const appointmentBooking = (0, import_hooks.useAppointmentBooking)();
  const shopDiscount = (0, import_hooks.useShopDiscount)();
  const [showDetail, setShowDetail] = (0, import_react.useState)(false);
  const { pisellos, action, token, store } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const { utils } = context.appHelper || {};
  const [code, setCode] = (0, import_react.useState)("");
  const [discountList, setDisCountList] = (0, import_react.useState)([]);
  const productRef = (0, import_react.useRef)(products);
  const { openLoginModal } = (0, import_hooks.useAppointmentBookingLogin)();
  const { accountLists } = (0, import_hooks.useAppointmentBookingAccount)();
  const { summary } = (0, import_context.useAppointmentBookingContext)();
  const { originTotal, total } = summary;
  const cart = (_b = appointmentBooking == null ? void 0 : appointmentBooking.store) == null ? void 0 : _b.cart;
  const isUserLoggedIn = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return !!((_b2 = (_a2 = utils == null ? void 0 : utils.token) == null ? void 0 : _a2.get) == null ? void 0 : _b2.call(_a2)) || false;
  }, [store]);
  (0, import_react.useEffect)(() => {
    const shopDiscount2 = pisellos.getModule("shopDiscount");
    shopDiscount2.setOriginTotalAmount(originTotal);
  }, [originTotal]);
  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]);
  (0, import_react.useEffect)(() => {
    if (isUserLoggedIn) {
      const shopDiscount2 = pisellos.getModule("shopDiscount");
      shopDiscount2.setCustomer(currentUser);
    }
  }, [currentUser.id, isUserLoggedIn]);
  (0, import_react.useEffect)(() => {
    shopDiscount.setProductList(products);
  }, [products]);
  const { run: onCartChange } = (0, import_ahooks.useDebounceFn)(
    () => {
      onCartChangeFn();
    },
    { wait: 300 }
  );
  const batchUpdateCart = (productList) => {
    var _a2;
    const items = productList.map((item) => {
      var _a3, _b2;
      return {
        _id: item._id,
        quantity: item.num,
        bundle: item.bundle,
        options: item._optionsOrigin,
        product: {
          ...item._productOrigin
        },
        discounts: ((_b2 = (_a3 = item._origin) == null ? void 0 : _a3.product) == null ? void 0 : _b2.discount_list) || []
      };
    });
    (_a2 = appointmentBooking == null ? void 0 : appointmentBooking.batchUpdateCart) == null ? void 0 : _a2.call(appointmentBooking, items);
  };
  const onCartChangeFn = () => {
    var _a2, _b2, _c, _d;
    const products2 = cart == null ? void 0 : cart.getItems();
    (_c = shopDiscount == null ? void 0 : shopDiscount.setBookingSubject) == null ? void 0 : _c.call(
      shopDiscount,
      (_b2 = (_a2 = appointmentBooking == null ? void 0 : appointmentBooking.otherParams) == null ? void 0 : _a2.bookingSetting) == null ? void 0 : _b2.bookingSubject
    );
    if (Array.isArray((_d = shopDiscount == null ? void 0 : shopDiscount.getDiscountList) == null ? void 0 : _d.call(shopDiscount)) && !(shopDiscount == null ? void 0 : shopDiscount.getDiscountList().length)) {
      return;
    }
    const val = shopDiscount.calcDiscount(products2);
    batchUpdateCart(val.productList);
  };
  const stringifiedHolders = (0, import_react.useMemo)(() => {
    let _ret;
    try {
      _ret = JSON.stringify(products.map((item) => (item == null ? void 0 : item.holder_id) || ""));
    } catch (error) {
      _ret = "";
    }
    return _ret;
  }, [products]);
  (0, import_react.useEffect)(() => {
    onCartChange();
  }, [stringifiedHolders]);
  (0, import_react.useEffect)(() => {
    const val = shopDiscount.getDiscountList();
    setDisCountList(val);
    pisellos.effects.on(
      ShopDiscountHooks.onLoadPrepareCalcResult,
      (result) => {
        batchUpdateCart(result.productList);
      }
    );
    pisellos.effects.on("appointmentBooking_cart:onAddItem", onCartChange);
    pisellos.effects.on(
      "appointmentBooking_cart:onUpdateQuotationPrice",
      onCartChange
    );
    pisellos.effects.on(
      "appointmentBooking_cart:onUpdateBookingDate",
      onCartChange
    );
    pisellos.effects.on(
      "appointmentBooking_cart:onUpdateCartItemNums",
      onCartChange
    );
    pisellos.effects.on("appointmentBooking_cart:onRemoveItem", onCartChange);
    pisellos.effects.on(
      ShopDiscountHooks.onDiscountListChange,
      (discount) => {
        console.log(discount, "discountChange");
        setDisCountList(discount);
      }
    );
  }, []);
  const onScanCode = async () => {
    const customerId = currentUser.id;
    const val = await shopDiscount.scanCode(code, customerId);
    if (val == null ? void 0 : val.isAvailable) {
      batchUpdateCart(val.productList);
      setCode("");
    } else {
      const message = (0, import_utils2.showDiscountScanFailMessage)(val, "goodpass", import_utils.locales);
      (0, import_materials.PisellToast)({ content: message });
    }
  };
  const renderLoginCard = () => {
    if (isUserLoggedIn) return null;
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "login-card" }, /* @__PURE__ */ import_react.default.createElement(import_UserCircle.default, { style: { fontSize: 28 } }), /* @__PURE__ */ import_react.default.createElement("div", { className: "text-wrapper" }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellText,
      {
        className: "login-btn",
        onClick: () => {
          if (!action) return;
          openLoginModal({
            callback: (status) => {
            }
          });
        }
      },
      import_utils.locales.getText("pisell2.text.goodpass.login")
    ), /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell2.text.goodpass.login-tip"))));
  };
  const mixedSort = (val) => {
    return [...val].sort((a, b) => {
      return Number(b == null ? void 0 : b.isSelected) - Number(a == null ? void 0 : a.isSelected);
    });
  };
  const renderVoucherInfo = () => {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "voucher-title" }, /* @__PURE__ */ import_react.default.createElement("span", { className: "voucher-title-left" }, import_utils.locales.getText("pisell2.text.goodpass")), /* @__PURE__ */ import_react.default.createElement(
      "span",
      {
        className: "voucher-title-right",
        onClick: () => {
          console.log("showDetail: ", showDetail);
          setShowDetail(!showDetail);
        }
      },
      import_utils.locales.getText("pisell2.text.details"),
      " ",
      /* @__PURE__ */ import_react.default.createElement(
        import_ChevronDown.default,
        {
          className: (0, import_classnames.default)("voucher-right-icon", {
            show: showDetail
          })
        }
      )
    )), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)("voucher-detail", {
          show: showDetail
        })
      },
      (availableData == null ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellGoodPassCard,
        {
          style: { width: "100%" },
          dataSource: availableData,
          mixedSort,
          onChange: (val) => {
            const detail = shopDiscount.setDiscountSelected({
              discountId: val.id,
              isSelected: val.isSelected
            });
            batchUpdateCart(detail.productList);
          }
        }
      ) : null,
      renderLoginCard(),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "voucher-code-input-wrapper" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "voucher-code-input" }, /* @__PURE__ */ import_react.default.createElement("div", { style: { whiteSpace: "nowrap" } }, import_utils.locales.getText("pisell2.text.goodpass.code"), ":"), /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellInput,
        {
          value: code,
          allowClear: true,
          onChange: (e) => {
            var _a2;
            setCode((_a2 = e.target) == null ? void 0 : _a2.value);
          },
          size: "small",
          placeholder: import_utils.locales.getText(
            "pisell2.text.goodpass.enter-code"
          )
        }
      )), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { size: "small", onClick: onScanCode, disabled: !code }, import_utils.locales.getText("pisell2.text.apply")))
    ));
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__appointment-booking-voucher-container" }, renderVoucherInfo());
};
var Voucher_default = VoucherCard;
