<template>
	<un-pages
		:show-nav-bar="true"
		nav-bar-title="统计分析"
		:show-back="true"
		:show-tab-bar="true"
		@tab-change="handleTabChange"
	>
		<view class="page-content">
			<!-- 月份选择 -->
			<view class="month-selector">
				<picker mode="date" fields="month" :value="currentMonth" @change="onMonthChange">
					<view class="month-picker">
						<uni-icons type="left" size="20" color="#666"></uni-icons>
						<text class="month-text">{{ currentMonth }}</text>
						<uni-icons type="right" size="20" color="#666"></uni-icons>
					</view>
				</picker>
			</view>

			<!-- 概览卡片 -->
			<view class="overview-section">
				<view class="overview-card income">
					<text class="card-label">本月收入</text>
					<text class="card-amount">¥{{ overview.income.toFixed(2) }}</text>
				</view>
				<view class="overview-card expense">
					<text class="card-label">本月支出</text>
					<text class="card-amount">¥{{ overview.expense.toFixed(2) }}</text>
				</view>
				<view class="overview-card balance">
					<text class="card-label">结余</text>
					<text class="card-amount">¥{{ overview.balance.toFixed(2) }}</text>
				</view>
			</view>

			<!-- 分类统计 -->
			<view class="category-section">
				<view class="section-header">
					<text class="section-title">支出分类</text>
					<text class="section-total">共 ¥{{ categoryTotal.toFixed(2) }}</text>
				</view>

				<view v-if="loading" class="loading-state">
					<uni-load-more status="loading"></uni-load-more>
				</view>

				<view v-else-if="categoryList.length === 0" class="empty-state">
					<text class="empty-text">暂无数据</text>
				</view>

				<view v-else class="category-list">
					<view class="category-item" v-for="(item, index) in categoryList" :key="index">
						<view class="category-info">
							<view class="category-icon" :style="{background: item.color}">
								<text>{{ item.icon }}</text>
							</view>
							<view class="category-details">
								<text class="category-name">{{ item.name }}</text>
								<view class="progress-bar">
									<view class="progress" :style="{width: item.percent + '%', background: item.color}"></view>
								</view>
							</view>
						</view>
						<view class="category-amount">
							<text class="amount">¥{{ item.amount.toFixed(2) }}</text>
							<text class="percent">{{ item.percent }}%</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 收支趋势 -->
			<view class="trend-section">
				<view class="section-header">
					<text class="section-title">收支趋势</text>
					<text class="period-text">最近7天</text>
				</view>

				<view v-if="loading" class="loading-state">
					<uni-load-more status="loading"></uni-load-more>
				</view>

				<view v-else-if="trendList.length === 0" class="empty-state">
					<text class="empty-text">暂无数据</text>
				</view>

				<view v-else class="trend-chart">
					<view class="chart-container">
						<view
							class="chart-bar"
							v-for="(item, index) in trendList"
							:key="index"
						>
							<view class="bar-wrapper">
								<view
									class="bar income-bar"
									:style="{height: item.incomeHeight + '%'}"
								></view>
								<view
									class="bar expense-bar"
									:style="{height: item.expenseHeight + '%'}"
								></view>
							</view>
							<text class="bar-label">{{ item.dateLabel }}</text>
						</view>
					</view>
					<view class="chart-legend">
						<view class="legend-item">
							<view class="legend-color income-legend"></view>
							<text class="legend-text">收入</text>
						</view>
						<view class="legend-item">
							<view class="legend-color expense-legend"></view>
							<text class="legend-text">支出</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</un-pages>
</template>

