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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
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/index.tsx
var wallet_exports = {};
__export(wallet_exports, {
  DetailProvider: () => import_DetailContext.DetailProvider,
  WalletCard: () => import_WalletCard.default,
  default: () => wallet_default,
  useDetail: () => import_DetailContext.useDetail
});
module.exports = __toCommonJS(wallet_exports);
var import_react = __toESM(require("react"));
var import_model = require("./model");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_icons = require("@ant-design/icons");
var import_serve = require("./serve");
var import_locales = __toESM(require("./locales"));
var import_utils2 = require("./../../utils");
var import_useEngineContext = __toESM(require("./../../hooks/useEngineContext"));
var import_RechargeableCard = __toESM(require("./RechargeableCard"));
var import_DiscountCard = __toESM(require("./DiscountCard"));
var import_PointCard = __toESM(require("./PointCard"));
var import_Voucher = __toESM(require("./Voucher/index"));
var import_WalletBar = __toESM(require("./components/WalletBar"));
var import_index = require("./index.less");
var import_DetailContext = require("./DetailContext");
var import_WalletCard = __toESM(require("./components/WalletCard"));
__reExport(wallet_exports, require("./utils/formatUtils"), module.exports);
__reExport(wallet_exports, require("./hooks/useWalletCard"), module.exports);
__reExport(wallet_exports, require("./serve"), module.exports);
__reExport(wallet_exports, require("./model"), module.exports);
var { Title } = import_materials.Typography;
var Wallet = (0, import_model.Provider)(() => {
  var _a, _b, _c, _d;
  const { global_wallet, dispatch } = (0, import_react.useContext)(import_model.Context);
  const {
    list = {},
    currentId,
    setup,
    currentTag,
    addWalletCode,
    searchList = [],
    currentSearchListItemCode = "",
    addModalOpen = false,
    currentDetail = {}
  } = global_wallet;
  const context = (0, import_useEngineContext.default)();
  const utils = ((_a = context == null ? void 0 : context.appHelper) == null ? void 0 : _a.utils) || {};
  const platform = (0, import_react.useMemo)(() => {
    if (utils.isMobile) {
      return utils.isMobile() ? "h5" : "pc";
    }
    if (typeof window !== "undefined") {
      return window.innerWidth <= 768 ? "h5" : "pc";
    }
    return "pc";
  }, [utils]);
  const dvaStore = (_c = (_b = utils == null ? void 0 : utils.getStore) == null ? void 0 : _b.call(utils)) == null ? void 0 : _c.getState();
  import_utils.locales.init(import_locales.default, ((_d = dvaStore == null ? void 0 : dvaStore.core) == null ? void 0 : _d.translateLocale) || "en");
  import_utils2.request.setRequest(utils == null ? void 0 : utils.request);
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
    getList({ num: 999, skip: 1 });
  }, []);
  const transformData = (data) => {
    const result = {};
    data == null ? void 0 : data.forEach((item) => {
      const { tag, par_value } = item;
      if (!tag) {
        console.warn("[transformData] Missing tag in item", item);
        return;
      }
      if (!result[tag]) {
        result[tag] = [];
      }
      if (tag === "product_discount_card") {
        const numericVal = parseFloat(par_value || "0");
        if (isNaN(numericVal) || numericVal <= 0) {
          return;
        }
      }
      if (tag === "good_pass") {
        if (!result["product_voucher"]) {
          result["product_voucher"] = [];
        }
        result["product_voucher"].push(item);
      }
      result[tag].push(item);
    });
    return result;
  };
  const getList = async (params, addWalletCode2) => {
    var _a2, _b2, _c2;
    try {
      let { list: list2 = [] } = await (0, import_serve.getWalletList)(params) || {};
      const formatData = transformData(list2);
      dispatch({ type: "setState", payload: formatData });
      if (addWalletCode2) {
        let addWalletItem = list2.filter(
          (item) => item.code === addWalletCode2 || item.encoded === addWalletCode2
        );
        dispatch({
          type: "setState",
          payload: {
            currentTag: ((_a2 = addWalletItem[0]) == null ? void 0 : _a2.tag) || "",
            currentId: ((_b2 = addWalletItem[0]) == null ? void 0 : _b2.id) || "",
            currentDetail: addWalletItem[0],
            addWalletCode: ""
          }
        });
        return;
      }
      const giftCards = formatData["gift_card"];
      if (giftCards && giftCards.length && !currentId) {
        dispatch({
          type: "setState",
          payload: {
            currentTag: "gift_card",
            currentId: ((_c2 = giftCards[0]) == null ? void 0 : _c2.id) || "",
            currentDetail: giftCards[0]
          }
        });
      }
    } catch (err) {
      console.error(err);
    }
  };
  const getBadge = (data, key) => {
    return data.filter(
      (item) => item.limit_status === "enable"
    ).length;
  };
  const handleTabChange = (key) => {
    dispatch({ type: "setState", payload: { currentTag: key } });
    if (platform === "pc") {
      const items = global_wallet[key];
      if (items && items.length > 0) {
        dispatch({
          type: "setState",
          payload: {
            currentId: items[0].id,
            currentDetail: items[0]
          }
        });
      }
    } else {
      dispatch({
        type: "setState",
        payload: {
          setup: "list",
          currentId: "",
          // 清空当前ID
          currentDetail: null
          // 清空当前详情
        }
      });
    }
  };
  const renderCardComponent = (cardType) => {
    const setGlobalState = (payload) => dispatch({ type: "setState", payload });
    const props = {
      globalState: global_wallet,
      setGlobalState
    };
    switch (cardType) {
      case "gift_card":
        return /* @__PURE__ */ import_react.default.createElement(import_RechargeableCard.default, { ...props });
      case "product_voucher":
        return /* @__PURE__ */ import_react.default.createElement(import_Voucher.default, { ...props });
      case "point_card":
        return /* @__PURE__ */ import_react.default.createElement(import_PointCard.default, { ...props });
      case "product_discount_card":
        return /* @__PURE__ */ import_react.default.createElement(import_DiscountCard.default, { ...props });
      default:
        return null;
    }
  };
  const TabsProps = {
    className: "pisell-lowcode__wallet__tabs",
    defaultActiveKey: "gift_card",
    onChange: handleTabChange,
    type: "line",
    items: [
      {
        key: "gift_card",
        label: import_utils.locales.getText("page.wallet.rechargeableCard"),
        children: renderCardComponent("gift_card"),
        badge: getBadge(global_wallet.gift_card, "gift_card")
      },
      {
        key: "product_voucher",
        label: import_utils.locales.getText("page.wallet.voucher"),
        children: renderCardComponent("product_voucher"),
        badge: getBadge(global_wallet.product_voucher, "product_voucher")
      },
      {
        key: "point_card",
        label: import_utils.locales.getText("page.wallet.pointCard"),
        children: renderCardComponent("point_card"),
        badge: getBadge(global_wallet.point_card, "point_card")
      },
      {
        key: "product_discount_card",
        label: import_utils.locales.getText("page.wallet.discountCard"),
        children: renderCardComponent("product_discount_card"),
        badge: getBadge(
          global_wallet.product_discount_card,
          "product_discount_card"
        )
      }
    ]
  };
  const menuItem = ({ count = 0, title = "" }) => /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-menu-item" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode-wallet-menu-title" }, title), count > 0 && /* @__PURE__ */ import_react.default.createElement(import_materials.Badge, { styleType: "default", count })), /* @__PURE__ */ import_react.default.createElement(import_icons.RightOutlined, null));
  const mergeSearch = (currentSearch, params) => {
    const searchParams = new URLSearchParams(currentSearch);
    Object.entries(params).forEach(([key, value]) => {
      searchParams.set(key, value);
    });
    return searchParams.toString();
  };
  const MenuProps = {
    className: "pisell-lowcode-wallet-menu",
    onClick: (e) => {
      var _a2, _b2;
      (_b2 = (_a2 = context.appHelper.utils) == null ? void 0 : _a2.history) == null ? void 0 : _b2.push({
        hash: location.hash,
        search: mergeSearch(location.search, { type: "list" })
      });
      dispatch({
        type: "setState",
        payload: {
          setup: "list",
          currentTag: e.key,
          currentId: "",
          currentDetail: {}
        }
      });
    },
    items: [
      {
        key: "gift_card",
        label: menuItem({
          title: import_utils.locales.getText("page.wallet.rechargeableCard"),
          count: getBadge(global_wallet.gift_card, "gift_card")
        })
      },
      {
        key: "product_voucher",
        label: menuItem({
          title: import_utils.locales.getText("page.wallet.voucher"),
          count: getBadge(global_wallet.product_voucher, "product_voucher")
        })
      },
      {
        key: "point_card",
        label: menuItem({
          title: import_utils.locales.getText("page.wallet.pointCard"),
          count: getBadge(global_wallet.point_card, "point_card")
        })
      },
      {
        key: "product_discount_card",
        label: menuItem({
          title: import_utils.locales.getText("page.wallet.discountCard"),
          count: getBadge(
            global_wallet.product_discount_card,
            "product_discount_card"
          )
        })
      }
    ]
  };
  (0, import_react.useEffect)(() => {
    const searchParams = new URLSearchParams(location.search);
    const type = searchParams.get("type");
    if (type) {
      dispatch({ type: "setState", payload: { setup: type } });
    } else {
      dispatch({ type: "setState", payload: { setup: "menu" } });
    }
  }, [location.search]);
  const onBack = () => {
    if (setup === "menu") {
      history.back();
    } else {
      const prevSetup = setup === "detail" ? "list" : "menu";
      dispatch({ type: "setState", payload: { setup: prevSetup } });
      history.back();
    }
  };
  const openAddModal = () => {
    dispatch({ type: "setState", payload: { addModalOpen: true } });
  };
  const closeAddModal = () => {
    dispatch({
      type: "setState",
      payload: {
        addModalOpen: false,
        searchList: [],
        currentSearchListItemCode: ""
      }
    });
  };
  const addWallet = async (code) => {
    const onError = () => {
      (0, import_materials.PisellToast)({
        content: import_utils.locales.getText("page.wallet.addError"),
        duration: 2
      });
      dispatch({ type: "setState", payload: { addModalOpen: false } });
    };
    const data = await (0, import_serve.customer)({ code }, onError);
    if (data) {
      const tagMap = {
        gift_card: "rechargeableCard",
        product_voucher: "voucher",
        point_card: "pointCard",
        product_discount_card: "discountCard"
      };
      const cardType = tagMap[currentTag];
      const successMessage = `${import_utils.locales.getText(
        `page.wallet.${cardType}`
      )} ${import_utils.locales.getText("page.wallet.addSuccess")}`;
      (0, import_materials.PisellToast)({
        content: successMessage,
        duration: 2
      });
      getList({ num: 999, skip: 1 }, code);
    }
    dispatch({
      type: "setState",
      payload: {
        addModalOpen: false,
        searchList: [],
        currentSearchListItemCode: ""
      }
    });
  };
  const handleSearch = async (code = "") => {
    const resetSearchState = () => {
      dispatch({
        type: "setState",
        payload: {
          searchList: [],
          currentSearchListItemCode: ""
        }
      });
    };
    if (!code.trim()) {
      resetSearchState();
      return;
    }
    const onSearchFail = () => {
      resetSearchState();
      (0, import_materials.PisellToast)({
        content: import_utils.locales.getText("page.wallet.searchNoFound"),
        duration: 2
      });
    };
    try {
      const data = await (0, import_serve.unbindList)(
        { code, tag: global_wallet.currentTag },
        onSearchFail
      );
      if (Array.isArray(data) && data.length > 0) {
        dispatch({
          type: "setState",
          payload: {
            searchList: data,
            currentSearchListItemCode: data[0].code || ""
          }
        });
      } else {
        onSearchFail();
      }
    } catch (error) {
      console.error("[handleSearch] error:", error);
      onSearchFail();
    }
  };
  const renderPcLayout = () => /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-pc" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-header" }, /* @__PURE__ */ import_react.default.createElement(Title, { className: "pisell-lowcode-wallet-title" }, import_utils.locales.getText("page.wallet.wallet")), /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null), size: "large", onClick: openAddModal }, import_utils.locales.getText("page.wallet.add"))), /* @__PURE__ */ import_react.default.createElement(import_materials.Tabs, { ...TabsProps }));
  const renderMobileContent = () => {
    const renderTitle = () => {
      if (setup === "menu") {
        return /* @__PURE__ */ import_react.default.createElement(Title, { className: "pisell-lowcode-wallet-title" }, import_utils.locales.getText("page.wallet.wallet"));
      }
      return null;
    };
    const renderContent = () => {
      switch (setup) {
        case "menu":
          return /* @__PURE__ */ import_react.default.createElement(import_materials.Menu, { ...MenuProps });
        case "list":
        case "detail":
          return renderCardComponent(currentTag);
        default:
          return renderCardComponent(currentTag);
      }
    };
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, renderTitle(), renderContent());
  };
  const renderMobileFooter = () => {
    if (setup === "menu") {
      return null;
    }
    if (setup === "list") {
      return /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          block: true,
          size: "large",
          className: "pisell-lowcode-wallet-add",
          type: "default",
          onClick: openAddModal
        },
        import_utils.locales.getText("page.wallet.add")
      );
    }
    return null;
  };
  const renderMobileLayout = () => {
    var _a2, _b2, _c2;
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-mobile" }, !((_c2 = (_b2 = (_a2 = utils == null ? void 0 : utils.interaction) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.isAppEnv) == null ? void 0 : _c2.call(_b2)) && /* @__PURE__ */ import_react.default.createElement(import_WalletBar.default, { setup, onBack }), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-content" }, renderMobileContent()), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode-wallet-footer" }, renderMobileFooter()));
  };
  const renderSearchCard = (item) => {
    const {
      id,
      product_name = "",
      balance = 0,
      code = "",
      encoded = "",
      expire_date = "",
      shop,
      limit_status,
      product_cover = "",
      unified_messages = {},
      par_value = ""
    } = item;
    const { title = "" } = unified_messages;
    const { name = "" } = shop;
    const isActive = code === currentSearchListItemCode && platform === "pc";
    const isEnabled = limit_status === "enable";
    const isDiscountCard = currentTag === "product_discount_card";
    const handleCardClick = () => {
      dispatch({
        type: "setState",
        payload: {
          currentSearchListItemCode: code
        }
      });
    };
    const getBalanceTitle = () => {
      if (global_wallet.currentTag === "point_card") {
        return import_utils.locales.getText("page.wallet.points");
      } else if (global_wallet.currentTag === "good_pass") {
        return import_utils.locales.getText("page.wallet.goodPass");
      }
      return void 0;
    };
    return /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellWalletPassCard,
      {
        balanceTitle: getBalanceTitle(),
        showDetail: false,
        showRedeem: false,
        showQrCode: false,
        cover: product_cover,
        disabled: !isEnabled,
        showDisabledReason: !isEnabled,
        disabledReason: title,
        propStyle: { marginBottom: 10 },
        showBalanceSymbol: global_wallet.currentTag !== "point_card",
        showBalance: global_wallet.currentTag !== "product_discount_card",
        active: isActive,
        name: product_name,
        qrCode: code,
        storeName: name,
        balance: Number(balance),
        code: encoded,
        discount: Number(par_value),
        showDiscount: isDiscountCard,
        validDate: expire_date,
        onClick: handleCardClick
      }
    );
  };
  const getAddModalClassName = () => {
    return addModalOpen ? "wallet-add-modal" : "pisell-lowcode__wallet__addModal";
  };
  return /* @__PURE__ */ import_react.default.createElement(import_DetailContext.DetailProvider, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-wallet-container", style: { height: "100%" } }, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode-wallet",
      style: {
        height: platform === "pc" ? "auto" : "100%",
        width: platform === "pc" ? 960 : "100vw",
        padding: platform === "pc" ? 20 : 0
      }
    },
    platform === "pc" ? renderPcLayout() : renderMobileLayout()
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      className: getAddModalClassName(),
      title: import_utils.locales.getText("page.wallet.add"),
      platform: platform === "pc" ? "pc" : "h5",
      mobileModalHeight: "auto",
      open: addModalOpen,
      onCancel: closeAddModal,
      cancelVisible: false,
      destroyOnClose: true,
      okText: import_utils.locales.getText("page.wallet.confirm"),
      okButtonProps: { disabled: !currentSearchListItemCode },
      onOk: () => addWallet(currentSearchListItemCode)
    },
    /* @__PURE__ */ import_react.default.createElement("div", { style: { margin: "24px 0" } }, /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellInformationEntry,
      {
        title: import_utils.locales.getText("page.wallet.addModalTitle"),
        entryModes: [
          {
            type: "scanCode",
            name: import_utils.locales.getText("page.wallet.scanBarQrCode")
          },
          {
            type: "input",
            name: import_utils.locales.getText("page.wallet.enterCodes")
          }
        ],
        searchDescribe: import_utils.locales.getText("page.wallet.searchDescribe"),
        onChange: (e) => handleSearch(e),
        onChangeType: () => {
          dispatch({
            type: "setState",
            payload: { searchList: [], currentSearchListItemCode: "" }
          });
        }
      }
    ), searchList.map((item) => renderSearchCard(item)))
  )));
});
var wallet_default = Wallet;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DetailProvider,
  WalletCard,
  useDetail,
  ...require("./utils/formatUtils"),
  ...require("./hooks/useWalletCard"),
  ...require("./serve"),
  ...require("./model")
});
