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/checkout/hooks/useWalletPass.ts
var useWalletPass_exports = {};
__export(useWalletPass_exports, {
  useWalletPass: () => useWalletPass
});
module.exports = __toCommonJS(useWalletPass_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_dayjs = __toESM(require("dayjs"));
var import_useEngineContext = require("../../../hooks/useEngineContext");
var import_utils2 = require("../components/WalletPassModule/utils");
var import_usePaymentLogger = __toESM(require("./usePaymentLogger"));
var import_utils3 = require("../../booking/utils");
var import_pisellos = require("../../ticketBooking/hooks/pisellos");
var import_useShopDiscountModule = require("../../ticketBooking/hooks/pisellos/useShopDiscountModule");
var useWalletPass = (props) => {
  const { onSelectChange, customAmount, clientId, totalAmount } = props;
  const logger = (0, import_usePaymentLogger.default)();
  const { executeIfActive } = (0, import_pisellos.useActiveExecute)();
  const [walletRecommendList, setWalletRecommendList] = (0, import_react.useState)([]);
  const [userIdentificationCodes, setUserIdentificationCodes] = (0, import_react.useState)(
    []
  );
  const [transformList, setTransformList] = (0, import_react.useState)([]);
  const [noApplicableVoucher, setNoApplicableVoucher] = (0, import_react.useState)([]);
  const initialOrderedDataRef = (0, import_react.useRef)([]);
  const initialDiscountOrderRef = (0, import_react.useRef)([]);
  const confirmedEditAmountIdsRef = (0, import_react.useRef)([]);
  const [searchIdentificationCodeList, setSearchIdentificationCodeList] = (0, import_react.useState)([]);
  const [orderInfo, setOrderInfo] = (0, import_react.useState)({});
  const [selectedWallet, setSelectedWallet] = (0, import_react.useState)([]);
  const selectedWalletRef = (0, import_react.useRef)([]);
  const [selectedVoucherIds, setSelectedVoucherIds] = (0, import_react.useState)([]);
  const [disabledWalletData, setDisabledWalletData] = (0, import_react.useState)([]);
  const notSetWalletSelectRef = (0, import_react.useRef)(false);
  const showBestToastRef = (0, import_react.useRef)(false);
  const [products, setProducts] = (0, import_react.useState)([]);
  const selectedWalletIds = (0, import_react.useMemo)(() => {
    return selectedWallet.map((item) => item.id);
  }, [selectedWallet]);
  const pisellos = (0, import_useEngineContext.usePisellOS)();
  const Toast = (0, import_materials.useToast)();
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [error, setError] = (0, import_react.useState)(null);
  const [discountList, setDiscountList] = (0, import_react.useState)([]);
  const checkoutModule = pisellos.getModule("checkout");
  const shopDiscount = (0, import_useShopDiscountModule.useShopDiscountModule)();
  const paymentModule = checkoutModule == null ? void 0 : checkoutModule.payment;
  const walletPassEvaluator = (0, import_react.useMemo)(() => {
    var _a, _b;
    return (_b = (_a = paymentModule == null ? void 0 : paymentModule.window) == null ? void 0 : _a.getWalletPassEvaluator) == null ? void 0 : _b.call(_a);
  }, []);
  const setWalletSelect = (0, import_ahooks.useMemoizedFn)((data2) => {
    setSelectedWallet(data2);
    selectedWalletRef.current = data2;
  });
  (0, import_react.useEffect)(() => {
    if ((0, import_utils3.isWalkIn)(clientId) && searchIdentificationCodeList.length === 0) {
      setUserIdentificationCodes([]);
      setWalletRecommendList([]);
      setDiscountList([]);
    }
  }, [clientId]);
  const availableDiscountList = (0, import_react.useMemo)(() => {
    const formattedData = (0, import_utils2.formatDiscountWalletData)(
      discountList.filter((item) => !!item.isAvailable).map((discount) => {
        return {
          ...discount,
          isDisabled: discount.isDisabled || discount.isDisabledForProductUsed,
          savedAmount: shopDiscount.calcDiscountApplicableProductTotalPrice(discount)
        };
      })
    );
    return formattedData;
  }, [discountList]);
  const selectedDiscountList = (0, import_react.useMemo)(() => {
    return availableDiscountList.filter((item) => item.isSelected && !item.isEditMode).map((item) => item.id);
  }, [availableDiscountList]);
  const mergeDataWithInitialOrder = (0, import_ahooks.useMemoizedFn)((newData) => {
    if (initialOrderedDataRef.current.length === 0) {
      return newData;
    }
    const newDataMap = new Map(newData.map((item) => [item.id, item]));
    const orderedResult = [];
    const addedIds = /* @__PURE__ */ new Set();
    if (searchIdentificationCodeList.length > 0) {
      const reversedSearchOrder = [...searchIdentificationCodeList].reverse();
      for (const searchItem of reversedSearchOrder) {
        const foundItem = newDataMap.get(searchItem.id);
        if (foundItem && !addedIds.has(searchItem.id)) {
          orderedResult.push(foundItem);
          addedIds.add(searchItem.id);
        }
      }
    }
    for (const newItem of newData) {
      const isNewItem = !initialOrderedDataRef.current.some(
        (initialItem) => initialItem.id === newItem.id
      );
      if (isNewItem && !addedIds.has(newItem.id)) {
        orderedResult.push(newItem);
        addedIds.add(newItem.id);
      }
    }
    for (const initialItem of initialOrderedDataRef.current) {
      if (newDataMap.has(initialItem.id) && !addedIds.has(initialItem.id)) {
        orderedResult.push(newDataMap.get(initialItem.id));
        addedIds.add(initialItem.id);
      }
    }
    return orderedResult;
  });
  const sortDiscountListWithInitialOrder = (0, import_ahooks.useMemoizedFn)(
    (newDiscountList) => {
      var _a;
      const sortBySelected = (list) => {
        return list.sort((a, b) => {
          if (a.isSelected && !b.isSelected) return -1;
          if (!a.isSelected && b.isSelected) return 1;
          return 0;
        });
      };
      if (initialDiscountOrderRef.current.length === 0 || newDiscountList.length === 0) {
        const historyItems2 = newDiscountList.filter((item) => item.isEditMode);
        const normalItems = newDiscountList.filter((item) => !item.isEditMode);
        return [...historyItems2, ...sortBySelected(normalItems)];
      }
      const newDataBucketMap = /* @__PURE__ */ new Map();
      for (const item of newDiscountList) {
        if (!newDataBucketMap.has(item.id)) {
          newDataBucketMap.set(item.id, []);
        }
        (_a = newDataBucketMap.get(item.id)) == null ? void 0 : _a.push(item);
      }
      const consumeItemByRef = (targetItem) => {
        const bucket = newDataBucketMap.get(targetItem.id);
        if (!(bucket == null ? void 0 : bucket.length)) return null;
        const targetIndex = bucket.indexOf(targetItem);
        if (targetIndex === -1) return null;
        return bucket.splice(targetIndex, 1)[0];
      };
      const consumeItemByInitial = (initialItem, matcher) => {
        const bucket = newDataBucketMap.get(initialItem.id);
        if (!(bucket == null ? void 0 : bucket.length)) return null;
        const targetIndex = bucket.findIndex(
          (candidate) => matcher(candidate, initialItem)
        );
        if (targetIndex === -1) return null;
        return bucket.splice(targetIndex, 1)[0];
      };
      const historyItems = [];
      const normalItemsByInitialOrder = [];
      const remainingNormalItems = [];
      const initialHistoryItems = initialDiscountOrderRef.current.filter(
        (item) => item.isEditMode
      );
      for (const initialItem of initialHistoryItems) {
        const matchedHistoryItem = consumeItemByInitial(
          initialItem,
          (candidate) => !!candidate.isEditMode
        );
        if (matchedHistoryItem) {
          historyItems.push(matchedHistoryItem);
        }
      }
      for (const item of newDiscountList) {
        if (!item.isEditMode) continue;
        const remainingHistoryItem = consumeItemByRef(item);
        if (remainingHistoryItem) {
          historyItems.push(remainingHistoryItem);
        }
      }
      for (const initialItem of initialDiscountOrderRef.current) {
        if (initialItem.isEditMode) continue;
        const matchedNormalItem = consumeItemByInitial(
          initialItem,
          (candidate) => !candidate.isEditMode
        );
        if (matchedNormalItem) {
          normalItemsByInitialOrder.push(matchedNormalItem);
        }
      }
      for (const item of newDiscountList) {
        if (item.isEditMode) continue;
        const remainingNormalItem = consumeItemByRef(item);
        if (remainingNormalItem) {
          remainingNormalItems.push(remainingNormalItem);
        }
      }
      return [
        ...historyItems,
        ...normalItemsByInitialOrder,
        ...sortBySelected(remainingNormalItems)
      ];
    }
  );
  const allVouchersForCalculation = (0, import_react.useMemo)(() => {
    return [...transformList || [], ...searchIdentificationCodeList || []];
  }, [transformList, searchIdentificationCodeList]);
  const selectedVouchers = (0, import_react.useMemo)(() => {
    return selectedVoucherIds.map((id) => allVouchersForCalculation.find((v) => v.id === id)).filter(Boolean);
  }, [selectedVoucherIds, allVouchersForCalculation]);
  const { displayVouchers, displayOtherVouchers, selectedWithDetails, totalDeduction } = (0, import_react.useMemo)(() => {
    if (!walletPassEvaluator || !allVouchersForCalculation.length || !totalAmount) {
      return {
        displayVouchers: [...transformList || [], ...noApplicableVoucher || []],
        displayOtherVouchers: searchIdentificationCodeList || [],
        selectedWithDetails: [],
        totalDeduction: 0
      };
    }
    const result = walletPassEvaluator.recalculateVouchers(
      allVouchersForCalculation,
      selectedVouchers,
      totalAmount,
      products || []
    );
    const currentCustomerVouchers = [];
    const otherCustomerVouchers = [];
    result.allWithUpdatedStatus.forEach((voucher) => {
      const isSearchVoucher = searchIdentificationCodeList.some((item) => item.id === voucher.id);
      if (isSearchVoucher) {
        otherCustomerVouchers.push(voucher);
      } else {
        currentCustomerVouchers.push(voucher);
      }
    });
    return {
      displayVouchers: [...currentCustomerVouchers, ...noApplicableVoucher || []],
      displayOtherVouchers: otherCustomerVouchers,
      selectedWithDetails: result.selectedWithDetails,
      totalDeduction: result.selectedWithDetails.reduce((sum, v) => sum + (v.actualDeduction || 0), 0)
    };
  }, [selectedVouchers, allVouchersForCalculation, transformList, searchIdentificationCodeList, noApplicableVoucher, totalAmount, products]);
  (0, import_ahooks.useDebounceEffect)(() => {
    notifySelectChange(selectedWithDetails);
    setWalletSelect(selectedWithDetails);
    setLoading(false);
  }, [selectedWithDetails], {
    wait: 200
  });
  const data = (0, import_react.useMemo)(() => {
    return (0, import_utils2.formatMachineCodeServer2CardList)(
      (0, import_utils.uniqueByKey)(
        mergeDataWithInitialOrder([
          ...selectedWithDetails,
          ...displayVouchers,
          ...displayOtherVouchers
        ]),
        "id"
      ),
      selectedVoucherIds
    );
  }, [displayVouchers, displayOtherVouchers, selectedVoucherIds, selectedWithDetails]);
  const fetchUserIdentificationCodes = (0, import_ahooks.useMemoizedFn)(async (params) => {
    setLoading(true);
    setError(null);
    try {
      const result = await paymentModule.wallet.getUserIdentificationCodeListAsync(params);
      const newData = (0, import_utils.uniqueByKey)(
        [...result, ...selectedWalletRef.current],
        "id"
      );
      setUserIdentificationCodes(newData);
      return result;
    } catch (err) {
      setError(err instanceof Error ? err.message : "获取用户识别码列表失败");
      throw err;
    } finally {
      setLoading(false);
    }
  });
  const getCachedWalletRecommendList = (0, import_ahooks.useMemoizedFn)(() => {
    return paymentModule.wallet.getWalletRecommendList();
  });
  const getCachedUserIdentificationCodes = (0, import_ahooks.useMemoizedFn)(() => {
    return paymentModule.wallet.getUserIdentificationCodes();
  });
  const clearWalletRecommendList = (0, import_ahooks.useMemoizedFn)(() => {
    paymentModule.wallet.clearWalletRecommendList();
  });
  const clearUserIdentificationCodes = (0, import_ahooks.useMemoizedFn)(() => {
    paymentModule.wallet.clearUserIdentificationCodes();
  });
  const clearAllCache = (0, import_ahooks.useMemoizedFn)(() => {
    paymentModule.wallet.clearAllCache();
  });
  const handleUserIdentificationCodesUpdated = (0, import_ahooks.useMemoizedFn)((data2) => {
    const newData = [
      ...selectedWalletRef.current,
      ...data2.userIdentificationCodes
    ];
    setUserIdentificationCodes(newData);
  });
  const handleSearchIdentificationCodeCompleted = (0, import_ahooks.useMemoizedFn)((data2) => {
    const { currentSearchResults, cachedSearchResults } = data2;
    let formattedResults = currentSearchResults;
    if (walletPassEvaluator && currentSearchResults.length > 0 && totalAmount) {
      formattedResults = walletPassEvaluator.searchVoucherFormat({
        vouchers: currentSearchResults,
        orderTotalAmount: totalAmount,
        products: products || []
      });
    }
    let formattedCachedResults = cachedSearchResults || [];
    if (walletPassEvaluator && cachedSearchResults && cachedSearchResults.length > 0 && totalAmount) {
      formattedCachedResults = walletPassEvaluator.searchVoucherFormat({
        vouchers: cachedSearchResults,
        orderTotalAmount: totalAmount,
        products: products || []
      });
    }
    const mergedSearchResults = (0, import_utils.uniqueByKey)(
      [...formattedCachedResults || [], ...formattedResults],
      "id"
    );
    let isAvailableData = [];
    let isDisabledData = [];
    if (formattedResults.length > 0) {
      formattedResults.forEach((item) => {
        if ((0, import_utils2.getVoucherAvailableStatus)(item)) {
          isAvailableData.push(item);
        } else {
          isDisabledData.push(item);
        }
      });
    }
    const availableData = mergedSearchResults.filter((item) => (0, import_utils2.getVoucherAvailableStatus)(item));
    const allDisabledData = mergedSearchResults.filter((item) => !(0, import_utils2.getVoucherAvailableStatus)(item));
    setDisabledWalletData(allDisabledData);
    let newValues = [...selectedWalletRef.current];
    if (isAvailableData.length === 1) {
      newValues = [...selectedWalletRef.current, ...isAvailableData];
    }
    setSearchIdentificationCodeList(availableData);
    setNoApplicableVoucher(allDisabledData);
    setWalletSelect(newValues);
    setSelectedVoucherIds(newValues.map((item) => item.id));
  });
  const onOrderCreated = (0, import_ahooks.useMemoizedFn)(() => {
    var _a, _b;
    const orderInfo2 = checkoutModule.getOrderOriginalData();
    setOrderInfo(orderInfo2);
    const recommendList = getCachedWalletRecommendList();
    const userIdentificationCodes2 = getCachedUserIdentificationCodes();
    const walletInitData = ((_b = (_a = paymentModule == null ? void 0 : paymentModule.wallet) == null ? void 0 : _a.getStoredWalletInitData) == null ? void 0 : _b.call(_a)) || {};
    const transformListData = walletInitData.transformList || userIdentificationCodes2;
    const noApplicableVoucherData = walletInitData.noApplicableVoucher || [];
    const productsData = walletInitData.products || [];
    const initialData = [...recommendList, ...userIdentificationCodes2];
    setWalletRecommendList(recommendList);
    setUserIdentificationCodes(userIdentificationCodes2);
    setTransformList(transformListData);
    setNoApplicableVoucher(noApplicableVoucherData);
    setProducts(productsData);
    initialOrderedDataRef.current = initialData;
    if (!notSetWalletSelectRef.current) {
      setWalletSelect(recommendList);
      setSelectedVoucherIds(recommendList.map((item) => item.id));
      const select = paymentModule.wallet.formatWalletPassList2PreparePayments(recommendList).map((item) => ({
        code: item.tag,
        voucher_id: item.voucher_id,
        amount: item.amount || 0,
        wallet_pass_usage_unit: item.wallet_pass_usage_unit,
        wallet_pass_use_value: item.wallet_pass_use_value
      }));
      logger == null ? void 0 : logger.addLog({
        type: "info",
        title: "useWalletPass_onOrderCreated onSelectChange 开始调用",
        metadata: {}
      });
      onSelectChange == null ? void 0 : onSelectChange(select);
    } else {
      setWalletSelect([]);
      setSelectedVoucherIds([]);
      notSetWalletSelectRef.current = false;
      onSelectChange == null ? void 0 : onSelectChange([]);
    }
    const originalDiscountList = shopDiscount.getDiscountList();
    const sortedDiscountList = sortDiscountListWithInitialOrder(originalDiscountList);
    initialDiscountOrderRef.current = sortedDiscountList;
    setDiscountList(sortedDiscountList);
    if (showBestToastRef.current) {
      Toast == null ? void 0 : Toast.success(
        import_utils.locales.getText("wallet-pass-module-best-combination-selected")
      );
    }
    showBestToastRef.current = false;
  });
  const customerName = (0, import_react.useMemo)(() => {
    var _a, _b, _c;
    if (!((_a = orderInfo == null ? void 0 : orderInfo.original_order_data) == null ? void 0 : _a.customer_id) || ((_b = orderInfo == null ? void 0 : orderInfo.original_order_data) == null ? void 0 : _b.customer_id) === 1) {
      return import_utils.locales.getText("wallet-pass-module-customer-name-walk-in");
    }
    return ((_c = orderInfo == null ? void 0 : orderInfo.original_order_data) == null ? void 0 : _c.customer_name) || "";
  }, [orderInfo]);
  const handleWalletCacheCleared = (0, import_ahooks.useMemoizedFn)((data2) => {
    if (data2.clearedTypes.includes("all")) {
      setSearchIdentificationCodeList([]);
    }
  });
  const handleWalletInitializationStarted = (0, import_ahooks.useMemoizedFn)(() => {
    setLoading(true);
  });
  const handleWalletInitializationCompleted = (0, import_ahooks.useMemoizedFn)(() => {
    setLoading(false);
  });
  const handleWalletInitializationFailed = (0, import_ahooks.useMemoizedFn)(() => {
    setLoading(false);
  });
  const handlePaymentStarted = (0, import_ahooks.useMemoizedFn)(
    async (params) => {
      if (params.paymentMethodCode !== "VOUCHER_BATCH" && Number(customAmount || 0) > 0) {
        notSetWalletSelectRef.current = true;
        await checkoutModule.initWalletData({
          order_wait_pay_amount: Number(customAmount)
        });
      }
    }
  );
  const handleWalletRecommendListUpdated = (0, import_ahooks.useMemoizedFn)((data2) => {
    setWalletRecommendList(data2.walletRecommendList);
  });
  (0, import_react.useEffect)(() => {
    if (!paymentModule) return;
    const core = pisellos;
    const wrappedHandlePaymentStarted = executeIfActive(handlePaymentStarted);
    const wrappedOnOrderCreated = executeIfActive(onOrderCreated);
    const wrappedHandleWalletRecommendListUpdated = executeIfActive(handleWalletRecommendListUpdated);
    const wrappedHandleUserIdentificationCodesUpdated = executeIfActive(handleUserIdentificationCodesUpdated);
    const wrappedHandleWalletCacheCleared = executeIfActive(handleWalletCacheCleared);
    const wrappedHandleSearchIdentificationCodeCompleted = executeIfActive(handleSearchIdentificationCodeCompleted);
    const wrappedHandleWalletInitializationStarted = executeIfActive(handleWalletInitializationStarted);
    const wrappedHandleWalletInitializationCompleted = executeIfActive(handleWalletInitializationCompleted);
    const wrappedHandleWalletInitializationFailed = executeIfActive(handleWalletInitializationFailed);
    paymentModule.effectsOn(
      "onWalletRecommendListUpdated",
      wrappedHandleWalletRecommendListUpdated
    );
    checkoutModule.effectsOn("onPaymentStarted", wrappedHandlePaymentStarted);
    checkoutModule.effectsOn("onPaymentItemAdded", wrappedHandlePaymentStarted);
    paymentModule.effectsOn(
      "onUserIdentificationCodesUpdated",
      wrappedHandleUserIdentificationCodesUpdated
    );
    paymentModule.effectsOn("onWalletCacheCleared", wrappedHandleWalletCacheCleared);
    paymentModule.effectsOn(
      "onSearchIdentificationCodeCompleted",
      wrappedHandleSearchIdentificationCodeCompleted
    );
    checkoutModule.effectsOn("onWalletDataInitialized", wrappedOnOrderCreated);
    paymentModule.effectsOn(
      "onWalletInitializationStarted",
      wrappedHandleWalletInitializationStarted
    );
    paymentModule.effectsOn(
      "onWalletInitializationCompleted",
      wrappedHandleWalletInitializationCompleted
    );
    paymentModule.effectsOn(
      "onWalletInitializationFailed",
      wrappedHandleWalletInitializationFailed
    );
    return () => {
      paymentModule.effectsOff(
        "onWalletRecommendListUpdated",
        wrappedHandleWalletRecommendListUpdated
      );
      checkoutModule.effectsOff("onPaymentStarted", wrappedHandlePaymentStarted);
      checkoutModule.effectsOff("onPaymentItemAdded", wrappedHandlePaymentStarted);
      paymentModule.effectsOff(
        "onUserIdentificationCodesUpdated",
        wrappedHandleUserIdentificationCodesUpdated
      );
      paymentModule.effectsOff("onWalletCacheCleared", wrappedHandleWalletCacheCleared);
      paymentModule.effectsOff(
        "onSearchIdentificationCodeCompleted",
        wrappedHandleSearchIdentificationCodeCompleted
      );
      checkoutModule.effectsOff("onWalletDataInitialized", wrappedOnOrderCreated);
      paymentModule.effectsOff(
        "onWalletInitializationStarted",
        wrappedHandleWalletInitializationStarted
      );
      paymentModule.effectsOff(
        "onWalletInitializationCompleted",
        wrappedHandleWalletInitializationCompleted
      );
      paymentModule.effectsOff(
        "onWalletInitializationFailed",
        wrappedHandleWalletInitializationFailed
      );
    };
  }, [paymentModule]);
  const allList = (0, import_react.useMemo)(() => {
    const reversedSearchData = [...searchIdentificationCodeList].reverse();
    return [
      ...userIdentificationCodes,
      ...walletRecommendList,
      ...reversedSearchData
    ];
  }, [
    walletRecommendList,
    userIdentificationCodes,
    searchIdentificationCodeList
  ]);
  const getOtherExactCodes = (0, import_ahooks.useMemoizedFn)(() => {
    return searchIdentificationCodeList.filter(
      (item) => !selectedWalletRef.current.some(
        (wallet) => wallet.id === item.id
      )
    ).map((item) => item.code);
  });
  const notifySelectChange = (0, import_ahooks.useMemoizedFn)((selectedDetails) => {
    const prepare_payments = paymentModule.wallet.formatWalletPassList2PreparePayments(selectedDetails);
    const select = [];
    prepare_payments.forEach((item) => {
      if (item.amount && select.every((s) => s.voucher_id !== item.voucher_id)) {
        select.push({
          voucher_id: item.voucher_id,
          amount: item.amount,
          code: item.tag,
          wallet_pass_usage_unit: item.wallet_pass_usage_unit,
          wallet_pass_use_value: item.wallet_pass_use_value
        });
      }
    });
    logger == null ? void 0 : logger.addLog({
      type: "info",
      title: "useWalletPass_notifySelectChange 通知外部选择变化",
      metadata: { selectedDetails, select }
    });
    onSelectChange == null ? void 0 : onSelectChange(select);
  });
  const handleSearchIdentificationCode = (0, import_ahooks.useMemoizedFn)((value) => {
    return paymentModule.wallet.searchIdentificationCodeAsync({
      code: value,
      prepare_payments: paymentModule.wallet.formatWalletPassList2PreparePayments(
        selectedWithDetails
      )
    });
  });
  const handleSelectWallet = (0, import_ahooks.useMemoizedFn)((value) => {
    setLoading(true);
    const deselectedIds = selectedVoucherIds.filter(
      (id) => !value.includes(id)
    );
    if (deselectedIds.length > 0) {
      const needResetIds = deselectedIds.filter((id) => {
        const voucher = allVouchersForCalculation.find((v) => v.id === id);
        return (voucher == null ? void 0 : voucher.edit_current_amount) !== void 0;
      });
      if (needResetIds.length > 0) {
        updateWalletDataById(needResetIds, { edit_current_amount: void 0 });
        confirmedEditAmountIdsRef.current = confirmedEditAmountIdsRef.current.filter(
          (id) => !needResetIds.includes(id)
        );
      }
    }
    setSelectedVoucherIds(value);
    const val = allVouchersForCalculation.filter(
      (item) => value.includes(item.id)
    );
    setWalletSelect(val);
  });
  const expiredWalletIds = (0, import_react.useMemo)(() => {
    return (0, import_utils.uniqueByKey)(allList, "id").filter(
      (item) => item.expire_date && (0, import_dayjs.default)(item.expire_date).isBefore((0, import_dayjs.default)())
    );
  }, [allList, selectedWalletIds]);
  const expiredWalletData = (0, import_react.useMemo)(() => {
    const expiredItems = (0, import_utils.uniqueByKey)(allList, "id").filter(
      (item) => item.expire_date && (0, import_dayjs.default)(item.expire_date).isBefore((0, import_dayjs.default)())
    );
    return (0, import_utils2.formatMachineCodeServer2CardList)(expiredItems, [], {
      error: true,
      showStatus: false
    });
  }, [allList]);
  const clearAllSelectedWallet = (0, import_ahooks.useMemoizedFn)(() => {
    var _a;
    if (confirmedEditAmountIdsRef.current.length > 0) {
      updateWalletDataById(confirmedEditAmountIdsRef.current, {
        edit_current_amount: void 0
      });
      confirmedEditAmountIdsRef.current = [];
    }
    if (selectedWalletIds.length === 0 && selectedDiscountList.length === 0) {
      return;
    }
    setLoading(true);
    if (selectedDiscountList.length) {
      notSetWalletSelectRef.current = true;
      const detail = shopDiscount.setDiscountSelected({
        selectedList: selectedDiscountList.map((item) => ({
          discountId: item,
          isSelected: false
        }))
      });
      const sortedDiscountList = sortDiscountListWithInitialOrder(
        detail.discountList
      );
      setDiscountList(sortedDiscountList);
      (_a = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _a.emit(
        "shopDiscount:onSelectedDiscountListChange",
        detail
      );
      return;
    }
    setWalletSelect([]);
    setSelectedVoucherIds([]);
    logger == null ? void 0 : logger.addLog({
      type: "info",
      title: "useWalletPass_clearAllSelectedWallet 立即通知外部清空",
      metadata: {}
    });
    onSelectChange == null ? void 0 : onSelectChange([]);
    setLoading(false);
  });
  const isCurrentSelectionBest = (0, import_ahooks.useMemoizedFn)(() => {
    if (walletRecommendList.length === 0) return true;
    const recommendedIds = walletRecommendList.map((item) => item.id).sort();
    const currentSelectedIds = selectedWalletIds.sort();
    return JSON.stringify(recommendedIds) === JSON.stringify(currentSelectedIds);
  });
  const handleBestSaving = (0, import_ahooks.useMemoizedFn)(() => {
    logger == null ? void 0 : logger.addLog({
      type: "info",
      title: "useWalletPass_handleBestSaving 开始调用",
      metadata: {}
    });
    setLoading(true);
    let hasGoodPass = false;
    let isBestDiscount = false;
    if (availableDiscountList.length) {
      hasGoodPass = true;
      showBestToastRef.current = true;
      shopDiscount.bestDiscount((result) => {
        if ((0, import_utils2.isSameContent)(
          ((result == null ? void 0 : result.discountList) || []).filter((item) => item.isSelected).map((item) => item.id),
          selectedDiscountList
        )) {
          showBestToastRef.current = false;
          isBestDiscount = true;
          setLoading(false);
          Toast == null ? void 0 : Toast.info(
            import_utils.locales.getText("wallet-pass-module-already-best-combination")
          );
        }
      });
    }
    if (walletRecommendList.length === 0) {
      if (!hasGoodPass || hasGoodPass && isBestDiscount) {
        setLoading(false);
      }
      if (searchIdentificationCodeList.length) {
        if ((0, import_utils2.isSameContent)(
          selectedWalletIds,
          searchIdentificationCodeList.map((item) => item.id)
        )) {
          Toast == null ? void 0 : Toast.info(
            import_utils.locales.getText("wallet-pass-module-already-best-combination")
          );
        } else {
          const select = searchIdentificationCodeList.filter((item) => (0, import_utils2.getVoucherAvailableStatus)(item));
          setWalletSelect(select);
          setSelectedVoucherIds(select.map((item) => item.id));
          if (select.length) {
            Toast == null ? void 0 : Toast.success(
              import_utils.locales.getText("wallet-pass-module-best-combination-selected")
            );
          }
        }
      }
      return;
    }
    let isChangeAmount = false;
    let newWalletRecommendList = walletRecommendList;
    if (confirmedEditAmountIdsRef.current.length > 0) {
      isChangeAmount = true;
      const detail = updateWalletDataById(confirmedEditAmountIdsRef.current, {
        edit_current_amount: void 0
      });
      newWalletRecommendList = detail.newWalletRecommendList;
      confirmedEditAmountIdsRef.current = [];
    }
    if (isCurrentSelectionBest() && !isChangeAmount) {
      if (!hasGoodPass) {
        Toast == null ? void 0 : Toast.info(
          import_utils.locales.getText("wallet-pass-module-already-best-combination")
        );
      }
    } else {
      if (hasGoodPass && !isBestDiscount) return;
      setWalletSelect(newWalletRecommendList);
      setSelectedVoucherIds(newWalletRecommendList.map((item) => item.id));
      Toast == null ? void 0 : Toast.success(
        import_utils.locales.getText("wallet-pass-module-best-combination-selected")
      );
    }
    setLoading(false);
  });
  const handleSelectDiscount = (0, import_ahooks.useMemoizedFn)((value, option) => {
    var _a, _b, _c;
    setLoading(true);
    const isSelected = value.includes(option.id);
    const detail = shopDiscount.setDiscountSelected({
      discountId: option.id,
      isSelected
    });
    if (!((_b = (_a = detail == null ? void 0 : detail.discountList) == null ? void 0 : _a.find((item) => item.id === option.id)) == null ? void 0 : _b.isSelected)) {
      setLoading(false);
    }
    const sortedDiscountList = sortDiscountListWithInitialOrder(
      detail.discountList
    );
    setDiscountList(sortedDiscountList);
    (_c = pisellos == null ? void 0 : pisellos.effects) == null ? void 0 : _c.emit(
      "shopDiscount:onSelectedDiscountListChange",
      detail
    );
  });
  const clearDisabledWalletData = (0, import_ahooks.useMemoizedFn)(() => {
    setDisabledWalletData([]);
  });
  const updateArrayItemById = (0, import_ahooks.useMemoizedFn)(
    (array, targetId, updateData) => {
      const targetIds = Array.isArray(targetId) ? targetId : [targetId];
      return array.map(
        (item) => targetIds.includes(item.id) ? { ...item, ...updateData } : item
      );
    }
  );
  const updateWalletDataById = (0, import_ahooks.useMemoizedFn)(
    (targetId, updateData) => {
      const newWalletRecommendList = updateArrayItemById(
        walletRecommendList,
        targetId,
        updateData
      );
      setWalletRecommendList(newWalletRecommendList);
      const newUserIdentificationCodes = updateArrayItemById(
        userIdentificationCodes,
        targetId,
        updateData
      );
      setUserIdentificationCodes(newUserIdentificationCodes);
      const newTransformList = updateArrayItemById(
        transformList,
        targetId,
        updateData
      );
      setTransformList(newTransformList);
      const newSearchIdentificationCodeList = updateArrayItemById(
        searchIdentificationCodeList,
        targetId,
        updateData
      );
      setSearchIdentificationCodeList(newSearchIdentificationCodeList);
      const newSelectedWallet = updateArrayItemById(
        selectedWallet,
        targetId,
        updateData
      );
      setWalletSelect(newSelectedWallet);
      return {
        newWalletRecommendList,
        newUserIdentificationCodes,
        newTransformList,
        newSearchIdentificationCodeList,
        newSelectedWallet
      };
    }
  );
  const handleConfirmEditAmount = (0, import_ahooks.useMemoizedFn)(
    (value, id, data2) => {
      if (value === 0) {
        const filteredIds = selectedVoucherIds.filter(
          (walletId) => walletId !== data2.id
        );
        handleSelectWallet(filteredIds);
        return;
      }
      setLoading(true);
      if (!confirmedEditAmountIdsRef.current.includes(data2.id)) {
        confirmedEditAmountIdsRef.current.push(data2.id);
      }
      updateWalletDataById(data2.id, { edit_current_amount: value });
    }
  );
  const handleBeforeEditAmount = (0, import_ahooks.useMemoizedFn)(
    async (value, index, data2) => {
      return true;
    }
  );
  return {
    // 状态
    walletRecommendList,
    userIdentificationCodes,
    loading,
    error,
    cardData: data,
    handleSelectWallet,
    selectedWalletIds,
    expiredWalletIds,
    expiredWalletData,
    disabledWalletData,
    clearAllSelectedWallet,
    clearDisabledWalletData,
    handleBeforeEditAmount,
    handleBestSaving,
    handleSearchIdentificationCode,
    availableDiscountList,
    selectedDiscountList,
    handleSelectDiscount,
    customerName,
    fetchUserIdentificationCodes,
    getCachedWalletRecommendList,
    getCachedUserIdentificationCodes,
    clearWalletRecommendList,
    clearUserIdentificationCodes,
    clearAllCache,
    handleConfirmEditAmount
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useWalletPass
});
