<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 v-if="hasFamily" class="data-type-switch">
				<view
					class="switch-item"
					:class="{active: dataType === 'family'}"
					@tap="switchDataType('family')"
				>
					<uni-icons type="home" size="16" :color="dataType === 'family' ? '#fff' : '#999'"></uni-icons>
					<text>家庭</text>
				</view>
				<view
					class="switch-item"
					:class="{active: dataType === 'personal'}"
					@tap="switchDataType('personal')"
				>
					<uni-icons type="person" size="16" :color="dataType === 'personal' ? '#fff' : '#999'"></uni-icons>
					<text>个人</text>
				</view>
			</view>

			<!-- 月份选择 -->
			<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 || 0) + '%'}"
									:title="'收入: ' + item.income"
								></view>
								<view
									class="bar expense-bar"
									:style="{height: (item.expenseHeight || 0) + '%'}"
									:title="'支出: ' + item.expense"
								></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>
import tool from '@/utils/tool'

export default {
	data() {
		return {
			loading: false,
			currentMonth: this.getCurrentMonth(),
			dataType: 'family', // family 或 personal
			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' }
			}
		}
	},
	computed: {
		hasFamily() {
			return this.$store.getters.hasFamily
		}
	},
	onLoad() {
		this.initDataType()
		this.loadStatistics()
	},
	onPullDownRefresh() {
		this.loadStatistics().then(() => {
			uni.stopPullDownRefresh()
		})
	},
	methods: {
		handleTabChange(path) {
			console.log('Tab changed to:', path)
		},
		initDataType() {
			// 如果用户加入了家庭，默认显示家庭数据
			this.dataType = this.hasFamily ? 'family' : 'personal'
		},
		switchDataType(type) {
			this.dataType = type
			this.loadStatistics()
		},
		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('-')
				console.log('加载统计数据 - 年:', year, '月:', month)

				const baseParams = {
					year: parseInt(year),
					month: parseInt(month),
					data_type: this.dataType // 使用data_type参数：personal 或 family
				}

				// 获取统计概览
				const overviewRes = await this.$api.statistics.overview.get(baseParams)
				console.log('概览接口返回:', overviewRes)
				if (overviewRes && overviewRes.code === 1) {
					this.overview = overviewRes.data || { income: 0, expense: 0, balance: 0 }
					console.log('概览数据:', this.overview)
				} else {
					console.error('概览接口返回错误:', overviewRes?.message)
				}

				// 获取分类统计
				const categoryRes = await this.$api.statistics.category.get(baseParams)
				console.log('分类接口返回:', categoryRes)
				if (categoryRes && categoryRes.code === 1) {
					this.processCategoryData(categoryRes.data || [])
					console.log('分类数据:', this.categoryList)
				} else {
					console.error('分类接口返回错误:', categoryRes?.message)
				}

				// 获取收支趋势
				const trendRes = await this.$api.statistics.trend.get(baseParams)
				console.log('趋势接口返回:', trendRes)
				if (trendRes && trendRes.code === 1) {
					this.processTrendData(trendRes.data || [])
					console.log('趋势数据:', this.trendList)
				} else {
					console.error('趋势接口返回错误:', trendRes?.message)
				}
			} catch (error) {
				console.error('加载统计数据失败', error)
				uni.showToast({
					title: error?.message || '加载失败，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		processCategoryData(data) {
			console.log('处理分类数据:', 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)
			console.log('处理后的分类列表:', this.categoryList)
		},
		processTrendData(data) {
			console.log('处理趋势数据:', data)
			if (!data || data.length === 0) {
				this.trendList = []
				return
			}

			// 找出最大值用于计算高度百分比
			let maxIncome = 0
			let maxExpense = 0

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

			console.log('最大收入:', maxIncome, '最大支出:', maxExpense)

			this.trendList = data.map(item => {
				const dateLabel = this.formatDate(item.date, 'MM/dd')

				// 确保高度至少为1，避免柱状图完全不可见
				let incomeHeight = 0
				let expenseHeight = 0

				if (maxIncome > 0) {
					incomeHeight = (item.income / maxIncome) * 100
					if (item.income > 0 && incomeHeight < 1) {
						incomeHeight = 1
					}
				}

				if (maxExpense > 0) {
					expenseHeight = (item.expense / maxExpense) * 100
					if (item.expense > 0 && expenseHeight < 1) {
						expenseHeight = 1
					}
				}

				return {
					date: item.date,
					dateLabel,
					income: item.income,
					expense: item.expense,
					incomeHeight,
					expenseHeight
				}
			})
			console.log('处理后的趋势列表:', this.trendList)
		},
		formatDate(date, fmt) {
			return tool.dateFormat(date, fmt)
		}
	}
}
</script>

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

.data-type-switch {
	display: flex;
	background: #f5f5f5;
	border-radius: 50rpx;
	padding: 8rpx;
	margin-bottom: 30rpx;

	.switch-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16rpx 0;
		border-radius: 50rpx;
		transition: all 0.3s;

		uni-icons {
			margin-right: 8rpx;
		}

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

		&.active {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

			text {
				color: #fff;
				font-weight: bold;
			}
		}
	}
}

.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-around;
			align-items: flex-end;
			height: 300rpx;
			padding: 20rpx 0;
			margin-bottom: 20rpx;
			border-bottom: 2rpx solid #f0f0f0;
			position: relative;

			.chart-bar {
				flex: 0 0 auto;
				width: 48rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				height: 100%;
				justify-content: flex-end;

				.bar-wrapper {
					display: flex;
					align-items: flex-end;
					gap: 6rpx;
					margin-bottom: 12rpx;
					width: 100%;
					height: 240rpx;
					position: relative;

					.bar {
						flex: 0 0 auto;
						width: 20rpx;
						min-height: 2rpx;
						border-radius: 4rpx 4rpx 0 0;
						transition: height 0.3s ease;
						position: absolute;
						bottom: 0;

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

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

				.bar-label {
					font-size: 20rpx;
					color: #999;
					text-align: center;
					white-space: nowrap;
					line-height: 1.2;
				}
			}
		}

		.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>
