<template>
	<view :class="{ gray: store.isgray == 1 }">
		<view class="progress-bar">
			<!-- 动态设置宽度和颜色 -->
			<view class="progressTime" :style="{ width: `${timePercent}%`, 'background-color': '#00aaff' }"></view>
			<!-- 显示带符号的百分比 -->
			<text class="progress-text">全年时间进度:{{ timePercent }}%</text>
		</view>
		<view class="container">
			<view v-for="(item, index) in shishiArr" :key="index" class="card-item" @click="handleCardClick(item.gas)">
				<view class="card">
					<text class="title">{{ item.gas }}</text>
					<view class="content">
						<text class="label">气量</text>
						<text class="value">{{ formatNumber(item.dailyVolume) || '-' }}</text>
					</view>
					<view class="content">
						<text class="label">年累计</text>
						<text class="value">{{ formatNumber(item.yearVolume) || '-' }}</text>
					</view>
					<view class="progress-bar">
						<!-- 动态设置宽度和颜色 -->
						<view class="progress" :style="{ width: `${Math.abs(item.yearPerCent)}%`, 'background-color': item.yearPerCent < 0 ? '#ff4444' : '#007aff' }"></view>
						<!-- 显示带符号的百分比 -->
						<text v-if="!(item.yearPlan === '' || item.yearPlan === '0')" class="progress-text">{{ item.yearPerCent }}%</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 数据弹窗 -->
		<uni-popup ref="popup" type="bottom" background-color="#fff">
			<view class="popup-content">
				<view class="popup-header">
					<text class="title">{{ selectedGas }}数据详情 单位(万立方米)</text>
					<uni-icons type="closeempty" size="24" color="#666" @click="closePopup"></uni-icons>
				</view>

				<view class="table">
					<!-- 表头 -->
					<view class="tr header">
						<view class="th1">序号</view>
						<view class="th">名称</view>
						<view class="th">日气量</view>
						<view class="th">年累计</view>
						<view class="th1">操作</view>
					</view>
					<scroll-view scroll-X="true" scroll-Y="true" class="table-container">
						<!-- 表格内容 -->
						<view class="tr" v-for="(item, index) in filteredData" :key="index" :class="{ even: index % 2 === 0 }">
							<view class="td1">{{ index + 1 }}</view>
							<view class="td">{{ item.unit }}</view>
							<view class="td" :class="{ negative: item.rq < 0 }">
								{{ formatNumber(item.rq) }}
							</view>
							<view class="td" :class="{ negative: item.yearVolume < 0 }">
								{{ formatNumber(item.yearVolume) }}
							</view>
							<view class="td1" style="color: red" @click="goHistory(item)">历史</view>
						</view>

						<!-- 空数据提示 -->
						<view v-if="!filteredData.length" class="empty">暂无相关数据</view>
					</scroll-view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, watchEffect } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { queryJinriShengchansj, queryYearShengchansj, queryJinriTrqShengchansj } from '@/api/shengchan.js';
import { formatDate, getDateAfterDays } from '@/utils/dateTime.js';
import { beforeJump } from '@/utils/index.js';
import { useStore } from '@/store';
import { getYearProgress } from '@/utils/dateTime.js';

const store = useStore();

const shishiArr = ref([]);
const dataJinriUnit = ref([]);
const selectedGas = ref('');
const filteredData = ref([]);
const popup = ref(null);
const strDate = ref('');
const timePercent = ref(0);

// 点击卡片处理
const handleCardClick = (gas) => {
	selectedGas.value = gas;
	let queryParms = {};
	filteredData.value = [];
	queryParms.day = strDate.value;
	queryParms.gas = gas;
	queryParms.unit = '文23气田,户部寨气田';
	console.log(queryParms);
	queryJinriTrqShengchansj(queryParms).then((res) => {
		if (res.success) {
			console.log(res);
			filteredData.value = res.result;
		}
	});

	popup.value.open();
};

// 关闭弹窗
const closePopup = () => {
	popup.value.close();
};
onMounted(() => {
	getJinriShengchansj();
	timePercent.value = getYearProgress();
});

// 数字格式化
const formatNumber = (num) => {
	let temp = 0;
	try {
		temp = parseFloat(num);
	} catch (error) {
		//TODO handle the exception
	}

	return temp.toFixed(4).replace(/\.?0+$/, '');
};

