<template>
	<scroll-view scroll-y class="page">
		<!-- Header -->
		<view class="title-card">
			<text class="title">物联网智能抄表管理系统</text>
		</view>

		<!-- 应缴金额区域 -->
		<view class="amount-area">
			<view class="row between">
				<text class="label">应缴金额(元)</text>
				<text class="amount" v-if="userInfo.settledType === 1">{{ userInfo.shouldCollectMoney }}</text>
				<text class="amount" v-else>0.00</text>
			</view>
			<view class="row between">
				<text></text>
				<text class="warn" v-if="userInfo.settledType === 1">有欠费，请尽快缴费</text>
			</view>
			<view class="info">
				<view class="row between info-item">
					<text>截止时间</text>
					<text class="warn">{{ userInfo.lastExamineTime }}</text>
				</view>
				<view class="row between">
					<text>户号信息</text>
					<text class="warn">{{ userInfo.userCode }}</text>
				</view>
				<view class="row between">
					<text>地址信息</text>
					<text class="warn">{{ userInfo.roomNumber }}</text>
				</view>
				<view class="row between info-mani">
					<text>缴费单位</text>
					<text class="warn">{{ userInfo.companyName }}</text>
				</view>
			</view>
		</view>
		<view class="floating-view"></view>
		<!-- 缴费金额选择 -->
		<view class="pay-select">
			<text class="label">缴费金额</text>
			<view class="preset">
				<button class="amount-btn" @click="duplicationEvents(20)">20元</button>
				<button class="amount-btn" @click="duplicationEvents(50)">50元</button>
				<button class="amount-btn" @click="duplicationEvents(100)">100元</button>
			</view>
		

			<view class="input-wrapper">
				<text class="prefix">¥</text>
				<input class="custom-input" v-model="moneyvalue" type="number" min="0" step="0.01" placeholder="点击输入缴费金额" />
			</view>
			<view class="current-debt" v-if="userInfo.settledType === 1">
				<text>当前欠费金额 {{ userInfo.shouldCollectMoney }} 元 </text>
				<text class="auto-fill warn" @click="duplicationEvents(money.value)">点击自动填入</text>
			</view>
			<view class="current-debt" v-else>
				<text>当前暂为欠费 </text>
			</view>
		</view>

		<!-- 支付按钮 -->
		<view class="pay-buttons">
			<button class="wxpay" @click="qita('weiPay')">微信支付</button>
			<button class="otherpay" @click="qita('zfbPay')">其他支付</button>
		</view>

		<!-- 二维码弹框 -->
		<uni-popup ref="popup" type="center" z-index="999" >
			<view class="modal">
				<text class="modal-title">物联网智能抄表管理系统</text>
				<view class="qrcode-container">
					<img v-if="qrcodeContainer" :src="qrcodeContainer" alt="" />
				</view>
				<button class="modal_button" @click="saveScreenshot">截屏保存</button>
			</view>
		</uni-popup>

		<!-- 账单信息 -->
		<view class="bill-info">
			<view class="bill-head">
				<text class="label">账单信息</text>
				<!-- <text class="date">2024年10月</text> -->
				<view class="container">
					<!-- <picker mode="date" fields="month" :value="single" start="2000-01-01" end="2030-12-31"
						@change="onMonthChange">
						<view class="uni-input">{{ single || defaultDate }} <text>▼</text></view>
					</picker> -->
					<picker
						mode="date"
						fields="month"
						:value="single"
						:start="startDate"
						:end="endDate"
						@change="onMonthChange"
					>
						<view class="uni-input">{{ single || defaultDate }} <text>▼</text></view>
					</picker>
				</view>
			</view>
			<view class="bill-detail">
				<text>本期用水量(m³)：<text class="bold">{{ currentWater }}</text></text>
				<text>本期水费(元)：<text class="bold">{{ currentMoney }}</text></text>
			</view>

			<!-- 用水柱状图 -->
			<LEchart force-use-old-canvas="false" class="chart" ref="barChartref" @finished="init"></LEchart>

			<text class="label">用水量情况</text>

			<!-- 用水曲线图 -->
			<LEchart force-use-old-canvas="false" class="chart2" ref="lineChartref" @finished="init"></LEchart>
		</view>
	</scroll-view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref,
		nextTick
	} from 'vue'
	import { get } from '@/utils/request'
	import { onLoad } from '@dcloudio/uni-app'
	import QRCode from 'qrcode-generator';
	import LEchart from '@/components/l-echart/l-echart.vue';
	
	const userInfo = ref({})
	
	// 图表  柱状  折线
	const barChartref = ref();
	const lineChartref = ref();
	
	onLoad(() => {
	  userInfo.value = uni.getStorageSync('userInfo')
	  setTimeout(() => {
		  getCurrentYearMonth();
	  }, 1000)
	})
	
	const echarts = require('../../static/echarts.min');
	
	// 点击选择年月
	const single = ref('');
	// 默认年月
	const defaultDate = ref('');
	// 欠费金额
	const money = ref(87.12)
	// 缴费金额
	const moneyvalue = ref()
	// 是否显示二维码弹框
	const showQRCodeModal = ref(false);
	const popup = ref(null);
	// 二维码容器
	const qrcodeContainer = ref('http://192.168.50.127:18001/api/images/63a8db7bfb4f190d6aed819088bfb396.jpg');
	// 本期用水量
	const currentWater = ref(0)
	// 本期水费
	const currentMoney = ref(0)
	// 自动填入
	const duplicationEvents = (data) => {
		moneyvalue.value = data
	}

	// 支付
	const qita = async (value) => {
		try {
			const res = await get('/api/payConfig/pay', {
			  payType: value
			})
			if (res.code === '200') {
				qrcodeContainer.value = res.data
				popup.value.open();
			} else {
				uni.showToast({ title: res.message || '绑定失败', icon: 'none' })
			}
		} catch (err) {
		  // console.log('请求失败：', err)
		  uni.showToast({ title: '请求失败，请稍后重试', icon: 'none' })
		}
	}

	// 截屏保存按钮点击事件
	const saveScreenshot = () => {
		// 这里可以实现截屏保存的逻辑，例如使用 HTML2Canvas 库
		console.log('截屏保存');
	};
	
	// 获取当前年份
	const currentYear = new Date().getFullYear()
	
	// 设置起始和结束为今年范围
	const startDate = `${currentYear}-01-01`
	const endDate = `${currentYear}-12-31`
	
	// 默认月份：当前月
	const now = new Date()
	const defaultMonth = `${currentYear}-${String(now.getMonth() + 1).padStart(2, '0')}`
	
	const selectedMonth = ref('')
	// 点击弹框获取年月
	const onMonthChange = (e) => {
		 // 截取到年月，如 "2025-06"
		const value = e.detail.value.slice(0, 7)
		single.value = value
		// console.log(single.value, 'selected month')
	
		// 提取月份部分（注意转为数字）
		const month = Number(value.slice(5, 7))
	
		if (month <= 6) {
			// console.log('上半年逻辑')
			findByTimes(1, 6)
		} else {
			// console.log('下半年逻辑')
			findByTimes(7, 12)
		}
	}

	// 默认显示时间
	const getCurrentYearMonth = () => {
		const date = new Date()
		const year = date.getFullYear()
		const month = date.getMonth() + 1 // JS 中月份从 0 开始
	
		// 格式化为 "YYYY-MM"
		const formattedMonth = String(month).padStart(2, '0')
		const shij = `${year}-${formattedMonth}`
	
		defaultDate.value = shij
		single.value = shij
	
		// 根据月份判断逻辑
		if (month <= 6) {
			// console.log('当前为上半年，执行上半年默认逻辑')
			findByTimes(1, 6)
		} else {
			// console.log('当前为下半年，执行下半年默认逻辑')
			findByTimes(7, 12)
		}
	}
	
	const realCollectMoneylist = ref([])
	const waterlist = ref([])
	const monthLabelslist = ref([])
	const findByTimes = async (startTime, endTime) => {
		
		try {
			const res = await get('/api/waterUser/findByTime', {
			  startTime: startTime,
			  endTime: endTime,
			  phoneNumber: userInfo.value.phoneNumber
			})
			if (res.code === '200') {
				currentMoney.value = res.data.currentMoney
				currentWater.value = res.data.currentWater
				
				realCollectMoneylist.value = res.data.data.map(item => Number(item.realCollectMoney));
				waterlist.value = res.data.data.map(item => item.waterData);
				monthLabelslist.value = res.data.months.map(item => `${item}月`);
				
				// 动态更新柱状图配置
				state.option.xAxis.data = monthLabelslist.value; // 更新 X 轴数据
				state.option.series[0].data = realCollectMoneylist.value; // 更新柱状图数据
			
				// 动态更新柱状图配置
				state.option.xAxis.data = monthLabelslist.value;
				state.option.series[0].data = realCollectMoneylist.value;
			
				// 动态更新折线图配置
				state2.option.xAxis.data = monthLabelslist.value;
				state2.option.series[0].data = waterlist.value;
			
				// 立即初始化图表
				barChartref.value.init(echarts, (chart) => {
					chart.setOption(state.option);
				});
				lineChartref.value.init(echarts, (chart) => {
					chart.setOption(state2.option);
				});
			} else {
				uni.showToast({ title: res.message || '查询失败', icon: 'none' })
			}
		} catch (err) {
		  uni.showToast({ title: '请求失败，请稍后重试', icon: 'none' })
		}
	}

	// 折线图
	const state2 = reactive({
		option: {}
	});

	state2.option = {
		grid: {
			right: '2%',
			top: '18%',
			left: '8%',
			bottom: '18%'
		},
		xAxis: {
			type: 'category',
			data: monthLabelslist.value,
			axisTick: {
				// 不显示刻度线
				show: false
			}
		},
		yAxis: {
			type: 'value',
			name: '(m³)',
		},
		series: [{
			data: waterlist.value,
			type: 'line',
			areaStyle: {},
			smooth: true,
			color: '#7bed8b',
			symbol: 'none',
			emphasis: {
				// 鼠标悬停时显示数据点
				itemStyle: {
					borderWidth: 2,
					borderColor: '#fff'
				},
				label: {
					show: true
				},
				// 鼠标悬停时显示圆形数据点
				symbol: 'circle',
				symbolSize: 8,
			}
		}]
	}

	// 柱状图
	const state = reactive({
		option: {}
	})
	// 获取当前月份（注意：getMonth() 返回值是 0 - 11，所以需要加 1）
	// const currentMonth = new Date().getMonth() + 1;
	// const months = ['5月', '6月', '7月', '8月', '9月'];
	// const data = realCollectMoneylist.value;
	const colors = new Array(realCollectMoneylist.value.length).fill('#cfdfff');

	// // 找到当前月份在 months 数组中的索引
	// const index = realCollectMoneylist.value.indexOf(`${currentMonth}月`);
	// if (index !== -1) {
	// 	// 如果找到当前月份对应的索引，将该柱子颜色修改为 #1756d9
	// 	colors[index] = '#1756d9';
	// }

	state.option = {
		grid: {
			right: '2%',
			top: '18%',
			left: '9%',
			bottom: '20%'
		},
		xAxis: {
			type: 'category',
			data: monthLabelslist.value, // X 轴数据
			axisTick: {
				// 不显示刻度线
				show: false
			}
		},
		yAxis: {
			type: 'value',
			name: '(元)'
		},
		series: [{
			data: realCollectMoneylist.value,
			type: 'bar',
			// 使用 colors 数组来设置每个柱子的颜色
			itemStyle: {
				color:'#1756d9'
			},
			barWidth: '40%',
			label: {
				show: true,
				position: 'top',
				color: '#1756d9'
			}
		}]
	};

	// 渲染完成
	const init = () => {
		console.log('渲染完成');
	}
