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 ShopDiscountHooks = {
  onInited: "shopDiscount:onInited",
  onDestroy: "shopDiscount:onDestroy",
  onLoadDiscountList: "shopDiscount:onLoadDiscountList",
  onCustomerChange: "shopDiscount:onCustomerChange",
  onScanCustomerChange: "shopDiscount:onScanCustomerChange",
  onDiscountListChange: "shopDiscount:onDiscountListChange",
  onRulesListChange: "shopDiscount:onRulesListChange",
  onLoadPrepareCalcResult: "shopDiscount:onLoadPrepareCalcResult"
};
var services = {};
var VoucherCard = (props) => {
  var _a, _b, _c, _d;
  const context = (0, import_useEngineContext.default)();
  const { state, dispatch, source } = props;
  const [showDetail, setShowDetail] = (0, import_react.useState)(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 = pisellos.getModule("shopDiscount");
  services = state.service;
  const changeCustomerToGlobalState = (0, import_ahooks.useMemoizedFn)((value) => {
    dispatch({
      type: "setClient",
      payload: {
        value,
        edit: true
      }
    });
  });
  const { selectCustomer } = (0, import_pisellos.useCustomer)({
    changeCustomerToGlobalState
  });
  (0, import_ahooks.useDebounceEffect)(
    () => {
      if (isBooking4Shop) {
        shopDiscount.setCustomer(state.client.value);
      }
    },
    [(_b = state.client.value) == null ? void 0 : _b.id, isBooking4Shop],
    {
      wait: 200
    }
  );
  (0, import_react.useEffect)(() => {
    if (isBooking4Shop) {
      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;
      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,
        quantity: value._extend.quantity
      };
    });
    return val;
  }, [state.service.value]);
  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 disabled = (0, import_react.useMemo)(() => {
    var _a2;
    if (["paid", "partially_paid"].includes(
      (_a2 = state.bookingDetail) == null ? void 0 : _a2.payment_status
    ) && [...addonsMemo, ...serviceMemo].every((item) => item.booking_id)) {
      return true;
    }
    return false;
  }, [state, addonsMemo, serviceMemo]);
  const { run } = (0, import_ahooks.useDebounceFn)(
    () => {
      var _a2, _b2;
      if (serviceValueRef.current === state.service.value && addonsValueRef.current === state.addons.value || !((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length)) {
        return;
      }
      if (isBooking4Shop) {
        const val = shopDiscount.calcDiscount([
          ...state.service.value,
          ...state.addons.value
        ]);
        console.log("input: ", state.service.value);
        console.log("output: ", val);
        productListToValue(val.productList);
      }
    },
    { wait: 500 }
  );
  (0, import_react.useEffect)(() => {
    run();
  }, [JSON.stringify(serviceMemo), JSON.stringify(addonsMemo), isBooking4Shop]);
  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;
    }
    productListToValue(result.productList);
  });
  (0, import_react.useEffect)(() => {
    if (!isBooking4Shop) return;
    const onScanCustomerChange = (customer) => {
      selectCustomer(customer);
    };
    const onDiscountListChange = (discount) => {
      setDisCountList(discount);
    };
    pisellos.effects.on(
      ShopDiscountHooks.onScanCustomerChange,
      onScanCustomerChange
    );
    pisellos.effects.on(ShopDiscountHooks.onLoadPrepareCalcResult, fn);
    pisellos.effects.on(
      ShopDiscountHooks.onDiscountListChange,
      onDiscountListChange
    );
    return () => {
      shopDiscount.clear();
      pisellos.effects.off(
        ShopDiscountHooks.onCustomerChange,
        onScanCustomerChange
      );
      pisellos.effects.off(ShopDiscountHooks.onLoadPrepareCalcResult, fn);
      pisellos.effects.off(
        ShopDiscountHooks.onDiscountListChange,
        onDiscountListChange
      );
    };
  }, [state.bookingId, isBooking4Shop, fn]);
  const productListToValue = (0, import_ahooks.useMemoizedFn)((list, edit) => {
    const { serviceList, addonsList } = (0, import_utils2.getServiceAddons)(list);
    serviceValueRef.current = serviceList;
    addonsValueRef.current = addonsList;
    let other = {};
    if (edit) {
      other = {
        edit: true
      };
    }
    dispatch({
      type: "setService",
      payload: {
        value: serviceList,
        ...other
      }
    });
    dispatch({
      type: "setAddons",
      payload: {
        value: addonsList,
        ...other
      }
    });
  });
  const onScanCode = async () => {
    const val = await shopDiscount.scanCode(code);
    console.log(val);
    if (val == null ? void 0 : val.isAvailable) {
      productListToValue(val.productList, true);
      setCode("");
    } else {
      (0, import_materials.PisellToast)({
        content: val.type === "server" ? import_utils.locales.getText("pisell2.text.goodpass.code-invalid") : import_utils.locales.getText("pisell2.text.goodpass.code-invalid-cart")
      });
    }
  };
  const availableData = (0, import_react.useMemo)(() => {
    if (!isBooking4Shop) return [];
    const shopDiscount2 = pisellos.getModule("shopDiscount");
    return discountList.filter((item) => !!item.isAvailable).map((discount) => {
      return {
        ...discount,
        isDisabled: discount.isDisabled || discount.isDisabledForProductUsed || disabled,
        savedAmount: shopDiscount2.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")), /* @__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: ((_d = (_c = state.service) == null ? void 0 : _c.value) == null ? void 0 : _d.length) ? availableData : [],
        mixedSort,
        onChange: (val) => {
          const shopDiscount2 = pisellos.getModule("shopDiscount");
          const detail = shopDiscount2.setDiscountSelected({
            discountId: val.id,
            isSelected: val.isSelected
          });
          console.log("setDiscountSelected:", detail);
          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;
