<template>
	<view class="pcs-warp">
		<view class="box">
			<view class="topology-box">
				<Section :title="$t('homePage.home.mpptTopu')" />
				<topoCanvas cId="canvas" :width="'100%'" :height="'100%'" :canvas-data="canvasData" />
			</view>
		</view>
		<view class="box">
			<Section :title="$t('homePage.home.powerGenerationCapacity')">
				<view slot="right" style="flex: 1">
					<view class="top-right-box">
						<span class="time">{{$t('homePage.device.timeGranularity')}}:</span>
						<span @click="openTimeAction" class="value">{{sampleTime}}</span>
					</view>
				</view>
			</Section>
			<view class="chart-box">
				<zero-loading v-if="chartLoading" position="absolute"></zero-loading>
				<charts v-else id="pcsChart" :options="curve_option"></charts>
			</view>
		</view>
		<historyModal :is-show.sync="histroyShow" :title="chartTitle" :params="hisParams" />
		<u-action-sheet :list="actionSheetList" v-model="timeShow" @click="actionSheetCallback" @close="closeTimeAction"
			:mask-close-able="false"></u-action-sheet>
	</view>
</template>
<script>
	import topoCanvas from '@/components/new-canvas/index.vue'
	import historyModal from '@/components/history-modal/index.vue'
	import Section from '@/components/section/index.vue'
	import charts from "@/components/charts/index";
	export default {
		components: {
			historyModal,
			Section,
			charts,
			topoCanvas
		},
		data() {
			return {
				
				curve_option: {},
				panelData: {},
				histroyShow: false,
				chartTitle: null,
				chartLoading: false,
				stationLoading: false,
				hisParams: {},
				timeShow: false,
				time: "1",
				stationId: null,
				srcId: null,
				hnStationId: [417, 398, 416, 415, 405, 485],
				actionSheetList: Object.values(this.$t('homePage.home.timesArr')),
				sampleTime:this.$t('homePage.home.timesArr')[0].text,
				canvasData: [],
				textCanvasData: [
					{
						type: "text",
						coord: [
							[144, 240]
						],
						font: [{
								text:this.$t('homePage.home.activePowerpcs'),
								size: 12,
								color: "#999",
							},
							{
								text: "",
								size: 12,
								color: "#000",
								offsetX: 0
							},
						],
					},
					{
						type: "text",
						coord: [
							[144, 260]
						],
						font: [{
								text:this.$t('homePage.home.highV') + ':',
								size: 12,
								color: "#999",
							},
							{
								text: "",
								size: 12,
								color: "#000",
								offsetX: 0
							},
						],
					},
					//2
					{
						type: "text",
						coord: [
							[144, 280]
						],
						font: [{
								text:this.$t('homePage.home.lowV') + ':',
								size: 12,
								color: "#999",
							},
							{
								text: "",
								size: 12,
								color: "#000",
								offsetX: 0
							},
						],
					},
					{
						type: "text",
						coord: [
							[144, 300]
						],
						font: [{
								text:this.$t('homePage.home.lowI') + ':',
								size: 12,
								color: "#999",
							},
							{
								text: "",
								size: 12,
								color: "#000",
								offsetX: 0
							},
						],
					},
					//5
					{
						type: "text",
						coord: [
							[3, 120]
						],
						font: [{
								text: this.$t('homePage.device.gridMode') + ':',
								size: 14,
								color: "#999999",
								width: 50,
							},
							{
								text: "",
								size: 14,
								color: "#000",
								left: 80
							},
						],
					},
					//6
					{
						type: "text",
						coord: [
							[3, 140]
						],
						font: [{
								text: this.$t('homePage.device.runState') + ':',
								size: 14,
								color: "#999999",
								width: 50,
							},
							{
								text: "",
								size: 14,
								color: "#000",
								offsetX: 0
							},
						],
					}
				],
				imageCanvasData: [
					{
						//AC/DC
						type: "image",
						url: "/static/topology/DCDC.png",
						coord: [
							[155, 80],
							[30, 30],
						],
					},
					{
						//电池
						type: "image",
						url: "/static/topology/pv.png",
						coord: [
							[144, 180],
							[50, 50],
						],
					},
				],
				lineCanvasData: [{
						type: "line",
						coord: [
							[60, 30],
							[280, 30],
						],
						color: "#19875c",
						width: 2,
					},
					{
						type: "line",
						coord: [
							[170, 30],
							[170, 180],
						],
						color: "#19875c",
						width: 2,
					},
				]
			}
		},
		computed: {
			currentStation() {
				return this.vuex_currentStation;
			},
		},
		watch: {
			currentStation: {
				handler(val) {
					this.stationId = val.id;
				},
				deep: true,
				immediate: true,
			},

		},

		methods: {
			getData(srcId) {
				this.srcId = srcId
				this.getChart()
				this.getStatus()
			},
			getChart() {
				const self = this
				self.chartLoading = true;
				return new Promise((resolve, reject) => {
					self.$u.api.deviceList
						.GetPvCurve({
							stationId: this.stationId,
							sampleTime: this.time,
							srcId: this.srcId,
						})
						.then((res) => {
							self.chartLoading = false;
							self.initChargeChart(res.data);
							// this.getStatus();
							resolve(res);
						})
						.catch((err) => {
							reject("错误");
						})
						.finally(() => {
							self.chartLoading = false;
						});
				});

			},
			initChargeChart(val) {
				const gonglv = [];
				// const soc = [];
				const xAxis = [];
				val.forEach((v) => {
					xAxis.push(v.data);
					gonglv.push(v.inCoreDataCurve);
					// soc.push(v.inCoreDataCurve);
				});
				this.curve_option = {
					color: ["#BFE49F"],
					animationDuration: 500,
					animationEasing: "cubicInOut",
					tooltip: {
						trigger: "axis",
						axisPointer: {},
						confine: true,
						textStyle: {
							textShadowBlur: 10, // 重点
							textShadowColor: 'transparent', // 重点
						},
						position: function(point, params, dom, rect, size) {
							// 鼠标坐标和提示框位置的参考坐标系是：以外层div的左上角那一点为原点，x轴向右，y轴向下
							// 提示框位置
							var x = 0; // x坐标位置
							var y = 0; // y坐标位置

							// 当前鼠标位置
							var pointX = point[0];
							var pointY = point[1];

							// 外层div大小
							// var viewWidth = size.viewSize[0];
							// var viewHeight = size.viewSize[1];

							// 提示框大小
							var boxWidth = size.contentSize[0];
							var boxHeight = size.contentSize[1];

							// boxWidth > pointX 说明鼠标左边放不下提示框
							if (boxWidth > pointX) {
								x = 5; // 自己定个x坐标值，以防出屏
								y -= 15; // 防止点被覆盖住，可根据情况自行调节
							} else {
								// 左边放的下
								x = pointX - boxWidth - 15;
							}

							// boxHeight > pointY 说明鼠标上边放不下提示框
							if (boxHeight + 20 > pointY) {
								y = pointY + 15;
							} else if (boxHeight > pointY) {
								y = 5;
							} else {
								// 上边放得下
								y += pointY - boxHeight;
							}
							return [x, y];
						},
					},
					grid: {
						top: "15%",
						left: "5%",
						right: "3%",
						bottom: "10%",
						containLabel: true,
					},
					xAxis: {
						type: "category",
						data: xAxis,
						splitLine: {
							show: false,
						},
						axisLabel: {
							show: true,
							color: "#A3A3A3",
							formatter: function(params) {
								let newParamsName = "";
								const paramsNameNumber = params.length; // 文字总长度
								const provideNumber = 11; //一行显示几个字
								const rowNumber = Math.ceil(paramsNameNumber / provideNumber);
								if (paramsNameNumber > provideNumber) {
									for (let p = 0; p < rowNumber; p++) {
										const start = p * provideNumber;
										const end = start + provideNumber;
										const tempStr =
											p === rowNumber - 1 ?
											params.substring(start, paramsNameNumber) :
											params.substring(start, end) + "\n";
										newParamsName += tempStr;
									}
								} else {
									newParamsName = params;
								}
								return newParamsName;
							},
						},
					},
					yAxis: [{
							type: "value",
							name:  this.$t('homePage.home.powerGenerationCapacity')  + "(kW)",
							axisLabel: {
								color: "#A3A3A3",
							},
							nameTextStyle: {
								color: "#A3A3A3",
							},
							min: function(value) {
								return Math.floor(
									(Math.abs(value.min) < value.max ?
										-value.max * 1.05 :
										value.min * 1.05
									).toFixed(2)
								);
							},
							max: function(value) {
								return Math.ceil(
									(Math.abs(value.min) < value.max ?
										value.max * 1.05 :
										-value.min * 1.05
									).toFixed(2)
								);
							},
							nameTextStyle: {
								fontSize: 12,
								padding: [0, 0, 0, 30],
							},
						}
					],
					dataZoom: {
						type: "inside",
					},
					series: [{
							name: this.$t('homePage.home.powerGenerationCapacity'),
							type: "line",
							smooth: true,
							symbol: "none",
							areaStyle: {
								opacity: 0,
							},
							data: gonglv,
						}
					],
				};
			},
			openTimeAction() {
				this.timeShow = true;
			},
			getStatus() {
				this.stationLoading = true
				const self = this;
				this.$u.api.deviceList
					.GetNewValue({
						stationId: this.stationId,
						srcId: this.srcId,
						colList: ["lowV", "highV", "lowI",
						"pvActivePower","runState","remoteInPlace",
						"onGrid","offGrid","stateCharging",
						"stateDischarging","deviceStateStand","deviceStateFault",
						"deviceStateFull","deviceStateEmpty","dcBreaker",
						"eStop","soc","grid",
						"outputPower",
							// "reactivePowerPCS",
							// ，,
							// "volA",
							// "volB",
							// "volC",
							// "currentA",
							// "currentB",
							// "currentC",
							// "dcPower",
							// "dcInputVol",
							// "dcCurrent",
						],
					})
					.then((res) => {
						const battery = self.updateBattery(res.data.soc?.value ? res.data.soc.value : 0);
						this.panelData = {
							lowV: res.data.lowV?.value ? res.data.lowV?.value : 0,
							highV: res.data.highV?.value ? res.data.highV?.value : 0,
							lowI: res.data.lowI?.value ? res.data.lowI?.value : 0,
							pvActivePower: res.data.pvActivePower?.value ? res.data.pvActivePower?.value : 0
						};
						this.textCanvasData[0].font[1].text = res.data.pvActivePower?.value ? res.data.pvActivePower.value + " kW" : 0 + " kW";
						this.textCanvasData[1].font[1].text = res.data.highV?.value ? res.data.highV.value + " V" : 0 + " V";
						this.textCanvasData[2].font[1].text = res.data.lowV?.value ? res.data.lowV.value + " V" : 0 + " V";
						this.textCanvasData[3].font[1].text = res.data.lowI?.value ? res.data.lowI.value + " A" : 0 + " A";
						this.textCanvasData[4].font[1].text = res.data.onGrid?.value ? this.$t('homePage.device.grid') : this.$t('homePage.device.offGrid');
						if(res.data.pvActivePower?.value){
							this.textCanvasData[5].font[1].text = this.getFlowDirection(res.data.pvActivePower?.value, res
								.data.runState?.value)
						}
						this.canvasData = [...this.textCanvasData, ...this.imageCanvasData, ...this.lineCanvasData]
					})
					.finally((res) => {
						this.stationLoading = false;
					});
			},
			updateBattery(value) {
				//电池电量 value 为0~100
				const batteryHeight = 0.35 * value;
				const battery = {
					type: "rect",
					background: "#19875c",
					coord: [
						[156, 285 - batteryHeight],
						[25.5, batteryHeight],
					],
				};
				return battery;
			},
			getRunState(value, value2) {
				if (value) {
					return this.$t('homePage.device.standby');
				} else if (value2) {
					return this.$t('homePage.device.fault');
				} else {
					return "";
				}
			},
			// 设备工作状态
			workStatus(val) {
				if (val === 0) {
					return this.$t('homePage.device.shutdown')
				} else if (val === 1) {
					return this.$t('homePage.device.run')
				} else if (val === 2) {
					return this.$t('homePage.device.standby')
				} else {
					return ''
				}
			},
			// 充放电状态
			getFlowDirection(val, flowDirection) {
				if (flowDirection === 2) {
					if (+val > +1) {
						return this.$t('homePage.device.discharge')
					}
					if (+val < -1) {
						return this.$t('homePage.device.charge')
					}
					if (val < 1 || +val.abs < 1 || !val) {
						return this.$t('homePage.device.standing')
					}
				} else {
					if (+val > +1) {
						return this.$t('homePage.device.charge')
					}
					if (+val < -1) {
						return this.$t('homePage.device.discharge')
					}
					if (val < 1 || +val.abs < 1 || !val) {
						return this.$t('homePage.device.standing')
					}
				}

			},
			// 电池信息
			updateBattery(value) {
				//电池电量 value 为0~100
				const batteryHeight = 0.35 * value;
				const battery = {
					type: "rect",
					background: "#19875c",
					coord: [
						[156, 285 - batteryHeight],
						[25.5, batteryHeight],
					],
				};

				return battery;
			},
			// 历史曲线
			showHistory(name, modelCol, modelType, unit) {
				this.hisParams = {
					modelCol: modelCol,
					modelType: modelType,
					unit: unit
				}
				this.chartTitle = name
				this.histroyShow = true
			},
			actionSheetCallback(index) {
				this.sampleTime = this.actionSheetList[index].text;
				this.time = this.actionSheetList[index].value;
				this.getChart()
			},
			closeTimeAction() {
				this.timeShow = false;
			},
		}
	}
