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/wallet/RechargeableCard/index.tsx
var RechargeableCard_exports = {};
__export(RechargeableCard_exports, {
  default: () => RechargeableCard_default
});
module.exports = __toCommonJS(RechargeableCard_exports);
var import_react = __toESM(require("react"));
var import_materials = require("@pisell/materials");
var import_model = require("./model");
var import_serve = require("./serve");
var import_useEngineContext = __toESM(require("./../../../hooks/useEngineContext"));
var import_serve2 = require("./../Detail/serve");
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("./../locales"));
var import_antd = require("antd");
var import_DetailContext = require("./../DetailContext");
var import_WalletCard = __toESM(require("../components/WalletCard"));
var import_index = require("./index.less");
var { Title } = import_materials.Typography;
var Amount = import_materials.PisellText.Amount;
var RechargeableCard = (0, import_model.Provider)(
  (props) => {
    var _a, _b, _c, _d;
    const { globalState, setGlobalState, handleAddWalletCard } = props;
    const recordViewRef = (0, import_react.useRef)(null);
    const { openDetail, renderDetail, closeDetail } = (0, import_DetailContext.useDetail)();
    const {
      currentId = "",
      currentDetail = {},
      gift_card = [],
      rechargeModalOpen = false
    } = globalState;
    const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
    const context = (0, import_useEngineContext.default)();
    const utils = context.appHelper.utils || {};
    const dvaStore = (_b = (_a = utils == null ? void 0 : utils.getStore) == null ? void 0 : _a.call(utils)) == null ? void 0 : _b.getState();
    const { action, storage } = utils || {};
    const platform = (0, import_react.useMemo)(() => (0, import_utils.isMobile)() ? "h5" : "pc", []);
    const handleBack = (0, import_react.useCallback)(() => {
      if (recordViewRef.current) {
        recordViewRef.current.closeDetailModal();
      }
      closeDetail();
      setGlobalState({
        setup: "list"
      });
    }, [recordViewRef, closeDetail, setGlobalState]);
    (0, import_react.useEffect)(() => {
      var _a2;
      import_utils.locales.init(import_locales.default, ((_a2 = dvaStore == null ? void 0 : dvaStore.core) == null ? void 0 : _a2.translateLocale) || "en");
    }, []);
    (0, import_react.useEffect)(() => {
      document.body.id = "body";
    }, []);
    const getDetail = async () => {
      try {
        const data = await (0, import_serve2.getDetailApi)({ id: currentId });
        const cardList = data.gift_option || [];
        dispatch({
          type: "setState",
          payload: {
            cardList,
            productId: data.product_id || "",
            detailId: data.id || "",
            // 如果有充值选项，则默认选中第一个
            ...cardList.length > 0 ? { selectedItem: cardList[0] } : {}
          }
        });
      } catch (error) {
        console.error(import_utils.locales.getText("page.wallet.log.getDetailFailed"), error);
      }
    };
    (0, import_react.useEffect)(() => {
      if (currentId && rechargeModalOpen) {
        getDetail();
      }
    }, [currentId, rechargeModalOpen]);
    (0, import_react.useEffect)(() => {
      var _a2;
      if (globalState.setup !== "detail") {
        (_a2 = recordViewRef.current) == null ? void 0 : _a2.closeDetailModal();
      }
    }, [globalState.setup]);
    (0, import_react.useEffect)(() => {
      if (currentId && gift_card.length > 0) {
        const card = gift_card.find((item) => item.id === currentId);
        if (card && (!(currentDetail == null ? void 0 : currentDetail.id) || currentDetail.id !== currentId)) {
          setGlobalState({
            currentDetail: card
          });
        }
      }
    }, [currentId, gift_card, currentDetail, setGlobalState]);
    (0, import_react.useEffect)(() => {
      const enabledCards = gift_card.filter(
        (item) => item.limit_status === "enable"
      );
      const total = enabledCards.reduce(
        (sum, item) => sum + Number(item.balance),
        0
      );
      dispatch({
        type: "setState",
        payload: { total }
      });
    }, [gift_card]);
    const renderItem = (0, import_react.useMemo)(() => {
      return (item) => {
        return /* @__PURE__ */ import_react.default.createElement(
          import_WalletCard.default,
          {
            item,
            currentId,
            onClick: () => {
              setGlobalState({
                type: "setState",
                payload: {
                  currentId: item.id
                }
              });
            }
          }
        );
      };
    }, [currentId, setGlobalState]);
    const detail = () => {
      var _a2;
      if (!(currentDetail == null ? void 0 : currentDetail.id)) return null;
      const detailWithButtons = {
        ...currentDetail,
        buttonGroupList: ((_a2 = currentDetail == null ? void 0 : currentDetail.machinecode_config) == null ? void 0 : _a2.hide_recharge) === 0 ? [
          [
            {
              isMore: false,
              buttonProps: {
                children: import_utils.locales.getText("page.wallet.recharge"),
                type: "primary",
                size: "large",
                block: true,
                onClick: () => {
                  setGlobalState({
                    rechargeModalOpen: true
                  });
                }
              }
            }
          ]
        ] : [[]],
        showWalletBar: platform === "h5",
        // 添加显示WalletBar的标志
        onBack: handleBack
        // 添加返回处理函数
      };
      return renderDetail(detailWithButtons);
    };
    const isEmpty = (0, import_react.useMemo)(() => {
      return !gift_card.some((item) => item.limit_status === "enable");
    }, [gift_card]);
    const formatData = () => {
      const available = {
        title: import_utils.locales.getText("page.wallet.available"),
        dataSource: gift_card.filter(
          (item) => item.limit_status === "enable"
        )
      };
      const unavailable = {
        title: import_utils.locales.getText("page.wallet.unavailable"),
        dataSource: gift_card.filter(
          (item) => item.limit_status === "disable"
        )
      };
      return [available, unavailable];
    };
    const shop = ((_d = (_c = dvaStore.core) == null ? void 0 : _c.core) == null ? void 0 : _d.shop) || {};
    const handleRecharge = async () => {
      try {
        const params = {
          voucher_id: state.detailId || "",
          product_id: state.productId || "",
          product_variant_id: state.selectedItem.variant_id || "",
          quantity: 1,
          type: "virtual",
          platform: "h5",
          currency_code: {
            currency_code: (shop == null ? void 0 : shop.currency_code) || "",
            currency_symbol: (shop == null ? void 0 : shop.currency_symbol) || "",
            currency_format: (shop == null ? void 0 : shop.currency_format) || ""
          }
        };
        const data = await (0, import_serve.goOrder)(params);
        if (data == null ? void 0 : data.order_id) {
          storage.set("orderId", data.order_id);
          action && action({
            type: "pisell1.payment",
            data,
            callback: () => {
            }
          });
        }
      } catch (error) {
        console.error(import_utils.locales.getText("page.wallet.log.rechargeOrderFailed"), error);
      }
    };
    const handleCloseRechargeModal = () => {
      setGlobalState({
        rechargeModalOpen: false
      });
      dispatch({
        type: "setState",
        payload: {
          selectedItem: {}
        }
      });
    };
    const handleSelectRechargeOption = (item) => {
      if (item.id === state.selectedItem.id) return;
      dispatch({
        type: "setState",
        payload: {
          selectedItem: item
        }
      });
    };
    const handleRowClick = (currentDetail2) => {
      var _a2;
      setGlobalState({
        currentId: currentDetail2.id || "",
        currentDetail: currentDetail2,
        setup: "detail"
        // 设置状态为detail
      });
      const detailWithButtons = {
        ...currentDetail2,
        buttonGroupList: ((_a2 = currentDetail2 == null ? void 0 : currentDetail2.machinecode_config) == null ? void 0 : _a2.hide_recharge) === 0 ? [
          [
            {
              isMore: false,
              buttonProps: {
                children: import_utils.locales.getText("page.wallet.recharge"),
                type: "primary",
                size: "large",
                block: true,
                onClick: () => {
                  setGlobalState({
                    rechargeModalOpen: true
                  });
                }
              }
            }
          ]
        ] : [[]],
        showWalletBar: platform === "h5",
        // 添加显示WalletBar的标志
        onBack: handleBack
        // 添加返回处理函数
      };
      openDetail(detailWithButtons);
    };
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, platform !== "pc" && /* @__PURE__ */ import_react.default.createElement("div", { className: "wallet-rechargeableCard-title" }, import_utils.locales.getText("page.wallet.rechargeableCard")), isEmpty ? /* @__PURE__ */ import_react.default.createElement(import_materials.PisellEmpty, null) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      import_materials.CardMetricItem,
      {
        title: import_utils.locales.getText("page.wallet.cardBalance"),
        style: { marginBottom: 24 },
        hint: false,
        tags: false,
        number: (state == null ? void 0 : state.total) || 0
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_materials.RecordView,
      {
        ref: recordViewRef,
        mobilePadDetailModalDisplay: true,
        leftSpan: 9,
        rightSpan: 15,
        gutter: 20,
        onRowClick: handleRowClick,
        modalWrapStyle: {
          overflowY: "auto",
          top: 0,
          height: "100%",
          zIndex: 998,
          position: "fixed",
          left: 0,
          right: 0
        },
        pcDetailModalDisplay: platform === "h5" ? true : false,
        padDetailModalDisplay: true,
        isShowClode: false,
        split: false,
        children: null,
        detail: detail(),
        emptyButtons: [],
        doubleList: true,
        doubleListSource: formatData(),
        dataSource: gift_card,
        renderItem
      }
    )), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Drawer,
      {
        title: import_utils.locales.getText("page.wallet.rechargeOptions"),
        open: rechargeModalOpen,
        zIndex: 999,
        onClose: handleCloseRechargeModal,
        width: 375,
        placement: platform === "pc" ? "right" : "bottom",
        footer: /* @__PURE__ */ import_react.default.createElement(
          import_antd.Button,
          {
            type: "primary",
            block: true,
            size: "large",
            onClick: handleRecharge,
            disabled: !state.selectedItem.id
          },
          import_utils.locales.getText("page.wallet.recharge")
        )
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "recharge-options" }, state.cardList.map((item) => /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key: item.id,
          onClick: () => handleSelectRechargeOption(item)
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_materials.PisellCard,
          {
            className: `pisell-card-item ${item.id === state.selectedItem.id ? "pisell-card-selected" : ""}`
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "card-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "card-content-left" }, /* @__PURE__ */ import_react.default.createElement("p", { className: "pisell-card-amount-item-name" }, item.name), /* @__PURE__ */ import_react.default.createElement(
            Amount,
            {
              showCurrencySymbol: true,
              className: "pisell-card-amount-item-value",
              useThousandsSeparator: true,
              value: item.gift_price
            }
          )), /* @__PURE__ */ import_react.default.createElement(
            Amount,
            {
              showCurrencySymbol: true,
              className: "pisell-card-amount-item-value",
              useThousandsSeparator: true,
              value: item.price
            }
          ))
        )
      )))
    ));
  }
);
var RechargeableCard_default = RechargeableCard;
