<template>
	<view class="container">
		<view class="wallet-card">
			<view class="balance-section">
				<view class="balance-label">账户余额(元)</view>
				<view class="balance-amount">{{ formatMoney(walletDetail.balance) }}</view>
			</view>
			<view class="wallet-footer">
				<view class="footer-item">
					<view class="footer-label">冻结金额</view>
					<view class="footer-value">{{ formatMoney(walletDetail.frozen_balance) }}</view>
				</view>
				<view class="footer-divider"></view>
				<view class="footer-item">
					<view class="footer-label">更新时间</view>
					<view class="footer-value">{{ walletDetail.updated_at }}</view>
				</view>
			</view>
		</view>

		<view class="tab-section">
			<view class="tab-header">
				<view class="tab-indicator" :style="{ left: currentTab === 0 ? '8rpx' : '50%' }"></view>
				<view class="tab-item" :class="{ active: currentTab === 0 }" @tap="onTabTap(0)">
					<text>充值记录</text>
				</view>
				<view class="tab-item" :class="{ active: currentTab === 1 }" @tap="onTabTap(1)">
					<text>钱包流水</text>
				</view>
			</view>

			<swiper class="tab-swiper" :current="currentTab" @change="onSwiperChange" :circular="false" :acceleration="true">
				<swiper-item class="swiper-item-content">
					<scroll-view scroll-y class="list-content">
						<view v-if="rechargeList.length === 0 && !rechargeLoading" class="empty-state">
							<view class="empty-icon">📋</view>
							<view class="empty-title">暂无充值记录</view>
						</view>

						<view v-else>
							<view class="card record-card" v-for="(item, index) in rechargeList" :key="index">
								<view class="record-header flex-row-sb">
									<view class="record-no">{{ item.recharge_no }}</view>
									<view class="tag-apple" :class="getRechargeStatusClass(item.status)">{{ item.status_name }}</view>
								</view>
								<view class="record-info">
									<view class="info-row flex-row-sb">
										<view class="info-label">充值金额</view>
										<view class="info-value text-danger">+¥{{ formatMoney(item.amount) }}</view>
									</view>
									<view class="info-row flex-row-sb">
										<view class="info-label">支付方式</view>
										<view class="info-value">{{ item.payment_method || '-' }}</view>
									</view>
									<view class="info-row flex-row-sb">
										<view class="info-label">自动购包</view>
										<view class="info-value">{{ item.auto_purchase_status === '1' ? '已开启' : '未开启' }}</view>
									</view>
									<view class="info-row flex-row-sb">
										<view class="info-label">创建时间</view>
										<view class="info-value">{{ item.created_at }}</view>
									</view>
								</view>
							</view>

							<view class="load-more" v-if="rechargeList.length > 0">
								<text v-if="rechargeLoading">加载中...</text>
								<text v-else-if="rechargeNoMore">— 没有更多了 —</text>
								<text v-else @tap="loadMoreRecharge">点击加载更多</text>
							</view>
						</view>
					</scroll-view>
				</swiper-item>

				<swiper-item class="swiper-item-content">
					<scroll-view scroll-y class="list-content">
						<view v-if="transactionList.length === 0 && !transactionLoading" class="empty-state">
							<view class="empty-icon">💰</view>
							<view class="empty-title">暂无钱包流水</view>
						</view>

						<view v-else>
							<view class="card record-card" v-for="(item, index) in transactionList" :key="index">
								<view class="record-header flex-row-sb">
									<view class="record-type">{{ item.type_name }}</view>
									<view class="record-amount" :class="item.amount >= 0 ? 'text-success' : 'text-danger'">
										{{ item.amount >= 0 ? '+' : '' }}{{ formatMoney(item.amount) }}
									</view>
								</view>
								<view class="record-info">
									<view class="info-row flex-row-sb">
										<view class="info-label">流水ID</view>
										<view class="info-value text-ellipsis">{{ item.transaction_id }}</view>
									</view>
									<view class="info-row flex-row-sb">
										<view class="info-label">变动后余额</view>
										<view class="info-value">¥{{ formatMoney(item.balance_after) }}</view>
									</view>
									<view class="info-row flex-row-sb" v-if="item.remark">
										<view class="info-label">备注</view>
										<view class="info-value">{{ item.remark }}</view>
									</view>
									<view class="info-row flex-row-sb">
										<view class="info-label">创建时间</view>
										<view class="info-value">{{ item.created_at }}</view>
									</view>
								</view>
							</view>

							<view class="load-more" v-if="transactionList.length > 0">
								<text v-if="transactionLoading">加载中...</text>
								<text v-else-if="transactionNoMore">— 没有更多了 —</text>
								<text v-else @tap="loadMoreTransaction">点击加载更多</text>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue';
	import { walletApi } from '@/api/index.js';
	import { useUserStore } from '@/store/index.js';

	const userStore = useUserStore();

	let currentTab = ref(0);

	const onTabTap = (index) => {
		currentTab.value = index;
	};

	const onSwiperChange = (e) => {
		currentTab.value = e.detail.current;
	};

	const formatMoney = (amount) => {
		if (!amount && amount !== 0) return '0.00';
		return (amount / 100).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	};

	let walletDetail = reactive({
		balance: 0,
		frozen_balance: 0,
		updated_at: ''
	});

	let rechargeList = reactive([]);
	let rechargeLoading = ref(false);
	let rechargeNoMore = ref(false);
	let rechargePage = ref(1);
	const rechargePageSize = 5;

	let transactionList = reactive([]);
	let transactionLoading = ref(false);
	let transactionNoMore = ref(false);
	let transactionPage = ref(1);
	const transactionPageSize = 5;

	const getRechargeStatusClass = (status) => {
		const classMap = {
			'0': 'tag-warning',
			'1': 'tag-success',
			'2': 'tag-danger'
		};
		return classMap[status] || '';
	};

	const loadWalletDetail = async () => {
		try {
			const data = await walletApi.getDetail(userStore.state.identifier);
			walletDetail.balance = data.balance || 0;
			walletDetail.frozen_balance = data.frozen_balance || 0;
			walletDetail.updated_at = data.updated_at || '';
		} catch (e) {
			console.error('加载钱包详情失败', e);
		}
	};

	const loadRechargeList = async (append = false) => {
		if (rechargeLoading.value || rechargeNoMore.value) return;
		rechargeLoading.value = true;

		try {
			const data = await walletApi.getRecharges(
				userStore.state.identifier,
				rechargePage.value,
				rechargePageSize
			);

			const newData = (data.items || []).map(item => ({
				...item,
				status_name: item.status === 1 ? '已支付' : item.status === 0 ? '待支付' : '已关闭'
			}));

			if (append) {
				rechargeList.push(...newData);
			} else {
				rechargeList.splice(0, rechargeList.length, ...newData);
			}

			if (newData.length < rechargePageSize) {
				rechargeNoMore.value = true;
			} else {
				rechargePage.value++;
			}
		} catch (e) {
			console.error('加载充值记录失败', e);
		}
		rechargeLoading.value = false;
	};

	const loadTransactionList = async (append = false) => {
		if (transactionLoading.value || transactionNoMore.value) return;
		transactionLoading.value = true;

		try {
			const data = await walletApi.getTransactions(
				userStore.state.identifier,
				transactionPage.value,
				transactionPageSize
			);

			const newData = (data.items || []).map(item => ({
				...item,
				type_name: item.type === 'recharge' ? '充值' : item.type === 'purchase' ? '消费' : '其他'
			}));

			if (append) {
				transactionList.push(...newData);
			} else {
				transactionList.splice(0, transactionList.length, ...newData);
			}

			if (newData.length < transactionPageSize) {
				transactionNoMore.value = true;
			} else {
				transactionPage.value++;
			}
		} catch (e) {
			console.error('加载钱包流水失败', e);
		}
		transactionLoading.value = false;
	};

	const loadMoreRecharge = () => {
		if (!rechargeNoMore.value) {
			loadRechargeList(true);
		}
	};

	const loadMoreTransaction = () => {
		if (!transactionNoMore.value) {
			loadTransactionList(true);
		}
	};

	onMounted(() => {
		loadWalletDetail();
		loadRechargeList();
		loadTransactionList();
	});
