<template>
	 <view class="container_bj">
	 	<view class="container">
	 			<!-- <image class="account_numberimage" src="@/static/222.jpg" mode="aspectFill"></image> -->
	 			<!-- 顶部导航栏 -->
	 			<view class="navigation"></view>
	 			<!-- 储能信息 -->
	 			<view class="power">
	 				<view class="power_1">
	 					<view class="power_month">
	 	
	 						<image src="/static/chi.png" mode=""></image>
	 						<!-- 本月储放 -->
	 						{{$t('device.dischargeTitle')}}
	 					</view>
	 					<view class="power_monthkwh">{{unitelectricity(devicedata.monthExportKwh)}} <text class="power_kwh">{{unitwh(devicedata.monthExportKwh)}}</text></view>
	 					<view class="power_Cumulative">
	 						<image src="/static/dian.png" mode=""></image>
	 						<!-- 累计储放 -->
	 						{{$t('device.totalDischarge')}}
	 					</view>
	 					<view class="power_Cumulativekwh">{{unitelectricity(devicedata.accumulativeExportKwh)}} <text class="power_kwh">{{unitwh(devicedata.accumulativeExportKwh)}}</text></view>
	 				</view>
	 				<view class="power_2">
	 	
	 					<image src="@/static/ring.png" mode="aspectFit" class="rotating" />
	 					<view class="power_2txt">
	 						<view class="power_2txt1">
	 							<!-- 昨日放电 -->
	 							{{$t('device.yesterdayDischarge')}}
	 						</view>
	 						<view class="power_2txtmeasure">{{unitelectricity(devicedata.dayExportKwh)}} <text class="power_kwh">{{unitwh(devicedata.dayExportKwh)}}</text></view>
	 					</view>
	 				</view>
	 			</view>
	 	
	 			<!-- 收益信息 -->
	 			<view class="income_box">
	 				<view class="income">
	 					<view class="income_yesterday">
	 						<view class="income_yesterday1">
	 							<!-- 昨日收益 -->
	 							{{$t('device.yesterdayEarnings')}}
	 						</view>
	 						<view class="income_yesterday2">
	 							{{devicedata.yesterdaysearnings?devicedata.yesterdaysearnings.toFixed(2):''}} <text class="income_unit">元</text> </view>
	 					</view>
	 					<view class="income_moon">
	 						<view class="income_moon1">
	 							<!-- 当月收益 -->
	 							{{$t('device.monthlyEarnings')}}
	 						</view>
	 						<view class="income_moon2">{{unitprice(devicedata.monthProfit)}} <text class="income_unit">{{unitprice(devicedata.totalProfit)==devicedata.totalProfit?'元':'万元'}}</text></view>
	 					</view>
	 					<view class="income_tired">
	 						<view class="income_tired1">
	 							<!-- 累计收益 -->
	 							{{$t('device.totalEarnings')}}
	 						</view>
	 						<view class="income_tired2">{{unitprice(devicedata.totalProfit)}} <text class="income_unit">{{unitprice(devicedata.totalProfit)==devicedata.totalProfit?'元':'万元'}}</text></view>
	 					</view>
	 				</view>
	 			</view>
	 	
	 			<!-- 电站信息 -->
	 			<view class="power_box">
	 				<view class="powerstation">
	 					<view class="power_yesterday" @click="ondevices(0)">
	 						<image src="@/static/power.png" mode=""></image>
	 						<view class="power_yesterday1">
	 							<!-- 全部电站 -->
	 							{{$t('device.allStations')}}
	 						</view>
	 						<view class="power_yesterday2">{{muitiStationinfo.totalCnt}}</view>
	 					</view>
	 					<view class="power_moon" @click="ondevices(1)">
	 						<image src="@/static/power.png" mode=""></image>
	 						<view class="power_moon1">
	 							<!-- 在线电站 -->
	 							{{$t('device.onlineStations')}}
	 						</view>
	 						<view class="power_moon2">{{muitiStationinfo.onlineCnt}}</view>
	 					</view>
	 					<view class="power_tired" @click="ondevices(2)">
	 						<image src="@/static/power.png" mode=""></image>
	 						<view class="power_tired1">
	 							<!-- 离线电站 -->
	 							{{$t('device.offlineStations')}}
	 						</view>
	 						<view class="power_tired2">{{muitiStationinfo.offlineCnt||''}}</view>
	 					</view>
	 				</view>
	 			</view>
	 	
	 			<!-- 顶部标签栏  -->
	 			<view class="toptabbar">
	 				<top-tabbar :tabIndex="tabIndex" :tabBars="[
	 	  { name: $t('device.batteryStatus'), id: 0 },
	 	  { name: $t('device.earnings'), id: 1 },
	 	]" @toggleToptab="toggleTab" selectedBottomColor="#30c58d" selectedTextColor="#343434" textColor="#7d7e80"
	 					bgColor="#ffffff"></top-tabbar>
	 			</view>
	 			<view class="datecalendar">
	 				<view class="datecalendar_1">
	 					<view @click="ondatecalendar(1)" class="datecalendar_1sun"
	 						 :style="{
	 						    backgroundColor: brightcalendar === 1 ? '#007544' : '#ffffff',
	 						    color: brightcalendar === 1 ? '#ffffff' : 'inherit'
	 						  }">
	 						<!-- 日 -->
	 						{{$t('device.daily')}}
	 					</view>
	 					<view @click="ondatecalendar(2)" class="datecalendar_1moon"
	 						:style="{
	 						   backgroundColor: brightcalendar === 2 ? '#007544' : '#ffffff',
	 						   color: brightcalendar === 2 ? '#ffffff' : 'inherit'
	 						 }">
	 						<!-- 月 -->
	 						{{$t('device.monthly')}}
	 					</view>
	 					<view @click="ondatecalendar(3)" class="datecalendar_1year"
	 						:style="{
	 						   backgroundColor: brightcalendar === 3 ? '#007544' : '#ffffff',
	 						   color: brightcalendar === 3 ? '#ffffff' : 'inherit'
	 						 }">
	 						<!-- 年 -->
	 						{{$t('device.yearly')}}
	 					</view>
	 				</view>
	 				<view v-if="brightcalendar!=3" class="datecalendar_2" @click="Dateselection">
	 					{{date}}
	 				</view>
	 			</view>
	 			<!-- 日历 -->
	 			<!-- <uni-calendar
	 	      ref="calendar"
	 	      class="uni-calendar--hook"
	 	      :clear-date="true"
	 	      :date="info.date"
	 	      :insert="info.insert"
	 	      :lunar="info.lunar"
	 	      :start-date="info.startDate"
	 	      :end-date="info.endDate"
	 	      :range="info.range"
	 	      @confirm="confirm"
	 	      @close="close"
	 	    /> -->
	 			<KDatePicker v-model="show" :type="selectiondata" :modelValue="date" :is-disabled="isDisabled"
	 				@change="handleChange" :formatter="formatter" />
	 			<!-- 图表 -->
	 			<view class="qiun_data">
	 				<view class="qiun_title">
	 					{{tabIndex==0?$t('device.batteryStatus'):$t('device.earnings')}}<text class="income_unit">{{tabIndex==0?'（'+typewh+'）':'（'+ typefirst +'）'}}</text>
	 				</view>
	 				<qiun-data-charts type="column" :opts="opts" :ontouch="true" :chartData="chartData" />
	 			</view>
	 		</view>
	 </view>

