<template>
	<view class="contentStyle" style="">
		<view class="status-bar"></view>
		<uni-nav-bar title="缴费记录" left-icon="left" @clickLeft="goBack" backgroundColor="transparent" :border="false">
		</uni-nav-bar>

		<!-- 表单区域 -->
		<scroll-view class="page" scroll-y="true">

			<!-- 累计缴费 -->
			<view class="total-box">
				<view class="top-box">
					<view class="total-title">累计缴费</view>
					<view class="total-price">¥{{ totalAmount }}</view>
				</view>

				<view class="chart-box">
					<view v-if="chartData.length === 0" class="empty-state">
						<uni-icons type="info" size="60" color="#ccc"></uni-icons>
						<text class="empty-text">
							{{ '暂无数据'}}
						</text>
					</view>
					<!-- 循环6个月柱状图 -->
					<view class="chart-item" v-for="(item,index) in chartData" :key="index">
						<!-- 柱子顶部金额文字 -->
						<view class="chart-label">{{ item.price }}元</view>
						<!-- 柱状图柱子 -->
						<view class="chart-bar" :style="{ height: barHeight(item.price) }"></view>
						<!-- 底部月份文字 -->
						<view class="chart-month">{{ item.month }}</view>
					</view>
				</view>

			</view>

			<!-- 缴费明细 -->
			<view class="list-wrapper">
				<!-- 按月份分组渲染 -->
				<view v-if="monthGroups.length === 0" class="empty-state">
					<uni-icons type="info" size="60" color="#ccc"></uni-icons>
					<text class="empty-text">
						{{ '暂无数据'}}
					</text>
				</view>
				<view class="month-group" v-for="(item, idx) in monthGroups" :key="idx">
					<view class="month-title">
						{{ item.month }}月 缴费 ¥{{ item.total }}元
					</view>

					<view class="item-list">
						<view class="bill-item" v-for="bill in item.list" :key="bill.id">
							<view class="bill-icon">
								<image class="iconStyle" src="https://wuyeadmin.bugtc.com/images/propertyImgs/water.png"
									v-if="bill.name=='物业费A'"></image>
								<image class="iconStyle" src="https://wuyeadmin.bugtc.com/images/propertyImgs/electric.png"
									v-if="bill.name=='物业费B'"></image>
				
							</view>
							<view class="bill-info">
								<view class="name">{{ bill.name }}</view>
								<view class="account">{{ bill.account }}</view>
							</view>
							<view class="bill-price">-{{ bill.amount }}</view>
						</view>
					</view>
				</view>
			</view>

		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed

	} from 'vue'
	import {
		onShow,
		onReady,
		onReachBottom,
		onLoad,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app'

	import {
		getTopupRecordWithStat
	} from '/pageSubPack/api/apiSub.js'
	// 响应式数据
	const statusBarHeight = ref(20)
	const pageNum = ref(1)
	const pageSize = ref(10)
	const totalAmount = ref('0.00')
	const chartData = ref([])
	const maxPrice = ref(100)
	const barMaxHeight = ref(300)

	const billList = ref([])

	// 图标映射
	const iconMap = {
		'物业费A': 'https://wuyeadmin.bugtc.com/images/propertyImgs/water.png',
		'物业费B': 'https://wuyeadmin.bugtc.com/images/propertyImgs/electric.png',
		'物业费': 'https://wuyeadmin.bugtc.com/images/propertyImgs/property.png',
		'暖气费': 'https://wuyeadmin.bugtc.com/images/propertyImgs/heating.png',
		'燃气费': 'https://wuyeadmin.bugtc.com/images/propertyImgs/gas.png'
	}

	// 获取缴费记录
	const getRecords = async () => {
		try {
			const res = await getTopupRecordWithStat({
				residentUserId: uni.getStorageSync('userId'),
				pageNum: pageNum.value,
				pageSize: pageSize.value
			})
			if (res.code === 200) {
				const records = res.data.records || []
				// 转换记录格式
				billList.value = records.map(item => ({
					id: item.id,
					month: item.rechargeTime && item.rechargeTime.split('-')[1] ? parseInt(item.rechargeTime.split('-')[1], 10) : 1,
					name: item.type == 1 ? '物业费B' : item.type == 2 ? '物业费A' : '',
					account: item.deviceCode || '-',
					amount: Number(item.rechargeAmount) || 0,
					icon: iconMap[item.type == 1 ? '物业费B' : item.type == 2 ? '物业费A' : ''] || 'https://wuyeadmin.bugtc.com/images/propertyImgs/water.png'
				}))
				// 累计缴费金额
				const total = records.reduce((sum, item) => sum + (Number(item.rechargeAmount) || 0), 0)
				totalAmount.value = total.toFixed(2)
				// 更新图表数据（根据 records 计算最近6个月）
				updateChartData()
			}
		} catch (err) {
			console.error('获取缴费记录失败', err)
		}
	}

	// 更新图表数据（根据 records 计算最近6个月）
	const updateChartData = () => {
		// 按月份汇总金额
		const monthTotal = {}
		billList.value.forEach(bill => {
			const monthKey = bill.month
			if (!monthTotal[monthKey]) {
				monthTotal[monthKey] = 0
			}
			monthTotal[monthKey] += bill.amount
		})
		// 取最近6个月（当前月往前）
		const now = new Date()
		const currentMonth = now.getMonth() + 1 // 1-12
		const currentYear = now.getFullYear()
		const months = []
		for (let i = 0; i < 6; i++) {
			let month = currentMonth - i
			let year = currentYear
			if (month <= 0) {
				month += 12
				year -= 1
			}
			months.push({
				month,
				year
			})
		}
		chartData.value = months.map((m, i) => ({
			month: (m.year + '').slice(-2) + '年' + m.month + '月',
			year: m.year,
			sortMonth: m.year * 12 + m.month,
			price: monthTotal[m.month] || 0,
			index: i
		})).sort((a, b) => a.sortMonth - b.sortMonth)
		const prices = chartData.value.map(c => c.price)
		maxPrice.value = Math.max(...prices, 100)
	}

	// 计算属性 —— 月份分组
	const monthGroups = computed(() => {
		let map = {}
		billList.value.forEach(bill => {
			if (!map[bill.month]) {
				map[bill.month] = {
					month: bill.month,
					total: 0,
					list: []
				}
			}
			map[bill.month].list.push(bill)
			map[bill.month].total += bill.amount
		})
		return Object.values(map).sort((a, b) => b.month - a.month)
	})

	// 生命周期
	onShow(() => {})
	onMounted(() => {})
	onLoad(() => {
		getRecords()
	})
	onReady(() => {})

	// 方法
	const barHeight = (price) => {
		const height = (price / maxPrice.value) * barMaxHeight.value
		return `${height}rpx`
	}

	const goBack = () => {
		uni.redirectTo({
			url: '/pageSubPack/payment-list/paymentIndex'
		});
	}
</script>

<style lang="scss">
	page {
		// background: #f2f1f6;
	}
</style>

<style scoped>
	.contentStyle {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: linear-gradient(to left bottom, #e2efff 0%, #f9f9f9 50%);
	}

	.page {
		flex: 1;
		overflow-y: auto;
		padding: 0px 40rpx;
		box-sizing: border-box;
	}

	.total-box {
		margin-bottom: 30rpx;
	}

	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
		color: #ccc;
	}

	.empty-text {
		font-size: 32rpx;
		color: #999;
		margin-top: 20rpx;
		margin-bottom: 10rpx;
	}

	.top-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.total-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.total-price {
		font-size: 48rpx;
		font-weight: bold;
		margin-top: 10rpx;
		margin-bottom: 20rpx;
	}

	.chart-canvas {
		width: calc(100vw - 60rpx);
		height: 30vh;
	}

	.list-wrapper {
		padding: 10rpx 0rpx;
	}

	.month-group {
		border-bottom: 2rpx solid #f2f2f2;
		padding: 30rpx;
		background-color: #fff;
		margin-bottom: 30rpx;
		border-radius: 10rpx;
	}

	.month-title {
		font-size: 32rpx;
		font-weight: 600;
		margin-bottom: 30rpx;
	}

	.bill-item {
		display: flex;
		align-items: center;
		margin-bottom: 30rpx;
		padding-bottom: 30rpx;
		border-bottom: 1px solid #ebebeb;
	}

	.bill-item:last-child {
		border-bottom: none;
		margin-bottom: 0rpx;
		padding-bottom: 0rpx;
	}

	.bill-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #4080FF;
		margin-right: 24rpx;
		font-size: 36rpx;
	}

	.iconStyle {
		width: 100%;
		height: 100%;
	}

	.bill-info {
		flex: 1;
	}

	.name {
		font-size: 28rpx;
		color: #333;
		font-weight: 600;
	}

	.account {
		font-size: 24rpx;
		color: #999;
		margin-top: 8rpx;
	}

	.bill-price {
		font-size: 32rpx;
		color: #333;
	}

	.status-bar {
		width: 100vw;
		height: 46px;
	}
</style>

<style scoped>
	.chart-box {
		width: 100%;
		height: 444rpx;
		display: flex;
		align-items: flex-end;
		justify-content: space-around;
		box-sizing: border-box;
	}

	.chart-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: flex-end;
		width: 120rpx;
		font-size: 24rpx;
	}

	.chart-label {
		font-size: 32rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.chart-bar {
		width: 40rpx;
		background: #3388ff;
		border-radius: 40rpx 40rpx 0 0;
	}

	.chart-month {
		font-size: 26rpx;
		color: #666;
		margin-top: 24rpx;
	}
</style>