</script>
<style lang="scss" scoped>
	.pcs-warp {
		background-color: #f5f5f5;
		height: 100%;

		.box {
			background: #ffffff;
			border-radius: 16rpx;
			padding: 20rpx;
			width: 100%;
			border: 16rpx;
			box-shadow: 0px 4rpx 16rpx rgba(0, 0, 0, 0.08);
			margin-bottom: 20rpx;
			position: relative;

			.topology-box {
				width: 100%;
				height: 640rpx;
				position: relative;


			}

			.top-right-box {
				display: flex;
				flex-direction: row;
				align-items: center;
				flex: 1;

				justify-content: flex-end;

				.time {
					padding-right: 10rpx;
					display: inline-block;
					height: 40rpx;
				}

				.value {
					background-color: #f5f5f5;
					border-radius: 8rpx;
					padding: 10rpx 20rpx 10rpx 20rpx;
					height: 40rpx;
				}

				.top-right-item {
					padding: 5rpx 10rpx;
					border: 1rpx solid #4c9ee6;
					font-size: 24rpx;
					color: #4c9ee6;
					cursor: pointer;
					margin-right: 10rpx;
					border-radius: 8rpx;

					&.active {
						background: #4c9ee6;
						color: #ffffff;
					}
				}
			}

			.chart-box {
				width: 650rpx;
				height: 460rpx;
				margin-top: 20rpx;
				position: relative;
			}

			.group-box {
				width: 100%;
				display: flex;
				flex-wrap: wrap;
				position: relative;

				.group-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					width: 199rpx;

					justify-content: center;
					background: #d7e9e548;
					border-radius: 10rpx;
					margin: 10rpx 10rpx;
					position: relative;
					padding: 10rpx 0;

					.history-icon {
						position: absolute;
						right: 0rpx;
						top: 0rpx;
	
					}

					image {
						width: 40rpx;
						height: 40rpx;
					}

					.item-con {
						display: flex;
						flex-direction: column;
						align-items: center;
						// margin-left: 15rpx;
						width: 100%;

						.item-title {
							width: 100%;
							font-size: 24rpx;
							color: #2a2a2a;
							margin-top: 10rpx;
							text-align: center;
						}

						.item-num {
							font-size: 36rpx;
							color: #282828;
							font-weight: bold;
							max-width: 90%;
							text-align: center;
						}

						.item-unit {
							color: #cccccc;
							font-size: 16rpx;
							padding-left: 10rpx;
						}
					}
				}
			}

		}
	}
</style>