import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import { request } from "../../utils/index.js";
import { DEFAULT_CARD_CONFIG } from "./types/index.js";
import { Context, Provider } from "./model.js";
import { batchGetWalletBalance, getWalletList, getWalletShopList, updateWalletHolder } from "./serve.js";
import { defaultWalletGuideConfig } from "./status.js";
import locales_default from "./locales.js";
import TempHolderSelector from "./tempHolderSelector/index.js";
import pinModal_default from "../pinModal/index.js";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { getUniqueId, locales } from "@pisell/utils";
import { Carousel, WalletCard } from "@pisell/materials";
import classNames from "classnames";
import { LeftOutlined, RightOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/components/walletList/index.tsx
const STORAGE_KEY = "pisell_wallet_list_data";
const STORAGE_KEY_BALANCE = "pisell_wallet_balance_data";
const safeLocalStorage = {
	getItem: (key) => {
		try {
			return typeof localStorage !== "undefined" ? localStorage.getItem(key) : null;
		} catch (error) {
			console.error("Error accessing localStorage:", error);
			return null;
		}
	},
	setItem: (key, value) => {
		try {
			if (typeof localStorage !== "undefined") localStorage.setItem(key, value);
		} catch (error) {
			console.error("Error writing to localStorage:", error);
		}
	}
};
const saveToLocalStorage = (key, data) => {
	try {
		safeLocalStorage.setItem(key, JSON.stringify(data));
	} catch (error) {
		console.error("Error saving to localStorage:", error);
	}
};
const getFromLocalStorage = (key) => {
	try {
		const data = safeLocalStorage.getItem(key);
		return data ? JSON.parse(data) : null;
	} catch (error) {
		console.error("Error reading from localStorage:", error);
		return null;
	}
};
const getLocalizedName = (name, translateLocale) => {
	if (!name) return "";
	return name[translateLocale || "en"] || name.original || "";
};
const DEFAULT_WALLET_CARD = {
	id: "default-wallet-card",
	code: "Wallet number",
	shop: { name: "Store name" },
	isLogin: false,
	showIcon: true,
	icon: "",
	wallet: {
		name: {
			original: "Level",
			"zh-CN": "Level",
			"zh-HK": "Level",
			"ja": "Level",
			"pt": "Level",
			en: "Level"
		},
		metadata: {
			showcaseWalletPassNew: [
				{
					type: "rechargeable",
					display: 1,
					custom_title: {
						original: "Balance",
						"zh-CN": "充值卡",
						"zh-HK": "充值卡",
						"ja": "充值卡",
						"pt": "Cartão de recarga",
						en: "Balance"
					}
				},
				{
					type: "point",
					display: 1,
					custom_title: {
						original: "Points",
						"zh-CN": "积分卡",
						"zh-HK": "積分卡",
						"ja": "ポイントカード",
						"pt": "Pontos",
						en: "Points"
					}
				},
				{
					type: "voucher",
					display: 1,
					custom_title: {
						original: "Voucher",
						"zh-CN": "代金券",
						"zh-HK": "代金券",
						"ja": "クーポン",
						"pt": "Cupom",
						en: "Voucher"
					}
				},
				{
					type: "discount",
					display: 1,
					custom_title: {
						original: "Discount",
						"zh-CN": "折扣卡",
						"zh-HK": "折扣卡",
						"ja": "割引カード",
						"pt": "Cartão de desconto",
						en: "Discount"
					}
				}
			],
			coverImage: "",
			icon: ""
		}
	}
};
const DEFAULT_BALANCE = {
	gift_card_balance: 0,
	point_card_balance: 0,
	voucher_count: 0,
	discount_card_count: 0,
	good_pass_count: 0
};
const WalletList = Provider((props) => {
	var _utils$getStore, _context$engine, _store$getState;
	const { globalState = {} } = props;
	const { state, dispatch } = useContext(Context);
	const context = useEngineContext();
	const { constants, utils } = context.appHelper || {};
	const dvaStore = utils === null || utils === void 0 || (_utils$getStore = utils.getStore) === null || _utils$getStore === void 0 || (_utils$getStore = _utils$getStore.call(utils)) === null || _utils$getStore === void 0 ? void 0 : _utils$getStore.getState();
	locales.init(locales_default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
	const isMountedRef = useRef(true);
	const carouselRef = useRef(null);
	const { store } = utils;
	const symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || "$";
	const prevButtonRef = useRef(null);
	const nextButtonRef = useRef(null);
	const [currentIndex, setCurrentIndex] = useState(0);
	const [walletShopList, setWalletShopList] = useState([]);
	const [editHolderVisible, setEditHolderVisible] = useState(false);
	const [editHolderData, setEditHolderData] = useState(null);
	const [updateHolderLoading, setUpdateHolderLoading] = useState(false);
	const requestIdRef = useRef("");
	const pubsub = utils === null || utils === void 0 ? void 0 : utils.pubsub;
	const pinModalRef = useRef(null);
	const isUserLoggedIn = useMemo(() => {
		var _utils$token, _utils$token$get;
		return !!(utils === null || utils === void 0 || (_utils$token = utils.token) === null || _utils$token === void 0 || (_utils$token$get = _utils$token.get) === null || _utils$token$get === void 0 ? void 0 : _utils$token$get.call(_utils$token)) || false;
	}, [store]);
	const { list = [], error, authError, hasAttempted, isLoggedIn } = state;
	useEffect(() => {
		if (utils === null || utils === void 0 ? void 0 : utils.request) request.setRequest(utils.request);
	}, [utils === null || utils === void 0 ? void 0 : utils.request]);
	useEffect(() => {
		if (isUserLoggedIn) {
			getWalletShopList({
				skip: 1,
				num: 50
			}).then((res) => {
				pubsub.publish("wallet:shopList", res);
			});
			const subscription = pubsub.subscribe("wallet:shopList", (res) => {
				setWalletShopList((res === null || res === void 0 ? void 0 : res.list) || []);
			});
			return () => {
				subscription.unsubscribe();
			};
		}
	}, [isUserLoggedIn]);
	useEffect(() => {
		return () => {
			isMountedRef.current = false;
			requestIdRef.current = "";
		};
	}, []);
	useEffect(() => {
		if (hasAttempted) return;
		if (!isUserLoggedIn) {
			if (isMountedRef.current) setState({
				list: [DEFAULT_WALLET_CARD],
				balance: [],
				hasAttempted: true,
				isLoggedIn: false
			});
			return;
		}
		const currentRequestId = Date.now().toString();
		requestIdRef.current = currentRequestId;
		(function() {
			var _ref = _asyncToGenerator(function* () {
				if (!isMountedRef.current) return;
				if (requestIdRef.current !== currentRequestId) return;
				yield initData(currentRequestId);
			});
			return function fetchData() {
				return _ref.apply(this, arguments);
			};
		})()().catch((err) => {
			if (isMountedRef.current) console.error("请求数据出错:", err);
		});
	}, [hasAttempted, isUserLoggedIn]);
	useEffect(() => {
		const timer = setTimeout(() => {
			if (!isMountedRef.current) return;
			const prevButton = document.querySelector(".pisell-lowcode__walletList .slick-prev");
			const nextButton = document.querySelector(".pisell-lowcode__walletList .slick-next");
			if (prevButton) prevButtonRef.current = prevButton;
			if (nextButton) nextButtonRef.current = nextButton;
		}, 300);
		return () => clearTimeout(timer);
	}, [list]);
	useEffect(() => {
		if (!isMountedRef.current) return;
		const timerId = setTimeout(() => {
			if (!isMountedRef.current) return;
		}, 500);
		return () => {
			clearTimeout(timerId);
		};
	}, [list]);
	const handleAfterChange = (current) => {
		if (isMountedRef.current) setCurrentIndex(current);
	};
	const setState = useCallback((payload) => {
		if (isMountedRef.current) dispatch({
			type: "setState",
			payload
		});
	}, [dispatch]);
	const handlePrevClick = (e) => {
		e.stopPropagation();
		e.preventDefault();
		if (currentIndex === 0) return;
		const newIndex = currentIndex - 1;
		if (isMountedRef.current) setCurrentIndex(newIndex);
		if (isMountedRef.current && carouselRef.current && typeof carouselRef.current.goTo === "function") carouselRef.current.goTo(newIndex);
	};
	const handleNextClick = (e) => {
		e.stopPropagation();
		e.preventDefault();
		if (currentIndex === list.length - 1) return;
		const newIndex = currentIndex + 1;
		if (isMountedRef.current) setCurrentIndex(newIndex);
		if (isMountedRef.current && carouselRef.current && typeof carouselRef.current.goTo === "function") carouselRef.current.goTo(newIndex);
	};
	const initData = function() {
		var _ref2 = _asyncToGenerator(function* (requestId) {
			if (!isMountedRef.current) return;
			if (requestIdRef.current !== requestId) return;
			if (!isUserLoggedIn) {
				setState({
					list: [DEFAULT_WALLET_CARD],
					balance: [],
					hasAttempted: true,
					isLoggedIn: false
				});
				return;
			}
			if (hasAttempted) return;
			let cachedList = null;
			let cachedBalance = null;
			try {
				cachedList = getFromLocalStorage(STORAGE_KEY);
				cachedBalance = getFromLocalStorage(STORAGE_KEY_BALANCE);
				if (!Array.isArray(cachedBalance) || !cachedBalance.some((item) => {
					var _item$hasOwnProperty;
					return (_item$hasOwnProperty = item.hasOwnProperty) === null || _item$hasOwnProperty === void 0 ? void 0 : _item$hasOwnProperty.call(item, "gift_card_balance");
				})) cachedBalance = null;
			} catch (e) {
				console.error("Error fetching from localStorage:", e);
			}
			if (cachedList && cachedBalance) setState({
				list: cachedList,
				balance: cachedBalance,
				hasAttempted: false
			});
			let tempList = [];
			try {
				if (!isMountedRef.current) return;
				const walletListData = yield getWalletList();
				const walletBalanceData = yield batchGetWalletBalance(walletListData.map((item) => item.wallet_id));
				if (!isMountedRef.current || requestIdRef.current !== requestId) return;
				if (walletListData) try {
					saveToLocalStorage(STORAGE_KEY, walletListData);
				} catch (e) {
					console.error("Error saving wallet list to localStorage:", e);
				}
				if (walletBalanceData) try {
					saveToLocalStorage(STORAGE_KEY_BALANCE, walletBalanceData);
				} catch (e) {
					console.error("Error saving wallet balance to localStorage:", e);
				}
				if (!walletBalanceData || Array.isArray(walletListData) && walletListData.length === 0) setTimeout(_asyncToGenerator(function* () {
					if (!isMountedRef.current || requestIdRef.current !== requestId) return;
					try {
						let retryBalanceData = walletBalanceData;
						let retryListData = walletListData;
						if (Array.isArray(walletListData) && walletListData.length === 0) {
							retryListData = yield getWalletList();
							if (retryListData && retryListData.length > 0) try {
								saveToLocalStorage(STORAGE_KEY, retryListData);
							} catch (e) {
								console.error("Error saving retry list to localStorage:", e);
							}
						}
						if (!walletBalanceData) {
							retryBalanceData = yield batchGetWalletBalance(retryListData.map((item) => item.wallet_id));
							if (retryBalanceData) try {
								saveToLocalStorage(STORAGE_KEY_BALANCE, retryBalanceData);
							} catch (e) {
								console.error("Error saving retry balance to localStorage:", e);
							}
						}
						setState({
							list: retryListData || [],
							balance: retryBalanceData,
							hasAttempted: true
						});
						tempList = retryListData || [];
					} catch (retryErr) {
						setState({
							list: walletListData || [],
							balance: walletBalanceData,
							hasAttempted: true
						});
						tempList = walletListData || [];
					}
				}), 2e3);
				else {
					setState({
						list: walletListData || [],
						balance: walletBalanceData,
						hasAttempted: true
					});
					tempList = walletListData || [];
				}
			} catch (err) {
				var _message, _data;
				if (!isMountedRef.current || requestIdRef.current !== requestId) return;
				const isAuthError = (err === null || err === void 0 ? void 0 : err.code) === 4001 || (err === null || err === void 0 || (_message = err.message) === null || _message === void 0 ? void 0 : _message.includes("login time out")) || (err === null || err === void 0 || (_data = err.data) === null || _data === void 0 ? void 0 : _data.code) === 4001;
				setState({
					error: err instanceof Error ? err : /* @__PURE__ */ new Error("加载失败"),
					authError: isAuthError,
					hasAttempted: true
				});
			}
			const walletDetailId = new URLSearchParams(window.location.search).get("wallet_detail_id");
			if (walletDetailId) {
				const found = tempList.find((item) => String(item.id) === walletDetailId);
				if (found) {
					var _carouselRef$current, _found$holder, _found$holder2;
					setCurrentIndex(tempList.indexOf(found));
					(_carouselRef$current = carouselRef.current) === null || _carouselRef$current === void 0 || _carouselRef$current.goTo(tempList.indexOf(found), true);
					if (((_found$holder = found.holder) === null || _found$holder === void 0 ? void 0 : _found$holder.holder_type) === "form" && !((_found$holder2 = found.holder) === null || _found$holder2 === void 0 ? void 0 : _found$holder2.holder_id)) {
						var _found$holder3, _found$holder4;
						setEditHolderData({
							wallet_record_id: found.id,
							customer_id: (_found$holder3 = found.holder) === null || _found$holder3 === void 0 ? void 0 : _found$holder3.customer_id,
							form_id: ((_found$holder4 = found.holder) === null || _found$holder4 === void 0 || (_found$holder4 = _found$holder4.metadata) === null || _found$holder4 === void 0 ? void 0 : _found$holder4.custom_id) || ""
						});
						setEditHolderVisible(true);
					}
				}
			}
		});
		return function initData(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const onViewPinClick = (card) => {
		if (card === null || card === void 0 ? void 0 : card.id) {
			var _pinModalRef$current;
			(_pinModalRef$current = pinModalRef.current) === null || _pinModalRef$current === void 0 || _pinModalRef$current.open(card === null || card === void 0 ? void 0 : card.id);
		} else console.error("onViewPinClick方法需要传入wallet_detail_id");
	};
	const onBindHolder = function() {
		var _ref3 = _asyncToGenerator(function* (holderId) {
			if (!(editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.wallet_record_id)) {
				console.error("wallet_record_id is required");
				return;
			}
			setUpdateHolderLoading(true);
			try {
				const res = yield updateWalletHolder(editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.wallet_record_id, {
					holder_id: holderId,
					holder_type: "form"
				});
				setEditHolderVisible(false);
				setEditHolderData(null);
				let newList = list;
				if (holderId) {
					if (res) newList = newList.map((item) => {
						if (item.id === (editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.wallet_record_id)) return _objectSpread2(_objectSpread2({}, item), {}, { holder: res });
						return item;
					});
				} else newList = newList.map((item) => {
					if (item.id === (editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.wallet_record_id)) return _objectSpread2(_objectSpread2({}, item), {}, { holder: null });
					return item;
				});
				setState({ list: newList });
			} catch (error) {
				console.error("Error updating wallet holder:", error);
			} finally {
				setUpdateHolderLoading(false);
			}
		});
		return function onBindHolder(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	const renderWalletCard = (item) => {
		var _dvaStore$core;
		const { code, shop, wallet, id, customer_id, holder } = item;
		const { metadata, name } = wallet || {};
		const { showcaseWalletPassNew = [], coverImage = "", icon = "" } = metadata || {};
		const { name: shopName } = shop;
		const { balance = [] } = state;
		const balanceItem = balance.find((bi) => bi.wallet_id == item.wallet_id) || DEFAULT_BALANCE;
		const _balanceKeyMap = {
			rechargeable: "gift_card_balance",
			point: "point_card_balance",
			voucher: "voucher_count",
			discount: "discount_card_count"
		};
		const cardItems = showcaseWalletPassNew.map((showCaseItem) => {
			const balanceKey = _balanceKeyMap[showCaseItem.type];
			let value = balanceKey ? balanceItem[balanceKey] || 0 : 0;
			if (showCaseItem.type === "voucher") value += balanceItem.good_pass_count || 0;
			return _objectSpread2(_objectSpread2({}, showCaseItem), {}, { value });
		});
		const cardProps = _objectSpread2(_objectSpread2(_objectSpread2({}, DEFAULT_CARD_CONFIG), globalState), {}, {
			id: wallet.id,
			iconImg: icon,
			symbol,
			cardNo: code,
			walletName: getLocalizedName(name, dvaStore === null || dvaStore === void 0 || (_dvaStore$core = dvaStore.core) === null || _dvaStore$core === void 0 ? void 0 : _dvaStore$core.translateLocale),
			shopName,
			items: cardItems.slice(0, 4),
			customBackgroundImage: coverImage,
			isLogin: isUserLoggedIn,
			holder,
			onSetHolder: () => {
				var _holder$metadata;
				setEditHolderData({
					wallet_record_id: id,
					customer_id: holder === null || holder === void 0 ? void 0 : holder.customer_id,
					form_id: holder === null || holder === void 0 || (_holder$metadata = holder.metadata) === null || _holder$metadata === void 0 ? void 0 : _holder$metadata.custom_id
				});
				setEditHolderVisible(true);
			}
		});
		return /* @__PURE__ */ React.createElement(WalletCard, _objectSpread2(_objectSpread2({ key: id }, cardProps), {}, { onViewPinClick: () => onViewPinClick(item) }));
	};
	const carouselProps = {
		className: classNames("pisell-lowcode__walletList"),
		arrows: false,
		infinite: false,
		slidesToShow: 1,
		slidesToScroll: 1,
		centerMode: false,
		autoplay: false,
		dots: false,
		draggable: true,
		swipe: true,
		accessibility: true,
		pauseOnHover: true,
		pauseOnFocus: true,
		speed: 500,
		useCSS: true,
		useTransform: true,
		variableWidth: false,
		adaptiveHeight: true,
		initialSlide: 0,
		waitForAnimate: false,
		afterChange: handleAfterChange,
		currentSlide: currentIndex,
		appendDots: () => /* @__PURE__ */ React.createElement("div", { style: { display: "none" } }),
		responsive: [{
			breakpoint: 768,
			settings: {
				slidesToShow: 1,
				slidesToScroll: 1,
				centerMode: false,
				infinite: false,
				swipe: true,
				draggable: true,
				accessibility: true,
				arrows: false
			}
		}]
	};
	useCallback((balance) => {
		return /* @__PURE__ */ React.createElement("div", {
			className: "pisell-balance-card",
			key: balance.id
		}, /* @__PURE__ */ React.createElement("div", { className: "balance-card-header" }, /* @__PURE__ */ React.createElement("div", { className: "balance-card-title" }, balance.name), /* @__PURE__ */ React.createElement("div", { className: "balance-card-value" }, balance.value)), /* @__PURE__ */ React.createElement("div", { className: "balance-card-content" }, balance.items && balance.items.map((item) => /* @__PURE__ */ React.createElement("div", {
			className: "balance-item",
			key: item.key
		}, /* @__PURE__ */ React.createElement("div", { className: "balance-item-label" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "balance-item-value" }, item.value)))));
	}, []);
	/**
	* @title: 是否显示引导页
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-06-09 13:16
	*/
	const isShowGuide = useMemo(() => {
		var _globalState$walletGu;
		if ((globalState === null || globalState === void 0 || (_globalState$walletGu = globalState.walletGuideConfig) === null || _globalState$walletGu === void 0 ? void 0 : _globalState$walletGu.show) === 0) return false;
		return (walletShopList === null || walletShopList === void 0 ? void 0 : walletShopList.length) > 0 && !(list === null || list === void 0 ? void 0 : list.length);
	}, [
		walletShopList,
		list,
		globalState === null || globalState === void 0 ? void 0 : globalState.walletGuideConfig
	]);
	const renderContent = () => {
		if (list.length === 0 && !isShowGuide) return null;
		return /* @__PURE__ */ React.createElement("div", { className: "pisell-wallet-list-container" }, /* @__PURE__ */ React.createElement("div", { className: "wallet-content" }, isShowGuide ? /* @__PURE__ */ React.createElement(WalletCard, _objectSpread2(_objectSpread2({
			key: getUniqueId(),
			isGuide: true
		}, globalState), {}, { walletGuideConfig: (globalState === null || globalState === void 0 ? void 0 : globalState.walletGuideConfig) || defaultWalletGuideConfig() })) : /* @__PURE__ */ React.createElement(Carousel, _objectSpread2({ ref: carouselRef }, carouselProps), list.map((item) => renderWalletCard(item)))), list && list.length > 1 && isUserLoggedIn && /* @__PURE__ */ React.createElement("div", { className: "wallet-navigation" }, /* @__PURE__ */ React.createElement("div", {
			className: `wallet-nav-button wallet-prev ${currentIndex === 0 ? "disabled" : ""}`,
			onClick: handlePrevClick,
			role: "button"
		}, /* @__PURE__ */ React.createElement(LeftOutlined, { style: {
			fontSize: "24px",
			color: currentIndex === 0 ? "#D0D5DD" : "#101828"
		} })), list && list.length <= 5 ? /* @__PURE__ */ React.createElement("div", { className: "wallet-dots-container" }, Array.from({ length: list.length }).map((_, index) => /* @__PURE__ */ React.createElement("div", {
			key: index,
			className: `wallet-dot ${index === currentIndex ? "active" : ""}`,
			onClick: (e) => {
				e.stopPropagation();
				if (carouselRef.current) carouselRef.current.slickGoTo(index);
			}
		}))) : /* @__PURE__ */ React.createElement("div", { className: "wallet-counter" }, currentIndex + 1, "/", list.length), /* @__PURE__ */ React.createElement("div", {
			className: `wallet-nav-button wallet-next ${currentIndex === list.length - 1 ? "disabled" : ""}`,
			onClick: handleNextClick,
			role: "button"
		}, /* @__PURE__ */ React.createElement(RightOutlined, { style: {
			fontSize: "24px",
			color: currentIndex === list.length - 1 ? "#D0D5DD" : "#101828"
		} }))), /* @__PURE__ */ React.createElement(pinModal_default, { ref: pinModalRef }));
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "wallet-list-wrapper" }, renderContent()), editHolderVisible && /* @__PURE__ */ React.createElement(TempHolderSelector, {
		visible: true,
		value: editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.holder_id,
		formId: editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.form_id,
		customerId: editHolderData === null || editHolderData === void 0 ? void 0 : editHolderData.customer_id,
		onConfirm: onBindHolder,
		onCancel: () => {
			setEditHolderVisible(false);
			setEditHolderData(null);
		},
		confirmLoading: updateHolderLoading
	}));
});
//#endregion
export { WalletList as default };