<script>
export default {
	data() {
		return {
			loading: false,
			currentMonth: this.getCurrentMonth(),
			overview: {
				income: 0,
				expense: 0,
				balance: 0
			},
			categoryList: [],
			categoryTotal: 0,
			trendList: [],
			categoryMap: {
				1: { name: '餐饮', icon: '🍜', color: '#FF6B6B' },
				2: { name: '交通', icon: '🚗', color: '#4ECDC4' },
				3: { name: '购物', icon: '🛒', color: '#45B7D1' },
				4: { name: '娱乐', icon: '🎮', color: '#96CEB4' },
				5: { name: '医疗', icon: '💊', color: '#FFEAA7' },
				6: { name: '教育', icon: '📚', color: '#DDA0DD' },
				7: { name: '居住', icon: '🏠', color: '#98D8C8' },
				8: { name: '其他', icon: '📦', color: '#BDC3C7' }
			}
		}
	},
	onLoad() {
		this.loadStatistics()
	},
	onPullDownRefresh() {
		this.loadStatistics().then(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		handleTabChange(path) {
			console.log('Tab changed to:', path)
		},
		getCurrentMonth() {
			const today = new Date()
			const year = today.getFullYear()
			const month = String(today.getMonth() + 1).padStart(2, '0')
			return `${year}-${month}`
		},
		onMonthChange(e) {
			this.currentMonth = e.detail.value
			this.loadStatistics()
		},
		async loadStatistics() {
			this.loading = true
			try {
				const [year, month] = this.currentMonth.split('-')

				// 获取统计概览
				const overviewRes = await this.$api.statistics.overview.get({
					year: parseInt(year),
					month: parseInt(month)
				})
				if (overviewRes.code === 200) {
					this.overview = overviewRes.data || { income: 0, expense: 0, balance: 0 }
				}

				// 获取分类统计
				const categoryRes = await this.$api.statistics.category.get({
					year: parseInt(year),
					month: parseInt(month)
				})
				if (categoryRes.code === 200) {
					this.processCategoryData(categoryRes.data || [])
				}

				// 获取收支趋势
				const trendRes = await this.$api.statistics.trend.get({
					year: parseInt(year),
					month: parseInt(month)
				})
				if (trendRes.code === 200) {
					this.processTrendData(trendRes.data || [])
				}
			} catch (error) {
				console.error('加载统计数据失败', error)
				uni.showToast({
					title: '加载失败，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		processCategoryData(data) {
			let total = 0
			const list = data.map(item => {
				total += item.amount
				return item
			})

			this.categoryTotal = total
			this.categoryList = list.map(item => {
				const categoryInfo = this.categoryMap[item.category_id] || { name: '未知', icon: '📦', color: '#BDC3C7' }
				return {
					...categoryInfo,
					amount: item.amount,
					percent: total > 0 ? Math.round((item.amount / total) * 100) : 0
				}
			}).sort((a, b) => b.amount - a.amount)
		},
		processTrendData(data) {
			// 找出最大值用于计算高度百分比
			let maxIncome = 0
			let maxExpense = 0

			data.forEach(item => {
				maxIncome = Math.max(maxIncome, item.income)
				maxExpense = Math.max(maxExpense, item.expense)
			})

			this.trendList = data.map(item => {
				const date = new Date(item.date)
				const dateLabel = `${date.getMonth() + 1}/${date.getDate()}`

				return {
					date: item.date,
					dateLabel,
					income: item.income,
					expense: item.expense,
					incomeHeight: maxIncome > 0 ? (item.income / maxIncome) * 100 : 0,
					expenseHeight: maxExpense > 0 ? (item.expense / maxExpense) * 100 : 0
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.page-content {
	padding: 30rpx;
	padding-bottom: 150rpx;
}

.month-selector {
	display: flex;
	justify-content: center;
	margin-bottom: 30rpx;

	.month-picker {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 50rpx;
		padding: 16rpx 40rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

		.month-text {
			font-size: 28rpx;
			color: #333;
			font-weight: bold;
			margin: 0 20rpx;
		}
	}
}

.overview-section {
	display: flex;
	gap: 20rpx;
	margin-bottom: 30rpx;

	.overview-card {
		flex: 1;
		background: #fff;
		border-radius: 20rpx;
		padding: 30rpx 20rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

		.card-label {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 12rpx;
		}

		.card-amount {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}

		&.income .card-amount {
			color: #2ECC71;
		}

		&.expense .card-amount {
			color: #FF6B6B;
		}

		&.balance .card-amount {
			color: #667eea;
		}
	}
}

.category-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;

		.section-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}

		.section-total {
			font-size: 24rpx;
			color: #999;
		}
	}

	.loading-state,
	.empty-state {
		padding: 60rpx 0;
		text-align: center;

		.empty-text {
			font-size: 26rpx;
			color: #999;
		}
	}

	.category-list {
		.category-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx 0;
			border-bottom: 2rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			.category-info {
				flex: 1;
				display: flex;
				align-items: center;

				.category-icon {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 20rpx;

					text {
						font-size: 28rpx;
					}
				}

				.category-details {
					flex: 1;

					.category-name {
						font-size: 26rpx;
						color: #333;
						margin-bottom: 12rpx;
						display: block;
					}

					.progress-bar {
						width: 100%;
						height: 8rpx;
						background: #f5f5f5;
						border-radius: 4rpx;
						overflow: hidden;

						.progress {
							height: 100%;
							transition: width 0.3s;
						}
					}
				}
			}

			.category-amount {
				text-align: right;
				margin-left: 20rpx;

				.amount {
					display: block;
					font-size: 26rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 4rpx;
				}

				.percent {
					display: block;
					font-size: 22rpx;
					color: #999;
				}
			}
		}
	}
}

.trend-section {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;

		.section-title {
			font-size: 28rpx;
			font-weight: bold;
			color: #333;
		}

		.period-text {
			font-size: 24rpx;
			color: #999;
		}
	}

	.loading-state,
	.empty-state {
		padding: 60rpx 0;
		text-align: center;

		.empty-text {
			font-size: 26rpx;
			color: #999;
		}
	}

	.trend-chart {
		.chart-container {
			display: flex;
			justify-content: space-between;
			align-items: flex-end;
			height: 300rpx;
			padding: 20rpx 0;
			margin-bottom: 20rpx;

			.chart-bar {
				flex: 1;
				display: flex;
				flex-direction: column;
				align-items: center;

				.bar-wrapper {
					display: flex;
					align-items: flex-end;
					gap: 4rpx;
					margin-bottom: 12rpx;

					.bar {
						width: 24rpx;
						min-height: 4rpx;
						border-radius: 4rpx;
						transition: height 0.3s;

						&.income-bar {
							background: #2ECC71;
						}

						&.expense-bar {
							background: #FF6B6B;
						}
					}
				}

				.bar-label {
					font-size: 22rpx;
					color: #999;
				}
			}
		}

		.chart-legend {
			display: flex;
			justify-content: center;
			gap: 40rpx;

			.legend-item {
				display: flex;
				align-items: center;

				.legend-color {
					width: 16rpx;
					height: 16rpx;
					border-radius: 4rpx;
					margin-right: 8rpx;

					&.income-legend {
						background: #2ECC71;
					}

					&.expense-legend {
						background: #FF6B6B;
					}
				}

				.legend-text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
	}
}
</style>