// 自动计算综合输差
watchEffect(() => {
	let totalJinqi = {
		gas: '总进气',
		dailyVolume: 0,
		yearVolume: 0,
		yearPlan: '100',
		yearPerCent: 0
	};
	let totalChuqi = {
		gas: '总出气',
		dailyVolume: 0,
		yearVolume: 0,
		yearPlan: '100',
		yearPerCent: 0
	};
	const compositeZx = {
		gas: '站线综合输差',
		dailyVolume: 0,
		yearVolume: 0,
		yearPlan: '100',
		yearPerCent: 0
	}; // 综合输差
	const compositeJc = {
		gas: '进出综合输差',
		dailyVolume: 0,
		yearVolume: 0,
		yearPlan: '100',
		yearPerCent: 0
	}; // 综合输差
	shishiArr.value.forEach((item) => {
		if (item.gas === '站输差' || item.gas === '线输差') {
			compositeZx.dailyVolume += parseFloat(item.dailyVolume) || 0;
			compositeZx.yearVolume += parseFloat(item.yearVolume) || 0;
		}
		if (item.gas === '气井气' || item.gas === '外部气' || item.gas === '返回气') {
			totalJinqi.dailyVolume += parseFloat(item.dailyVolume) || 0;
			totalJinqi.yearVolume += parseFloat(item.yearVolume) || 0;
		}
		if (item.gas === '自耗气' || item.gas === '用户气' || item.gas === '返采油厂干气') {
			totalChuqi.dailyVolume += parseFloat(item.dailyVolume) || 0;
			totalChuqi.yearVolume += parseFloat(item.yearVolume) || 0;
		}
	});

	compositeZx.yearPerCent = calcPercent(compositeZx.yearPlan, compositeZx.yearVolume);

	compositeJc.dailyVolume = (-totalJinqi.dailyVolume + totalChuqi.dailyVolume).toFixed(4);
	compositeJc.yearVolume = (-totalJinqi.yearVolume + totalChuqi.yearVolume).toFixed(4);
	compositeJc.yearPerCent = calcPercent(compositeJc.yearPlan, compositeJc.yearVolume);
	shishiArr.value.push(compositeZx);
	shishiArr.value.push(compositeJc);

	// console.log(composite);
});

const getJinriShengchansj = () => {
	const now = new Date();
	if (now.getHours() < 11) {
		strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11点之前  头一天的数据
	} else {
		strDate.value = formatDate(now).toString();
	}
	let queryParms = {};
	shishiArr.value = [];

	queryParms.day = strDate.value;
	// // console.log(queryParms);
	queryJinriTrqShengchansj(queryParms).then((res) => {
		if (res.success) {
			console.log(res);
			let temp = res.result;

			temp.forEach((item) => {
				if (item.gas === '气井气') {
					item.yearPlan = 7500;
					item.yearPerCent = calcPercent(item.yearPlan, item.yearVolume);
				}
			});
			shishiArr.value = temp;
		}
	});
};
function goHistory(val) {
	uni.navigateTo({
		url: '/pages/views/shengchan/ribaoshuju/rbsjLsxq?data=' + JSON.stringify(val) + '&type=trq'
	});
}
function calcPercent(yearJihua, yearShiji) {
	// 计算进度百分比，避免除数为 0
	// 确保进度百分比不超过 100
	let plan = parseFloat(yearJihua === '' ? 0 : yearJihua);
	let shiji = parseFloat(yearShiji);
	let percent = 0;
	// 修改原始计算代码
	if (plan > 0) {
		percent = (shiji / plan) * 100;
		percent = Math.min(percent, 100); // 限制最大100%
	}
	return parseFloat(percent.toFixed(2)); // 转为数值
}
</script>

<style lang="scss" scoped>
.container {
	display: flex;
	flex-wrap: wrap;
	padding: 20rpx;
	gap: 20rpx;
}

.popup-content {
	padding: 30rpx;
	max-height: 40vh;
}

.popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
	padding-bottom: 20rpx;
	border-bottom: 2rpx solid #eee;

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

.table-container {
	width: 100%;
	height: 30vh;
	overflow: hidden;
}

.table {
	min-width: 100%;
	border: 2rpx solid #e8e8e8;

	.tr {
		display: flex;
		border-bottom: 2rpx solid #e8e8e8;

		&.header {
			background-color: #fafafa;
			font-weight: 600;
		}

		&.even {
			background-color: #f8f8f8;
		}
	}

	.th,
	.td {
		flex: 1;
		min-width: 80rpx;
		padding: 10rpx;
		font-size: 22rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		white-space: nowrap;
		height: 30rpx;
		vertical-align: middle;
	}

	.th1,
	.td1 {
		flex: 1;
		max-width: 40rpx;
		padding: 10rpx;
		font-size: 22rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		white-space: nowrap;
		height: 30rpx;
		vertical-align: middle;
	}

	.th {
		background-color: #f0f0f0;
	}

	.td.negative {
		color: #ff4444;
		font-weight: 500;
	}
}

.empty {
	padding: 40rpx;
	text-align: center;
	color: #888;
	font-size: 16rpx;
}

.card-item {
	flex: 1 1 200rpx; // 基础宽度300rpx，自动伸缩   selectedGas  formatNumber
	min-width: 240rpx;
	max-width: calc(50% - 10rpx); // 最大不超过容器一半（考虑间距）

	@media (min-width: 768px) {
		max-width: calc(33.33% - 14rpx); // 大屏显示3列
	}
}

.card {
	background: #ffffff;
	border-radius: 16rpx;
	padding: 10rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.title {
		display: block;
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 16rpx;
	}

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

		&:last-child {
			margin-bottom: 0;
		}

		.label {
			font-size: 24rpx;
			color: #666;
		}

		.value {
			font-size: 28rpx;
			color: #0000ff;
			font-weight: 500;
		}
	}
}

.progress-item {
	margin-bottom: 20px;
}

.progress-bar {
	position: relative;
	height: 20px;
	background: #f0f0f0;
	border-radius: 10px;
	overflow: hidden;
}

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

.progress-text {
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%, -50%);
	color: red; /* 保持红色 */
	font-size: 12px;
	font-weight: bold;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1); /* 提升可读性 */
}
</style>