</template>
<!--    -->
<script setup>
	import {
		onMounted,
		ref
	} from 'vue';
	import topTabbar from '@/components/top-tabbar.vue';
	import KDatePicker from '../../components/k-date-picker/KDatePicker.vue';
	import request from '@/utils/request';
	import {
		getMonthRange,
		getMonth
	} from '@/utils/date.js';
	import {
		useI18n
	} from 'vue-i18n'
	const {
		t
	} = useI18n()
	const defaultValue = ref()
	const brightcalendar = ref(1);
	onMounted(() => {
		uni.setTabBarItem({
			index: 0,
			text: t('tabBar.publicize')
		})
		uni.setTabBarItem({
			index: 1,
			text: t('tabBar.products')
		})
		uni.setTabBarItem({
			index: 2,
			text: t('tabBar.Devices')
		})
		uni.setTabBarItem({
			index: 3,
			text: t('tabBar.My')
		})

		const monthRange = getMonthRange();
		params.value = {
			startDate: monthRange.firstDay,
			endDate: monthRange.lastDay
		}
		date.value = monthRange.firstDay.substring(0, 7);
		getoverview(); // 储放收益
		getmuitiStationinfo(); // 电站接口
		getelectricity(); // 充放电统计图

	});

	const devicedata = ref({})
	const getoverview = async () => {
		try {
			const response = await request({
				url: '/muitiStation/overview',
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
			});
			devicedata.value = response.data

		} catch (error) {
			console.error('登录失败:', error);
		}
	}
	// 电站数量
	const muitiStationinfo = ref({})
	const onlineStatus = ref()
	const getmuitiStationinfo = async () => {
		try {
			const response = await request({
				url: '/muitiStation/page/info',
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				data: {
					state: '',
					city: '',
					country: '',
					county: '',
					keyword: '',
					keywordCategory: 0,
					countryCode: '',
					provinceCode: '',
					cityCode: '',
					countyCode: '',
					pn: 1,
					ps: 99,
					onlineStatus: ''
				}
			});
			muitiStationinfo.value = response.data.stationPicArray

		} catch (error) {
			console.error('登录失败:', error);
		}
	};
	// 图表数据
	const chartData = ref({});
	const opts = ref({

		enableScroll: true, //开启滚动条，X轴配置里需要配置itemCount单屏幕数据点数量
		color: ["#B2D5CB"],
		padding: [15, 10, 0, 15],
		backgroundColor: "#B2D5CB",
		legend: {},
		xAxis: {
			disableGrid: true,
			itemCount: 5, //单屏数据密度即图表可视区域内显示的X轴数据点数量，仅在启用enableScroll时有效
			scrollShow: false, //是否显示滚动条，配合拖拽滚动使用（即仅在启用【基本配置】的 enableScroll 时有效）

		},
		yAxis: {
			gridType: "dash",
			dashLength: 2,

		},
		extra: {
			line: {
				type: "straight",
				width: 2,
				activeType: "hollow",

			},
			column: {
				barBorderRadius: [4, 4, 0, 0],
			},
		}

	})
	// const firstDay = ref();
	// const lastDay = ref();
	const params = ref();

	const measureURL = ref('/stats/multStation/power/between/day');
	const incomeURL = ref('/stats/multStation/profit/between/day');
	// 多站电量
	const typewh =ref('kwh')
	const getelectricity = async () => {

		try {
			const response = await request({
				url: measureURL.value,
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				data: params.value
			});
			let arr1 = [];
			let arr2 = [];
			response.data.forEach((item, index) => {
				if (brightcalendar.value == 1) {
					const ymdSubstring = item.ymd.slice(5, 10);
					arr1.push(ymdSubstring);
					arr2.push(((item.dischargeTotal*1)/1000).toFixed(2));
					typewh.value = 'MWh'
				} else {
					arr1.push(item.ymd);
					arr2.push(((item.dischargeTotal*1)/1000).toFixed(2));
					typewh.value = 'MWh'
				}

			})
			setTimeout(() => {
				//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
				let res = {
					categories: arr1,
					series: [{
							name: "电量" + typewh.value,
							data: arr2
						},

					]
				};
				chartData.value = JSON.parse(JSON.stringify(res));
			}, 500);
		} catch (error) {
			console.error('登录失败:', error);
		};
	};

	// 多站收益
	const typefirst =ref('元')
	const getServerData = async () => {
		try {
			const response = await request({
				url: incomeURL.value,
				method: 'POST',
				header: {
					'Content-Type': 'application/x-www-form-urlencoded'
				},
				data: params.value
			});
			let arr1 = [];
			let arr2 = [];
			response.data.forEach((item, index) => {

				if (brightcalendar.value == 1) {
					const ymdSubstring = item.ymd.slice(5, 10);
					arr1.push(ymdSubstring);
					arr2.push((item.profit*1 / 10000).toFixed(2));
					typefirst.value = '万元'
				} else {
					arr1.push(item.ymd);
					arr2.push((item.profit*1 / 10000).toFixed(2));
					typefirst.value = '万元'
				}
			})
			setTimeout(() => {
				//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
				let res = {
					categories: arr1,
					series: [{
							name:'收益' + typefirst.value,
							data: arr2
						},

					]
				};
				chartData.value = JSON.parse(JSON.stringify(res));
			}, 500);
		} catch (error) {
			console.error('登录失败:', error);
		};
	};
	// 选中标签的索引
	const tabIndex = ref(0);

	// 导航栏标签列表
	const tabBars = ref([{
			name: '电量',
			id: 0
		},
		{
			name: '收益',
			id: 1
		},
	]);

	// 切换标签
	const toggleTab = (index) => {
		tabIndex.value = index;
		if (index == 0) {
			if (brightcalendar.value == 3) {
				date.value = new Date().getFullYear();
				params.value = {
					startYearMonth: '2024',
					endYearMonth: date.value
				}
			}
			getelectricity();
		} else {
			if (brightcalendar.value == 3) {
				date.value = new Date().getFullYear();
				params.value = {
					startDate: '2024',
					endDate: date.value
				}
			}
			getServerData(); // 收益统计图
		}
	};

	const show = ref(false)
	const date = ref('')
	const open = () => {
		show.value = true;
		toggleTab(tabIndex.value);
	};
	const isDisabled = (value) => {
		return value > new Date().getTime()
	}

	const handleChange = async (value) => {
		// 示例用法
		try {
			date.value = value
			if (brightcalendar.value == 1) {
				const monthRange = getMonth(value);
				params.value = {
					startDate: monthRange.firstDay,
					endDate: monthRange.lastDay
				}
				// firstDay.value = monthRange.firstDay;
				//   lastDay.value = monthRange.lastDay;
			} else if (brightcalendar.value == 2) {
				params.value = {
					startDate: date.value + '-' + '01',
					endDate: date.value + '-' + '12'
				}
				// firstDay.value =date.value;
				//  lastDay.value = date.value;

			} else if (brightcalendar.value == 3) {
				params.value = {
					startYearMonth: date.value,
					endYearMonth: date.value
				}
				// firstDay.value =date.value;
				//  lastDay.value = date.value; 
			}
			show.value = false
			toggleTab(tabIndex.value);
			// console.log('月初第一天:', monthRange.firstDay); // 输出: 2023-10-01
			// console.log('月末最后一天:', monthRange.lastDay); // 输出: 2023-10-31
		} catch (error) {
			console.error(error.message);
		}

	};
	const selectiondata = ref('month');
	const formatter = ref('YYYY-MM');

	const ondatecalendar = (e) => {
		console.log(e);
		brightcalendar.value = e
		if (e == 1) {
			const monthRange = getMonthRange();
			// firstDay.value = monthRange.firstDay;
			// lastDay.value = monthRange.lastDay;
			params.value = {
				startDate: monthRange.firstDay,
				endDate: monthRange.lastDay
			}
			date.value = monthRange.firstDay.substring(0, 7);
			selectiondata.value = 'month'
			formatter.value = 'YYYY-MM'
			incomeURL.value = '/stats/multStation/profit/between/day'
			measureURL.value = '/stats/multStation/power/between/day'
		} else if (e == 2) {
			const Year = new Date().getFullYear(); // 获取当前年份
			const Month = (new Date().getMonth() + 1).toString().padStart(2, '0'); // 获取当前月份并补零
			date.value = Year + '-' + Month
			// firstDay.value =date.value
			// lastDay.value =date.value
			params.value = {
				startDate: Year + '-' + '01',
				endDate: date.value
			}
			selectiondata.value = 'year'
			formatter.value = 'YYYY'

			incomeURL.value = '/stats/multStation/profit/between/Month'
			measureURL.value = '/stats/multStation/power/between/Month'
		} else if (e == 3) {
			date.value = new Date().getFullYear();
			if (tabIndex.value == 0) {
				params.value = {
					startYearMonth: '2024',
					endYearMonth: date.value
				}
			} else if (tabIndex.value == 1) {
				params.value = {
					startDate: '2024',
					endDate: date.value
				}
			}


			incomeURL.value = '/stats/multStation/profit/between/yearMonth'
			measureURL.value = '/stats/multStation/power/between/yearMonth'
		}
		toggleTab(tabIndex.value);
	}
	const Dateselection = (e) => {
		console.log(e);
		open();
	}
	// 电站列表
	const ondevices = (e) => {
		uni.navigateTo({
			url: `/pages/devices/index?type=${e}`
		})
	}
	// 金额进位
	const unitprice = (e) => {
		if(e*1>10000){
			return (e / 10000).toFixed(2)
		}else{
			return e
		}
	}
	// 放电进位
	const unitelectricity = (e) => {
		
		if(e*1>1000){
			return (e / 1000).toFixed(2)
		} else if(e*1>1000000) {
			
			return (e / 1000000).toFixed(2)
		} else{
			return e
		}
	}
	// 放电进位Wh
	const unitwh = (e) => {
	
	if(e*1>1000){
		return 'MWh'
	} else if(e*1>1000000) {
		return 'GWh'
	} else{
		return 'kWh'
	}
	}