</script>

<style scoped lang="scss">
	:deep .uni-popup {
		z-index: 999 !important;
	}
	/* 遮罩层样式 */
	.modal-overlay {
		z-index: 99999 !important;
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		/* 修改为 align-items 以垂直居中 */
		position: fixed;
		top: 0;
		left: 0;
		background-color: rgba(0, 0, 0, 0.5);
		/* 加深背景透明度 */
		backdrop-filter: blur(3rpx);
		/* 添加模糊效果 */
	}

	/* 模态框样式 */
	.modal {
		width: 600rpx;
		height: 850rpx;
		background: #ffffff;
		/* 白色背景 */
		border-radius: 15rpx;
		/* 增大圆角 */
		text-align: center;
		position: relative;
		box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
		/* 添加阴影效果 */
		padding: 40rpx;
		/* 添加内边距 */
		box-sizing: border-box;
		/* 包含内边距在宽度内 */
	}

	/* 模态框标题样式 */
	.modal-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		margin-bottom: 30rpx;
		/* 增加底部间距 */
	}

	/* 二维码容器样式 */
	.qrcode-container {
		width: 520rpx;
		height: 520rpx;
		/* 调整二维码容器高度 */
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 40rpx;
		/* 增加底部间距 */
	}

	/* 按钮样式 */
	.modal_button {
		position: absolute;
		/* 修改为相对定位 */
		left: 0;
		bottom: 0;
		width: 100%;
		border: none;
		background: linear-gradient(to right, #6ea5ff, #3d81fd);
		/* 蓝色背景 */
		color: #ffffff;
		/* 白色文字 */
		font-size: 32rpx;
		padding: 15rpx 0;
		border-radius: 0rpx;
	}

	/* 按钮悬停效果 */
	.modal_button:hover {
		background-color: #0056b3;
		/* 悬停时颜色加深 */
	}

	.page {
		width: calc(100% - 60rpx);
		background-color: #f7f8fa;
		padding: 30rpx;
	}

	.title-card {
		background: linear-gradient(to right, #6ea5ff, #3c80fd);
		padding: 25rpx 25rpx 45rpx 25rpx;
		border-radius: 20rpx 20rpx 0 0;
	}

	.title {
		color: #fff;
		font-size: 30rpx;
		font-weight: bold;
		text-align: center;
	}

	.amount-area {
		background: #fff;
		padding: 30rpx;
		border-radius: 20rpx;
		margin-top: -20rpx;
		margin-bottom: 2rpx;
	}

	.amount-area .row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.floating-view {
		border-top: 2rpx dashed #d8d8d8;
		width: calc(100% - 40rpx);
		margin: 0 20rpx;
	}

	.amount {
		font-size: 50rpx;
		color: #000;
		font-weight: bold;
	}

	.label {
		font-weight: 600;
		font-size: 35rpx;
		color: #515151;
	}

	.warn {
		color: red;
		margin-top: 10rpx;
		font-size: 24rpx;
	}

	.info text {
		display: block;
		margin-top: 10rpx;
		font-size: 26rpx;
		color: #666;
		margin: 13rpx;
	}

	.info-item {
		margin-top: 16px;
		border-bottom: 1rpx solid #e6e6e6;
	}

	.info-mani {
		/* border-bottom: 1rpx solid #e6e6e6; */
	}

	.pay-select {
		background: #fff;
		padding: 30rpx;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.preset {
		display: flex;
		justify-content: space-between;
		margin: 35rpx 0;
	}

	.amount-btn {
		background-color: #f5f5f5;
		color: #333;
		font-weight: bold;
		padding: 0rpx 40rpx;
		border: none;
		border-radius: 10rpx;
		font-size: 28rpx;
	}

	.amount-btn::after {
		border: 0px solid rgba(0, 0, 0, 0.2);
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		height: 70rpx;
		border-bottom: 1rpx solid #e6e6e6;
	}

	.prefix {
		font-size: 32rpx;
		font-weight: 600;
		color: #3e3e3e;
		margin-right: 10rpx;
	}

	.custom-input {
		flex: 1;
		font-size: 32rpx;
		color: #333;
		border: none;
		outline: none;
	}

	.current-debt {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 24rpx;
		color: #666;
		margin-top: 16rpx;
	}

	.auto-fill {
		color: #2f80ed;
		margin-left: 10rpx;
	}

	.pay-buttons {
		display: flex;
		justify-content: space-around;
		margin: 40rpx 0;
	}

	.wxpay {
		background-color: #2f80ed;
		color: white;
		border-radius: 50rpx;
		flex: 1;
		margin-right: 20rpx;
	}

	.otherpay {
		border: 1rpx solid #2f80ed;
		color: #2f80ed;
		background-color: white;
		border-radius: 50rpx;
		flex: 1;
	}

	.bill-info {
		background: #fff;
		padding: 30rpx;
		border-radius: 20rpx;
		margin-bottom: 40rpx;
	}

	.bill-head {
		display: flex;
		justify-content: space-between;
		font-weight: bold;
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}

	.bill-detail {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;
	}

	.bold {
		font-weight: bold;
		font-size: 30rpx;
	}

	.chart {
		height: 300rpx;
		width: 100%;
		z-index: 2 !important;
	}

	.chart2 {
		margin-top: 16rpx;
		height: 300rpx;
		width: 100%;
		z-index: 2 !important;
	}
</style>