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/booking/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_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_useIsBooking4Shop = require("../../hooks/useIsBooking4Shop");
var import_index = require("./index.less");
var import_ahooks = require("ahooks");
var import_utils2 = require("./utils");
var import_pisellos = require("../../../ticketBooking/hooks/pisellos");
var import_utils3 = require("../../info/clientVariant/utils");
var import_useShopDiscountModule = require("../../../ticketBooking/hooks/pisellos/useShopDiscountModule");
var services = {};
var VoucherCard = (props) => {
  var _a, _b, _c, _d, _e, _f;
  const context = (0, import_useEngineContext.default)();
  const { state, dispatch, source, isInModal = false } = props;
  const [showDetail, setShowDetail] = (0, import_react.useState)(isInModal ? true : false);
  const { pisellos } = (_a = context.appHelper) == null ? void 0 : _a.utils;
  const [code, setCode] = (0, import_react.useState)("");
  const [discountList, setDisCountList] = (0, import_react.useState)([]);
  const serviceValueRef = (0, import_react.useRef)(state.service.value);
  const addonsValueRef = (0, import_react.useRef)(state.addons.value);
  const isBooking4Shop = (0, import_useIsBooking4Shop.useIsBooking4Shop)(state);
  const shopDiscount = (0, import_useShopDiscountModule.useShopDiscountModule)();
  const { executeIfActive } = (0, import_pisellos.useActiveExecute)();
  const holderChangedRef = (0, import_react.useRef)(false);
  const stateRef = (0, import_react.useRef)(state);
  stateRef.current = state;
  services = state.service;
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    if (shopDiscount == null ? void 0 : shopDiscount.setOrderId) {
      (_b2 = shopDiscount.setOrderId) == null ? void 0 : _b2.call(shopDiscount, ((_a2 = state.bookingDetail) == null ? void 0 : _a2.id) || state.bookingId);
    }
  }, [(_b = state.bookingDetail) == null ? void 0 : _b.id, state.bookingId]);
  const { selectCustomer } = (0, import_pisellos.useCustomer)({});
  (0, import_ahooks.useDebounceEffect)(
    () => {
      if (isBooking4Shop) {
        shopDiscount.setCustomer(state.client.value);
      }
    },
    [(_c = state.client.value) == null ? void 0 : _c.id, isBooking4Shop],
    {
      wait: 200
    }
  );
  (0, import_react.useEffect)(() => {
    if (isBooking4Shop && shopDiscount) {
      shopDiscount.setProductList([
        ...state.service.value,
        ...state.addons.value
      ]);
    }
  }, [state.service.value, state.addons.value, isBooking4Shop]);
  const serviceMemo = (0, import_react.useMemo)(() => {
    var _a2;
    const val = (_a2 = state.service.value || []) == null ? void 0 : _a2.map((value) => {
      var _a3, _b2, _c2;
      return {
        booking_id: value.booking_id,
        id: value.id,
        price: value.price,
        total: (_a3 = value == null ? void 0 : value._extend) == null ? void 0 : _a3.total,
        discount_list: value.discount_list,
        origin_total: (_b2 = value == null ? void 0 : value._extend) == null ? void 0 : _b2.origin_total,
        holder_id: (_c2 = value == null ? void 0 : value._extend) == null ? void 0 : _c2.holder_id,
        quantity: value._extend.quantity,
        startDate: value._extend.startDate
      };
    });
    return val;
  }, [state.service.value]);
  const serviceTotal = (0, import_react.useMemo)(() => {
    return serviceMemo.reduce((total, item) => {
      return total + (item.total || 0);
    }, 0);
  }, [serviceMemo]);
  const onScanWallPassCode = (0, import_ahooks.useMemoizedFn)((e) => {
    if (!e.detail.code) {
      return;
    }
    onScanCode(e.detail.code);
  });
  const onOriginExpectAmountWithoutDiscountChange = (0, import_ahooks.useMemoizedFn)((e) => {
    var _a2;
    (_a2 = shopDiscount == null ? void 0 : shopDiscount.setOriginTotalAmount) == null ? void 0 : _a2.call(shopDiscount, e.detail.originExpectAmountWithoutDiscount);
  });
  (0, import_react.useEffect)(() => {
    const wrappedOnScanWallPassCode = executeIfActive(onScanWallPassCode);
    window.addEventListener("onScanWallPassCode", wrappedOnScanWallPassCode);
    window.addEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
    return () => {
      window.removeEventListener(
        "onScanWallPassCode",
        wrappedOnScanWallPassCode
      );
      window.removeEventListener("onOriginExpectAmountWithoutDiscountChange", onOriginExpectAmountWithoutDiscountChange);
    };
  }, []);
  const addonsMemo = (0, import_react.useMemo)(() => {
    var _a2;
    const val = (_a2 = state.addons.value || []) == null ? void 0 : _a2.map((value) => {
      var _a3, _b2;
      return {
        booking_id: value.booking_id,
        id: value.id,
        _id: value._id,
        price: value.price,
        total: (_a3 = value == null ? void 0 : value._extend) == null ? void 0 : _a3.total,
        discount_list: value.discount_list,
        _key: value._key,
        num: (_b2 = value == null ? void 0 : value._extend) == null ? void 0 : _b2.quantity
      };
    });
    return val;
  }, [state.addons.value]);
  const holdersMemo = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    if (isBooking4Shop) {
      let list = [];
      if ((_a2 = state.pet) == null ? void 0 : _a2.value) {
        let entries = Object.entries(state.pet.value);
        if (entries.length === 1) {
          list = entries[0][1];
        }
      }
      (_b2 = shopDiscount == null ? void 0 : shopDiscount.setHolders) == null ? void 0 : _b2.call(shopDiscount, list);
      holderChangedRef.current = true;
      return list || [];
    }
  }, [(_d = state.pet) == null ? void 0 : _d.value, isBooking4Shop]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2;
    console.log("update booking subject", state.bookingConfig);
    (_d2 = shopDiscount == null ? void 0 : shopDiscount.setBookingSubject) == null ? void 0 : _d2.call(
      shopDiscount,
      (_c2 = (_b2 = (_a2 = state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.appointment_subject
    );
  }, [state.bookingConfig]);
  const disabled = (0, import_react.useMemo)(() => {
    var _a2;
    if (((_a2 = state.bookingDetail) == null ? void 0 : _a2.payment_status) === "paid" && [...addonsMemo, ...serviceMemo].every((item) => item.booking_id)) {
      return true;
    }
    return false;
  }, [state, addonsMemo, serviceMemo]);
  const { run } = (0, import_ahooks.useDebounceFn)(
    () => {
      var _a2, _b2, _c2;
      if (serviceValueRef.current === state.service.value && addonsValueRef.current === state.addons.value && !holderChangedRef.current || !((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length)) {
        return;
      }
      if (Array.isArray((_c2 = shopDiscount == null ? void 0 : shopDiscount.getDiscountList) == null ? void 0 : _c2.call(shopDiscount)) && !(shopDiscount == null ? void 0 : shopDiscount.getDiscountList().length)) {
        return;
      }
      if (isBooking4Shop) {
        const val = shopDiscount.calcDiscount([
          ...stateRef.current.service.value,
          ...stateRef.current.addons.value
        ]);
        console.log("input: ", state.service.value);
        console.log("output: ", val);
        productListToValue(val.productList);
        holderChangedRef.current = false;
      }
    },
    { wait: 1e3 }
  );
  (0, import_react.useEffect)(() => {
    run();
  }, [
    JSON.stringify(serviceMemo),
    JSON.stringify(addonsMemo),
    JSON.stringify(holdersMemo),
    isBooking4Shop
  ]);
  (0, import_react.useEffect)(() => {
    var _a2;
    if (shopDiscount) {
      const wrappedHandler = executeIfActive(fn);
      (_a2 = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _a2.on("shopDiscount:onSelectedDiscountListChange", wrappedHandler);
      return () => {
        var _a3;
        (_a3 = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _a3.off(
          "shopDiscount:onSelectedDiscountListChange",
          wrappedHandler
        );
      };
    }
  }, []);
  const fn = (0, import_ahooks.useMemoizedFn)((result) => {
    var _a2;
    if (!(result == null ? void 0 : result.productList) || ((_a2 = result == null ? void 0 : result.productList) == null ? void 0 : _a2.some((item) => !item))) {
      return;
    }
    if (window.isPaymentModalPluginOpen && !(state == null ? void 0 : state.isEditTicketMode)) return;
    productListToValue(result.productList);
  });
  (0, import_react.useEffect)(() => {
    if (!isBooking4Shop || !shopDiscount) return;
    const onScanCustomerChange = (customer) => {
      const clientVariantClose = (0, import_utils3.getClientVariantClose)();
      if (clientVariantClose) {
        clientVariantClose();
      }
      selectCustomer(customer);
    };
    const onDiscountListChange = (discount) => {
      setDisCountList(discount);
    };
    const wrappedOnScanCustomerChangeHandler = executeIfActive(onScanCustomerChange);
    const wrappedOnDiscountListChangeHandler = executeIfActive(onDiscountListChange);
    const wrappedFn = executeIfActive(fn);
    shopDiscount.effectsOn(
      "onScanCustomerChange",
      wrappedOnScanCustomerChangeHandler
    );
    shopDiscount.effectsOn("onLoadPrepareCalcResult", wrappedFn);
    shopDiscount.effectsOn(
      "onDiscountListChange",
      wrappedOnDiscountListChangeHandler
    );
    return () => {
      shopDiscount.clear();
      shopDiscount.effectsOff(
        "onScanCustomerChange",
        wrappedOnScanCustomerChangeHandler
      );
      shopDiscount.effectsOff("onLoadPrepareCalcResult", wrappedFn);
      shopDiscount.effectsOff(
        "onDiscountListChange",
        wrappedOnDiscountListChangeHandler
      );
    };
  }, [state.bookingId, isBooking4Shop, fn]);
  const productListToValue = (0, import_ahooks.useMemoizedFn)((list, edit) => {
    var _a2;
    const { serviceList, addonsList } = (0, import_utils2.getServiceAddons)(list);
    const newTotal = serviceList.reduce((total, item) => {
      return total + (item._extend.total || 0);
    }, 0);
    if (newTotal !== serviceTotal) {
      edit = true;
    }
    serviceValueRef.current = serviceList;
    addonsValueRef.current = addonsList;
    let other = {};
    if (edit) {
      other = {
        edit: true
      };
    }
    dispatch({
      type: "setService",
      payload: {
        value: serviceList,
        ...other
      }
    });
    if (!((_a2 = props == null ? void 0 : props.state) == null ? void 0 : _a2.isBookingTicket2)) {
      setTimeout(() => {
        dispatch({
          type: "setAddons",
          payload: {
            value: addonsList,
            ...other
          }
        });
      });
    }
  });
  const onScanCode = async (codeParam) => {
    var _a2;
    const customerId = (_a2 = state.client.value) == null ? void 0 : _a2.id;
    const val = await shopDiscount.scanCode(codeParam || code, customerId);
    console.log(val);
    if (val == null ? void 0 : val.isAvailable) {
      productListToValue(val.productList, true);
      setCode("");
    } else {
      const content = {
        time_limit: import_utils.locales.getText(
          "pisell2.text.goodpass.code-invalid-expired"
        )
      };
      (0, import_materials.PisellToast)({
        content: val.type === "server" ? import_utils.locales.getText("pisell2.text.goodpass.code-invalid") : content[val == null ? void 0 : val.unavailableReason] || import_utils.locales.getText("pisell2.text.goodpass.code-invalid-cart")
      });
    }
  };
  const availableData = (0, import_react.useMemo)(() => {
    if (!isBooking4Shop) return [];
    return discountList.filter((item) => !!item.isAvailable).map((discount) => {
      return {
        ...discount,
        isDisabled: discount.isDisabled || discount.isDisabledForProductUsed || disabled,
        savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
      };
    });
  }, [discountList, isBooking4Shop, disabled]);
  if (!isBooking4Shop) return null;
  const mixedSort = (val) => {
    return [...val].sort((a, b) => {
      return Number(b == null ? void 0 : b.isSelected) - Number(a == null ? void 0 : a.isSelected);
    });
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-footer-voucher-container" }, /* @__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")), !isInModal && /* @__PURE__ */ import_react.default.createElement(
    "span",
    {
      className: "voucher-title-right",
      onClick: () => {
        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 || isInModal
      })
    },
    (availableData == null ? void 0 : availableData.length) > 0 ? /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellGoodPassCard,
      {
        style: { width: "100%" },
        isInModal: isInModal || false,
        dataSource: ((_f = (_e = state.service) == null ? void 0 : _e.value) == null ? void 0 : _f.length) ? availableData : [],
        mixedSort,
        onChange: (val) => {
          const detail = shopDiscount.setDiscountSelected({
            discountId: val.id,
            isSelected: val.isSelected
          });
          productListToValue(detail.productList, true);
        }
      }
    ) : null,
    /* @__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,
        onChange: (e) => {
          var _a2;
          setCode((_a2 = e.target) == null ? void 0 : _a2.value);
        },
        size: "small",
        allowClear: true,
        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")))
  ));
};
var voucher_default = VoucherCard;