</script>

<style lang="scss" scoped>
	.container {
		height: 100vh;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		padding: 20rpx;
		box-sizing: border-box;
	}

	.wallet-card {
		background: linear-gradient(135deg, #0A84FF 0%, #5AC8FA 50%, #64D2FF 100%);
		border-radius: 24rpx;
		padding: 36rpx;
		color: #fff;
		box-shadow: 0 8rpx 32rpx rgba(10, 132, 255, 0.3);

		.balance-section {
			margin-bottom: 28rpx;
			.balance-label { font-size: 24rpx; opacity: 0.75; margin-bottom: 8rpx; }
			.balance-amount { font-size: 72rpx; font-weight: 700; letter-spacing: -2rpx; }
		}

		.wallet-footer {
			display: flex;
			align-items: center;
			padding-top: 24rpx;
			border-top: 1rpx solid rgba(255, 255, 255, 0.2);
			.footer-divider { width: 1rpx; height: 40rpx; background: rgba(255, 255, 255, 0.3); margin: 0 32rpx; }
			.footer-item {
				flex: 1;
				.footer-label { font-size: 22rpx; opacity: 0.7; margin-bottom: 6rpx; }
				.footer-value { font-size: 26rpx; font-weight: 600; }
			}
		}
	}

	.tab-section {
		margin-top: 32rpx;
		flex: 1;
		min-height: 0;
		display: flex;
		flex-direction: column;
		.tab-header {
			flex-shrink: 0;
			display: flex;
			position: relative;
			background: #fff;
			border-radius: 16rpx;
			padding: 8rpx;
			.tab-indicator {
				position: absolute;
				top: 8rpx;
				width: calc(50% - 16rpx);
				height: calc(100% - 16rpx);
				background: var(--primary);
				border-radius: 12rpx;
				transition: left 0.3s ease;
				z-index: 0;
			}
			.tab-item {
				flex: 1;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx 0;
				font-size: 28rpx;
				font-weight: 500;
				color: var(--text-tertiary);
				position: relative;
				z-index: 1;
				transition: color 0.3s;
				&.active {
					color: #fff;
					font-weight: 600;
				}
			}
		}
	}

	.tab-swiper {
		flex: 1;
		margin-top: 20rpx;
		min-height: 0;
	}

	.swiper-item-content {
		height: 100%;
	}

	.list-content {
		height: 100%;
		padding-top: 16rpx;
		box-sizing: border-box;
	}

	.record-card {
		margin-bottom: 24rpx;
		.record-header {
			margin-bottom: 20rpx;
			.record-no { font-size: 28rpx; font-weight: 600; color: var(--text-primary); }
			.record-type { font-size: 28rpx; font-weight: 600; color: var(--text-primary); }
			.record-amount { font-size: 32rpx; font-weight: 700; }
		}
		.record-info {
			.info-row {
				padding: 10rpx 0;
				.info-label { font-size: 24rpx; color: var(--text-tertiary); }
				.info-value { font-size: 24rpx; color: var(--text-primary); max-width: 380rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
			}
		}
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 40rpx;
		.empty-icon { font-size: 100rpx; margin-bottom: 24rpx; opacity: 0.5; }
		.empty-title { font-size: 28rpx; font-weight: 600; color: var(--text-secondary); }
	}

	.load-more {
		text-align: center;
		padding: 32rpx;
		color: var(--text-tertiary);
		font-size: 24rpx;
	}
</style>