<template>
	<!-- <view style="margin-left: 20rpx;"> <uni-title :title="strDate + '：生产数据'" type="h1" color="red" /> -->
	<!-- </view> -->
	<view class="content">
		<!-- 标题行 -->
		<view class="header-row">
			<view class="title">原油产量</view>
			<view class="more"></view>
		</view>
	</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">{{ item.rcwy || '-' }}</text>
				</view>
				<view class="content">
					<text class="label">月累计</text>
					<text class="value">{{ item.yl || '-' }}</text>
				</view>
				<view class="content">
					<text class="label">年累计</text>
					<text class="value">{{ item.nl || '-' }}</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>
	<!-- 数据弹窗 -->
	<wd-popup v-model="popup" position="bottom" closable custom-style="height: 400px;" @close="handleClose">
		<wd-cell-group title="原油数据详情 单位(吨)">
			<wd-table :data="dataJinri" :height="800">
				<wd-table-col prop="dw" label="名称" :width="screenWidth * 29 / 140" align="center"></wd-table-col>
				<wd-table-col prop="rcwy" label="日油量" :width="screenWidth / 5" align="center"></wd-table-col>
				<wd-table-col prop="yl" label="月累计" :width="screenWidth / 5" align="center"></wd-table-col>
				<wd-table-col prop="nl" label="年累计" :width="screenWidth / 4" align="center"></wd-table-col>
				<wd-table-col prop="" label="操作" :width="screenWidth / 7" align="center">
					<template #value="{row}">
						<text style="color: red;" @click="goHistory(row)">历史</text>
					</template>
				</wd-table-col>
			</wd-table>
		</wd-cell-group>
	</wd-popup>
</template>

<script setup>
	import {
		queryJinriYuanyouShengchansj
	} from '@/api/production';
	import {
		formatDate,
		getDateAfterDays
	} from '@/utils/dateTime';
	const shishiArr = ref([{
		gas: '原油产量',
		rcwy: '',
		yl: '',
		nl: '',
		yearPlan: '1500',
		yearPerCent: ''
	}]);
	const screenWidth = ref(0)
	const dataJinri = ref([]);
	const dataJinriSum = ref([]);
	const popup = ref(false);
	// 点击卡片处理
	const handleCardClick = () => {
		popup.value = true
	};

	// 关闭弹窗
	const closePopup = () => {
		popup.value = false
	};
	onMounted(() => {
		getJinriYuanyouShengchansj();
		// getYearShengchansj();
		calculateTableHeight();
		// 监听屏幕旋转变化
		uni.onWindowResize(() => {
			calculateTableHeight();
		});
	});

	const strDate = ref('');
	// 数字格式化
	const formatNumber = (num) => {
		if (typeof num !== 'number') return '-';
		return num.toFixed(4).replace(/\.?0+$/, '');
	};
	const handleClose = () => {
		popup.value = false
	}

	function goHistory(val) {
		uni.navigateTo({
			url: '/pages/production/ribaoshuju/rbsjLsxq?data=' + JSON.stringify(val) + '&type=yy'
		});
	}
	const calculateTableHeight = () => {
		const systemInfo = uni.getSystemInfoSync();
		screenWidth.value = systemInfo.screenWidth;
	}
	const getJinriYuanyouShengchansj = () => {
		const now = new Date();
		if (now.getHours() < 11) {
			strDate.value = formatDate(getDateAfterDays(now, -1)).toString(); //11点之前  头一天的数据
		} else {
			strDate.value = formatDate(now).toString();
		}
		let queryParms = {};
		dataJinri.value = [];
		dataJinriSum.value = [];
		queryParms.scrq = strDate.value;
		queryParms.pageSize = 100;
		queryJinriYuanyouShengchansj(queryParms).then((res) => {
			if (res.success) {
				dataJinri.value = res.result.records;
				dataJinriSum.value = sumByOil(dataJinri.value); //包含gas  unit  rq  cq  totalGas
				// // console.log(dataJinriSum.value);
				nextTick();
				shishiArr.value.forEach((item) => {
					dataJinriSum.value.forEach((itemjinri) => {
						item.rcwy = itemjinri.rcwy.toFixed(4);
						item.nl = itemjinri.nl.toFixed(4);
						item.yl = itemjinri.yl.toFixed(4);
						item.yearPerCent = calcPercent(item.yearPlan, item.nl);
					});
				});

				dataJinri.value = dataJinri.value.map(item => {
					return {
						...item,
						rcwy: formatNumber(item.rcwy),
						yl: formatNumber(item.yl),
						nl: formatNumber(item.nl)
					}
				})
				// getYearShengchansj(); //再获取今年以来的数据
			}
		});
	};

	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)); // 转为数值
	}

	function sumByOil(records) {
		// console.log(records);
		const summaryMap = {};
		try {
			records.forEach((record) => {
				const gas = record.gas;
				if (!summaryMap[gas]) {
					// 初始化该 gas 类型的汇总对象
					summaryMap[gas] = {
						rcwy: 0,
						yl: 0,
						nl: 0
					};
				}
				// 无论是否是第一次遇到该 gas 类型，都进行累加操作
				summaryMap[gas].rcwy += record.rcwy || 0;
				summaryMap[gas].yl += record.yl || 0;
				summaryMap[gas].nl += record.nl || 0;
			});
			return Object.values(summaryMap);
		} catch (error) {
			//TODO handle the exception
			// console.log(error);
		}
	}
</script>

<style lang="scss" scoped>
	.header-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 0;
		border-bottom: 1rpx solid #eee;
		margin-left: 10px;
		margin-right: 10px;

	}

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

	.more {
		font-size: 26rpx;
		color: #666;
		cursor: pointer;
	}

	.more::after {
		content: '';
		width: 8rpx;
		height: 8rpx;
		border-top: 2rpx solid #666;
		border-right: 2rpx solid #666;
		transform: rotate(45deg);
		margin-left: 8rpx;
		vertical-align: middle;
	}

	/* 鼠标悬停效果 */
	.more:hover {
		color: #007aff;
	}

	.container {
		display: flex;
		flex-wrap: wrap;
		padding: 20rpx;
		gap: 20rpx;
	}

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

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

	.card {
		background: #ececec;
		border-radius: 16rpx;
		padding: 15rpx;
		box-shadow: 0 4rpx 12rpx rgba(197, 197, 197, 0.1);

		.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-bar {
		position: relative;
		height: 20px;
		background: #f0f0f0;
		border-radius: 10px;
		overflow: hidden;
	}

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