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/pay/toC/PaymentMethods/WalletPass/index.tsx
var WalletPass_exports = {};
__export(WalletPass_exports, {
  default: () => WalletPass_default
});
module.exports = __toCommonJS(WalletPass_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_icons = require("@ant-design/icons");
var import_pinVerifyModal = __toESM(require("../../../../pinVerifyModal"));
var import_MultiModeSearch = __toESM(require("./MultiModeSearch"));
var import_List = __toESM(require("./List"));
var import_serve = require("./serve");
var import_utils2 = require("./utils");
var import_utils3 = require("../../utils");
var import_index = require("./index.less");
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var { Amount } = import_materials.PisellText;
var WalletPass = (0, import_react.forwardRef)((props, ref) => {
  var _a, _b, _c, _d, _e;
  const { onWalletPassChange, walletPass, walletSetting } = props;
  const context = (0, import_useEngineContext.default)();
  const isWalletCode = (_d = (_c = (_b = (_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.businessUtils) == null ? void 0 : _c.getAppByModal) == null ? void 0 : _d.call(_c, "wallet");
  const [currentWalletPass, setCurrentWalletPass] = (0, import_react.useState)(walletPass);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [open, setOpen] = (0, import_react.useState)(false);
  const [searchOpen, setSearchOpen] = (0, import_react.useState)(false);
  const [addList, setAddList] = (0, import_react.useState)([]);
  const [order, setOrder] = (0, import_react.useState)(null);
  const [searchData, setSearchData] = (0, import_react.useState)([]);
  const [searchSelectData, setSearchSelectData] = (0, import_react.useState)({
    ids: [],
    details: []
  });
  const isAutoSelect = (0, import_react.useRef)(false);
  const listRef = (0, import_react.useRef)(null);
  const searchValRef = (0, import_react.useRef)(null);
  const pinVerifyModalRef = (0, import_react.useRef)(null);
  const { cards: walletPassSelectCards, amount } = currentWalletPass || {};
  const [currentCustomerWalletPass, otherCustomerWalletPass] = (0, import_react.useMemo)(() => {
    const current = [];
    const other = [];
    (walletPassSelectCards || []).forEach((item) => {
      if (item.customer_id === (order == null ? void 0 : order.customer_id)) {
        current.push(item);
      } else {
        other.push(item);
      }
    });
    return [current, other];
  }, [walletPassSelectCards, order == null ? void 0 : order.customer_id]);
  const prepare_payments = (0, import_react.useMemo)(() => {
    return (0, import_utils3.formatWalletPassList2PreparePayments)(
      (0, import_utils.uniqueByKey)(
        (walletPassSelectCards || []).concat(searchSelectData.details),
        "id"
      )
    );
  }, [walletPassSelectCards, searchSelectData]);
  const selectValue = (0, import_react.useMemo)(() => {
    return (walletPassSelectCards == null ? void 0 : walletPassSelectCards.map((item) => item.id)) || [];
  }, [walletPassSelectCards]);
  const otherCustomerWalletPassList = (0, import_react.useMemo)(() => {
    return (0, import_utils2.formatMachineCodeServer2CardList)(addList, selectValue);
  }, [addList, selectValue]);
  const other_exact_codes = (0, import_react.useMemo)(() => {
    const codes = [];
    addList.forEach((item) => {
      if (!selectValue.includes(item.id)) {
        codes.push(item.code);
      }
    });
    return codes;
  }, [addList, selectValue]);
  const refreshList = (0, import_ahooks.useMemoizedFn)(() => {
    var _a2, _b2;
    if ((order == null ? void 0 : order.order_id) && (order == null ? void 0 : order.customer_id)) {
      (_b2 = listRef.current) == null ? void 0 : _b2.init(
        {
          order_id: order.order_id,
          available: 2,
          prepare_payments,
          filter_prepare_wallet_pass: 1,
          sale_channel: ((_a2 = order._order) == null ? void 0 : _a2.sale_channel) || "online-store",
          other_exact_codes
        },
        // 已选择的卡片接口中不会返回，所以追加进入列表
        (val) => {
          const idMap = val.reduce((pre, cur) => {
            return {
              ...pre,
              [cur.id]: cur
            };
          }, {});
          setAddList((prevState) => {
            return prevState.map((item) => {
              if (idMap[item.id]) {
                return idMap[item.id];
              }
              return item;
            });
          });
          return [...currentCustomerWalletPass || [], ...val];
        }
      );
    }
  });
  (0, import_react.useEffect)(() => {
    if ((order == null ? void 0 : order.order_id) && searchValRef.current) {
      searchList(searchValRef.current, true);
    }
  }, [order == null ? void 0 : order.order_id, searchSelectData]);
  const init = async (res) => {
    if (!res) return;
    setOrder(res);
    setOpen(true);
    setCurrentWalletPass(walletPass);
    setTimeout(() => {
      refreshList();
    });
  };
  const searchList = async ({ code, customer_pin_key }, isSelectChange) => {
    var _a2;
    if (!(order == null ? void 0 : order.order_id)) return;
    setLoading(true);
    try {
      const result = await (0, import_serve.searchMachineCodeList)({
        order_id: order.order_id,
        code,
        prepare_payments,
        // filter_prepare_wallet_pass: 1,
        sale_channel: ((_a2 = order._order) == null ? void 0 : _a2.sale_channel) || "online-store",
        customer_pin_key
      });
      if (!result) {
        if (!isSelectChange) {
          (0, import_materials.PisellToast)({
            content: import_utils.locales.getText("tocPay.text.walletSearchEmpty")
          });
        }
        return;
      }
      if (isSelectChange && !searchValRef.current) {
        return;
      }
      setSearchData(
        (0, import_utils2.formatMachineCodeServer2CardList)(
          [...searchSelectData.details, ...result],
          searchSelectData.ids
        )
      );
      if (result.length) {
        if (result.length === 1 && result[0].unified_available_status && isAutoSelect.current) {
          setSearchSelectData({
            ids: [result[0].id],
            details: result
          });
        }
        setSearchOpen(true);
        searchValRef.current = { code, customer_pin_key };
      }
    } finally {
      setLoading(false);
    }
  };
  const searchWalletCodeFn = async (val) => {
    var _a2;
    setLoading(true);
    try {
      const result = await (0, import_serve.searchWalletCode)({ code: val, with_customer: 1 });
      console.log(result, "result");
      if (!result) {
        searchList({ code: val });
        return;
      }
      (_a2 = pinVerifyModalRef.current) == null ? void 0 : _a2.open({
        wallet_code: result.code,
        wallet_detail_id: result.id,
        failed_count: result.failed_count,
        check_max_count: result.check_max_count,
        customer: result.customer
      });
    } finally {
      setLoading(false);
    }
  };
  const handleSearch = (0, import_ahooks.useMemoizedFn)((val) => {
    if (!val || searchOpen) return;
    isAutoSelect.current = true;
    if ((0, import_utils2.getIsWalletCode)(val) && isWalletCode) {
      searchWalletCodeFn(val);
    } else {
      searchList({ code: val });
    }
  });
  (0, import_react.useImperativeHandle)(ref, () => ({
    init
  }));
  const handleSearchModalClose = () => {
    setSearchOpen(false);
    searchValRef.current = null;
    setSearchSelectData({
      ids: [],
      details: []
    });
  };
  const handleSelectOk = () => {
    changeWalletPass(
      (0, import_utils.uniqueByKey)(
        [
          ...walletPassSelectCards || [],
          ...searchSelectData.details
        ],
        "id"
      )
    );
    setAddList((prevState) => {
      return (0, import_utils.uniqueByKey)(
        [...prevState, ...searchSelectData.details],
        "id"
      ).filter(
        (item) => !(order == null ? void 0 : order.customer_id) || item.customer_id !== (order == null ? void 0 : order.customer_id)
      );
    });
    handleSearchModalClose();
  };
  const handleAddChange = (0, import_ahooks.useMemoizedFn)(
    (val, details) => {
      isAutoSelect.current = false;
      setSearchSelectData({
        ids: val,
        details: details.map((item) => item.originData)
      });
    }
  );
  const changeWalletPass = (cards) => {
    setCurrentWalletPass == null ? void 0 : setCurrentWalletPass({
      cards,
      amount: (0, import_utils3.calcWalletPassListAmount)(cards)
    });
    setTimeout(() => {
      refreshList();
    });
  };
  const handleSelectChange = (val, details, type) => {
    let cards = details.map((item) => item.originData);
    if (type === "other") {
      cards = currentCustomerWalletPass.concat(cards);
    } else if (type === "current") {
      cards = otherCustomerWalletPass.concat(cards);
    }
    changeWalletPass(cards);
  };
  const handleRedeem = () => {
    onWalletPassChange == null ? void 0 : onWalletPassChange((0, import_utils2.formatWalletPassWithUniquePaymentNumber)(currentWalletPass));
    setOpen(false);
  };
  const handleWalletClose = () => {
    setOpen(false);
    setCurrentWalletPass(walletPass);
  };
  const handleOtherChange = (0, import_ahooks.useMemoizedFn)(
    (val, valDetail) => {
      handleSelectChange(val, valDetail, "other");
    }
  );
  const handleCurrentChange = (0, import_ahooks.useMemoizedFn)(
    (val, valDetail) => {
      handleSelectChange(val, valDetail, "current");
    }
  );
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      title: /* @__PURE__ */ import_react.default.createElement("div", null, walletSetting.name),
      open,
      onCancel: () => handleWalletClose(),
      cancelVisible: false,
      destroyOnClose: true,
      okText: /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("tocPay.text.redeem"), " ", /* @__PURE__ */ import_react.default.createElement(Amount, { value: amount })),
      onOk: handleRedeem
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "", style: { marginTop: 24 } }, /* @__PURE__ */ import_react.default.createElement(import_MultiModeSearch.default, { onChange: handleSearch }), /* @__PURE__ */ import_react.default.createElement("div", { className: "wallet-pass-modal-multi-selection-available" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "wallet-pass-modal-multi-selection-available-title" }, /* @__PURE__ */ import_react.default.createElement(import_icons.InfoCircleOutlined, { className: "wallet-pass-modal-multi-selection-available-title-icon" }), import_utils.locales.getText("tocPay.text.multipleSelectionAvailable")), /* @__PURE__ */ import_react.default.createElement("div", { className: "wallet-pass-modal-multi-selection-available-desc" }, import_utils.locales.getText(
      "tocPay.text.youCanSelectMultipleWalletPassesToCombineForPayment"
    )(walletSetting.name))), otherCustomerWalletPassList.length > 0 && /* @__PURE__ */ import_react.default.createElement(
      import_List.default,
      {
        walletSetting,
        data: otherCustomerWalletPassList,
        title: import_utils.locales.getText("tocPay.text.couponCodesAdded"),
        onChange: handleOtherChange,
        value: selectValue,
        loading,
        onChangeDebounce: true
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_List.default,
      {
        walletSetting,
        title: walletSetting.name,
        onChange: handleCurrentChange,
        ref: listRef,
        value: selectValue,
        onLoadingChange: setLoading,
        customer_id: order == null ? void 0 : order.customer_id
      }
    ))
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      title: /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("tocPay.text.searchResult")),
      mobileModalHeight: "90%",
      destroyOnClose: true,
      open: searchOpen,
      onCancel: () => handleSearchModalClose(),
      cancelVisible: false,
      okText: import_utils.locales.getText("tocPay.text.select"),
      onOk: handleSelectOk,
      okButtonProps: {
        disabled: ((_e = searchSelectData.ids) == null ? void 0 : _e.length) === 0
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "", style: { marginTop: 24 } }, /* @__PURE__ */ import_react.default.createElement(
      import_List.default,
      {
        walletSetting,
        data: searchData,
        value: searchSelectData.ids,
        onChange: handleAddChange,
        loading
      }
    ))
  ), /* @__PURE__ */ import_react.default.createElement(
    import_pinVerifyModal.default,
    {
      ref: pinVerifyModalRef,
      onSuccess: (params) => {
        searchList({ customer_pin_key: params == null ? void 0 : params.customer_pin_key });
      }
    }
  ));
});
var WalletPass_default = (0, import_react.memo)(WalletPass);
