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 IntersectionObserverProvider, { IntersectionTrigger } from "../../../productSelect/components/IntersectionObserver.js";
import { getOffsetTopRelativeToScrollContainer } from "../../../productSelect/utils.js";
import CategoryTabs from "../../../productSelect/CategoryTabs/index.js";
import { getDetailApi } from "../../serve.js";
import locales_default from "../../locales.js";
import UsageRules from "../usageRule/index.js";
import TimelineSection from "../timelineSection/index.js";
import Recharge from "../recharge/index.js";
import FooterButtons from "../footerButton/index.js";
import { formatScheduleText } from "../../../../components/wallet/utils.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button, Empty, Typography } from "antd";
import { locales } from "@pisell/utils";
import { PisellStatisticList, PisellToast, usePisellConfig } from "@pisell/materials";
import classNames from "classnames";
import { useRequest } from "ahooks";
import "./index.less";
//#region src/plus/walletPassGallery/components/passDetail/index.tsx
const { Text } = Typography;
const PassDetail = (props) => {
	var _context$appHelper, _context$appHelper2, _store$getState, _context$engine, _context$appHelper3, _dataSource$machineco, _getDetail$data, _getDetail$data2, _dataSource$machineco2;
	const { symbol = "$" } = usePisellConfig();
	const { dataSource, platform = "pc", showTimeLine = true, onListRefresh } = props;
	const [activeKey, setActiveKey] = useState("detail");
	const [rechargeOpen, setRechargeOpen] = useState(false);
	const containerRef = useRef(null);
	const isIndicatorVisibleRef = useRef(false);
	const context = useEngineContext();
	const { store, isTerminal, interaction, isApp } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const { apiPrefix } = ((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.constants) || { apiPrefix: "/h5" };
	const timezone = (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 || (_store$getState = _store$getState.symbol) === null || _store$getState === void 0 || (_store$getState = _store$getState.shop) === null || _store$getState === void 0 ? void 0 : _store$getState.timezone) || "Asia/Shanghai";
	const isTerminalEnv = (typeof isTerminal === "function" ? isTerminal() : !!isTerminal) || (isApp === null || isApp === void 0 ? void 0 : isApp());
	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");
	if ((_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 || (_context$appHelper3 = _context$appHelper3.utils) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.request) {
		var _context$appHelper4;
		request.setRequest((_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 || (_context$appHelper4 = _context$appHelper4.utils) === null || _context$appHelper4 === void 0 ? void 0 : _context$appHelper4.request);
	}
	const { id = "", code = "", tag = "", product_title = "", encoded = "", balance, expire_date = "", product = {}, custom_schedule_snapshot, customer_id } = dataSource || {};
	const { description = "", extension_data = [], customer_order_behavior_count = 0 } = product || {};
	const _getDetail = useRequest(() => getDetailApi({
		id,
		apiPrefix,
		order_behavior_count_customer_id: customer_id
	}), {
		ready: !!id,
		refreshDeps: [id, customer_id]
	});
	useEffect(() => {
		var _interaction$utils, _interaction$utils$mo;
		interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$mo = _interaction$utils.mountFunction) === null || _interaction$utils$mo === void 0 || _interaction$utils$mo.call(_interaction$utils, "customer", "recharge", function() {
			var _ref = _asyncToGenerator(function* (strVal) {
				return onListRefresh === null || onListRefresh === void 0 ? void 0 : onListRefresh();
			});
			return function(_x) {
				return _ref.apply(this, arguments);
			};
		}());
	}, [id]);
	const scheduleList = useMemo(() => {
		return (custom_schedule_snapshot === null || custom_schedule_snapshot === void 0 ? void 0 : custom_schedule_snapshot.data) || [];
	}, [custom_schedule_snapshot]);
	useEffect(() => {
		if (tag === "product_discount_card") setActiveKey("detail");
		if (containerRef.current) containerRef.current.scrollTop = 0;
	}, [id, tag]);
	const _anchorOptions = useMemo(() => {
		const options = [{
			key: "detail",
			label: locales.getText("wallet-pass-gallery.detail")
		}];
		if (tag !== "product_discount_card") options.push({
			key: "activityLog",
			label: locales.getText("wallet-pass-gallery.activelog")
		});
		return options;
	}, [dataSource === null || dataSource === void 0 ? void 0 : dataSource.tag]);
	const debounceIndicator = useCallback((delay) => {
		isIndicatorVisibleRef.current = true;
		const timeoutId = setTimeout(() => {
			isIndicatorVisibleRef.current = false;
		}, delay);
		return () => clearTimeout(timeoutId);
	}, []);
	const descs = useMemo(() => {
		var _context$engine2;
		const detail = formatScheduleText(scheduleList, context === null || context === void 0 || (_context$engine2 = context.engine) === null || _context$engine2 === void 0 || (_context$engine2 = _context$engine2.props) === null || _context$engine2 === void 0 ? void 0 : _context$engine2.locale);
		let expireText = expire_date ? expire_date : locales.getText("wallet-pass-gallery.expireDate");
		if (scheduleList.length > 0) {
			let validityTexts = "";
			let excludedText = "";
			let includedText = "";
			detail.forEach((item) => {
				if (item.validityTexts.length > 0) validityTexts = `${validityTexts}${item.validityTexts.join("\n")}\n`;
				if (item.excluded_date.length > 0) excludedText = `${excludedText}${item.excluded_date.join("\n")}\n`;
				if (item.included_date.length > 0) includedText = `${includedText}${item.included_date.join("\n")}\n`;
			});
			expireText = /* @__PURE__ */ React.createElement("span", { className: "wallet-detail-expire-text" }, validityTexts, excludedText && /* @__PURE__ */ React.createElement("div", { className: "wallet-detail-expire-text-title" }, locales.getText("page.wallet.notValidDate")), excludedText, includedText && /* @__PURE__ */ React.createElement("div", { className: "wallet-detail-expire-text-title" }, locales.getText("page.wallet.includedDate")), includedText);
		}
		let data = [
			{
				label: locales.getText("wallet-pass-gallery.cardName"),
				value: product_title
			},
			{
				label: locales.getText("wallet-pass-gallery.carNumber"),
				value: encoded,
				isLink: false
			},
			{
				label: locales.getText("wallet-pass-gallery.validDate"),
				value: expireText
			}
		];
		if (tag === "product_discount_card") {
			var _dataSource$metadata;
			const isFixedAmount = ((_dataSource$metadata = dataSource.metadata) === null || _dataSource$metadata === void 0 ? void 0 : _dataSource$metadata.discount_card_type) === "fixed_amount";
			data.splice(2, 0, {
				label: locales.getText("wallet-pass-gallery.discount"),
				value: balance ? isFixedAmount ? `${symbol}${Number(balance)}` : `${Number(balance)}%` : ""
			});
		} else if (tag === "point_card") data.splice(2, 0, {
			label: locales.getText("wallet-pass-gallery.points"),
			value: balance ? `${Number(balance)}` : ""
		});
		else if (tag === "good_pass") data.splice(2, 0, {
			label: locales.getText("wallet-pass-gallery.goodPass"),
			value: balance ? `${Number(balance)}` : ""
		});
		else data.splice(2, 0, {
			label: locales.getText("wallet-pass-gallery.balance"),
			value: balance ? `${symbol}${Number(balance)}` : ""
		});
		return data;
	}, [dataSource]);
	const handleItemIntersectionIn = useCallback((_key) => {
		if (!isIndicatorVisibleRef.current && _key) setActiveKey(_key);
	}, []);
	const handleRechargeClick = useCallback(() => {
		if ((dataSource === null || dataSource === void 0 ? void 0 : dataSource.product_status) && (dataSource === null || dataSource === void 0 ? void 0 : dataSource.product_status) !== "published") {
			PisellToast({ content: locales.getText("wallet-pass-gallery.rechargeToast.productUnavailable") });
			return;
		}
		if (isTerminalEnv) {
			var _interaction$utils2, _interaction$utils2$p;
			const productId = (product === null || product === void 0 ? void 0 : product.id) || (dataSource === null || dataSource === void 0 ? void 0 : dataSource.product_id) || "";
			interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 || _interaction$utils2$p.call(_interaction$utils2, {
				module: "customer",
				key: "recharge",
				data: {
					product_id: String(productId || ""),
					card_id: String(id || ""),
					card_code: String(code || ""),
					customer_id: String(customer_id || "")
				}
			});
			return;
		}
		setRechargeOpen(true);
	}, [
		isTerminalEnv,
		id,
		code,
		customer_id,
		product,
		dataSource
	]);
	if (!dataSource) return /* @__PURE__ */ React.createElement(Empty, null);
	const _switchCategory = (key) => {
		setActiveKey(key);
		debounceIndicator(300);
		const categoryIndex = _anchorOptions.findIndex((item) => item.key === key);
		const _scrollParent = containerRef.current;
		if (!_scrollParent) return;
		const target = document.querySelector(`[data-anchor="${key}"]`);
		if (!target) return;
		const detailWrapper = document.querySelector(`.pisell-wallet-pass-gallery_detail-content`);
		const tabsWrapper = document.querySelector(`.pisell-wallet-pass-gallery-tabs-wrapper`);
		const tabsHeight = (tabsWrapper === null || tabsWrapper === void 0 ? void 0 : tabsWrapper.offsetHeight) || 0;
		if (categoryIndex === 0) {
			if (detailWrapper) _scrollParent.scrollTop = getOffsetTopRelativeToScrollContainer(detailWrapper, _scrollParent);
			return;
		} else _scrollParent.scrollTop = getOffsetTopRelativeToScrollContainer(target, _scrollParent) - tabsHeight;
	};
	const renderTimeLine = () => {
		if (tag === "product_discount_card") return null;
		if (!showTimeLine) return null;
		return /* @__PURE__ */ React.createElement(TimelineSection, {
			code,
			tag,
			timezone,
			apiPrefix,
			isTerminalEnv,
			interaction
		});
	};
	if (!props.dataSource) return null;
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: classNames(`pisell-wallet-pass-gallery_detail`, `pisell-wallet-pass-gallery_detail-${platform}`, { [`pisell-wallet-pass-gallery_detail-with-footer`]: platform === "h5" && tag === "gift_card" }) }, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-wallet-pass-gallery_detail-content",
		ref: containerRef
	}, _anchorOptions.length > 1 && /* @__PURE__ */ React.createElement(CategoryTabs, {
		key: id,
		className: "pisell-wallet-pass-gallery-tabs-wrapper",
		activeKey,
		items: _anchorOptions,
		onChange: _switchCategory,
		loading: false,
		style: { padding: 0 }
	}), /* @__PURE__ */ React.createElement(IntersectionObserverProvider, {
		rootMargin: "-70px 0px -270px 0px",
		priorityMode: "top"
	}, /* @__PURE__ */ React.createElement(IntersectionTrigger, {
		style: { height: "1px" },
		onShow: () => handleItemIntersectionIn("detail")
	}, /* @__PURE__ */ React.createElement("div", { "data-anchor": "detail" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Text, { className: "pisell-wallet-pass-gallery_detail-title" }, locales.getText("wallet-pass-gallery.details")), platform === "pc" && tag === "gift_card" && (dataSource === null || dataSource === void 0 || (_dataSource$machineco = dataSource.machinecode_config) === null || _dataSource$machineco === void 0 ? void 0 : _dataSource$machineco.hide_recharge) === 0 && /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		size: "large",
		onClick: handleRechargeClick
	}, locales.getText("wallet-pass-gallery.recharge")), /* @__PURE__ */ React.createElement(PisellStatisticList, {
		data: descs,
		labelColor: "#667085",
		valueColor: "#101828",
		backgroundColors: ["#fff"],
		isHasBorder: false
	}), description && /* @__PURE__ */ React.createElement("div", { className: "pisell-wallet-pass-gallery_detail-card-content-tip" }, /* @__PURE__ */ React.createElement("div", { dangerouslySetInnerHTML: { __html: description } })), /* @__PURE__ */ React.createElement(UsageRules, { dataSource: _getDetail.data })), /* @__PURE__ */ React.createElement(IntersectionTrigger, {
		style: { height: "1px" },
		onShow: () => handleItemIntersectionIn("activityLog")
	}, /* @__PURE__ */ React.createElement("div", { "data-anchor": "activityLog" })), renderTimeLine()))), platform === "h5" && tag === "gift_card" ? /* @__PURE__ */ React.createElement(FooterButtons, {
		appleWalletUrl: (_getDetail$data = _getDetail.data) === null || _getDetail$data === void 0 ? void 0 : _getDetail$data.apple_wallet_url,
		googleWalletUrl: (_getDetail$data2 = _getDetail.data) === null || _getDetail$data2 === void 0 ? void 0 : _getDetail$data2.google_wallet_url,
		onRechargeClick: (dataSource === null || dataSource === void 0 || (_dataSource$machineco2 = dataSource.machinecode_config) === null || _dataSource$machineco2 === void 0 ? void 0 : _dataSource$machineco2.hide_recharge) === 0 ? handleRechargeClick : void 0,
		platform
	}) : null, /* @__PURE__ */ React.createElement(Recharge, {
		platform,
		detailData: _getDetail.data,
		open: rechargeOpen,
		onClose: () => setRechargeOpen(false)
	}));
};
//#endregion
export { PassDetail as default };