</script>

<style scoped>

.container_bj{
}
	.container {
	background: linear-gradient(to bottom, #007545 -10%, #f0f5f5 40%, #f0f5f5 100%);
		/* background-image: url('@/static/222.jpg'); */
		/* background-size: 100% 600rpx; */
		/* background-repeat: no-repeat; */
		/* box-sizing: border-box; */
	}

	.navigation {
		width: 100%;
		height: 60px;
	}

	.power {
		width: 100%;
		height: 220px;
		padding: 0rpx 40rpx;
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
	}
.power_kwh{
	font-size: 20rpx;
}
	.power_1 {
		height: 180px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		text-align: center;
	}

	.power_1 image {
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}

	.power_month {
		font-size: 32rpx;
		color: #eee !important;
		display: flex;
		align-items: center;
	}

	.power_monthkwh {
		font-size: 32rpx;
		margin-top: 16rpx;
		color: #fff;
	}

	.power_Cumulative {
		font-size: 32rpx;
		display: flex;
		align-items: center;
		margin-top: 42rpx;
		color: #eee !important;
	}

	.power_Cumulativekwh {
		font-size: 32rpx;
		margin-top: 16rpx;
		color: #fff;
	}

	.power_2 {
		padding: 2px;
		width: 170px;
		height: 170px;
		border-radius: 50%;
		border: 3px solid #007545;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		overflow: hidden;
		color: #fff
	}

	.power_2 image {
		width: 160px;
		height: 160px;
	}

	.power_2txt {
		position: absolute;
		top: 32%;
		color: #fff;
	}

	.power_2txt1 {
		color: #eee !important;
		font-size: 38rpx;
	}

	.power_2txtmeasure {
		font-size: 36rpx;
		margin-top: 10px;
		font-weight: 600;
		color: #fff;
		text-align: center;
	}

	/* 旋转动画 */
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.rotating {
		animation: rotate 12s linear infinite;
		transform-origin: 50% 50%;
		backface-visibility: hidden;
		width: 180px;
		height: 180px;
		/* border-radius: 100rpx; */
		/* background-color: #f0f5f5; */
		overflow: hidden;
	}

	.income_box {
		width: 100%;
		height: 200rpx;
		box-sizing: border-box;
		padding: 20rpx;
	}

	.income {
		width: 100%;
		height: 200rpx;
		border-radius: 16rpx;
		background-color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.income_yesterday1,
	.income_moon1,
	.income_tired1 {
		font-size: 28rpx;
		color: #999999;
	}

	.income_yesterday2,
	.income_moon2,
	.income_tired2 {
		margin-top: 20rpx;
		font-size: 32rpx;
		font-weight: 600;
	}
.income_unit{
	font-size: 22rpx;

}
	.power_box {
		width: 100%;
		height: 220rpx;
		padding: 20rpx;
		box-sizing: border-box;
		margin-top: 20px;
	}

	.powerstation {
		width: 100%;
		height: 220rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.power_yesterday,
	.power_moon,
	.power_tired {
		width: 31%;
		height: 100%;
		display: flex;
		border-radius: 10rpx;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: #ffffff;
	}

	.power_yesterday image,
	.power_moon image,
	.power_tired image {
		width: 48rpx;
		height: 48rpx;
		padding: 13rpx;
		border-radius: 100%;
	}

	.power_yesterday image {
		background-color: #007544;
	}

	.power_moon image {
		background-color: #3774f3;
	}

	.power_tired image {
		background-color: #b3cef9;
	}

	.power_yesterday1,
	.power_moon1,
	.power_tired1 {
		margin: 10rpx 0rpx;
		font-size: 28rpx;
		color: #999999;
	}

	.toptabbar {
		width: 100%;
		height: 80rpx;
		margin-top: 20px;
		padding: 10rpx 20rpx;
		box-sizing: border-box;
	}

	/deep/ .uni-scroll-view-content {
		display: flex;
		justify-content: center;
	}

	.datecalendar {
		display: flex;
		justify-content: space-between;
		padding: 0rpx 24rpx;
		margin-top: 60rpx;
	}

	.datecalendar_1 {
		width: 320rpx;
		height: 60rpx;
		display: flex;
		font-size: 28rpx;
		border: 0.2rpx solid #999999;
		border-radius: 40rpx;
		overflow: overlay;
	}

	.datecalendar_1sun {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #222222;
		background-color: #ffffff;
	}

	.datecalendar_1moon {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #ffffff;
		border-left: 0.2rpx solid #999999;
		border-right: 0.2rpx solid #999999;
	}

	.datecalendar_1year {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #ffffff;
	}

	.datecalendar_2 {
		width: 180rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		border: 0.2rpx solid #999999;
		border-radius: 40rpx;
	}

	.qiun_data {
		width: 100%;
		height: 600rpx;
		padding: 16rpx;
		overflow: auto;
		box-sizing: border-box;
	}

	.qiun_title {
		height: 12%;
		font-size: 28rpx;
		margin-left: 20rpx;
	}

	.account_numberimage {
		width: 100%;
		padding: 0rpx;
		position: fixed;
		top: 0rpx;
		left: 0rpx;
	}
</style>