<template>
	<view class="realTime">
		<view class="" v-if="facilityList && facilityList.length > 0">
			<view class="realTime-content">
				<view class="realTime-content-btn">
					<view class="">
						<!-- <u-button size="mini" type="primary" :custom-style="customStyle" :ripple="true"
							@click="oneOpenModalFlag = true">一键合闸</u-button>
						<u-button size="mini" type="primary" :custom-style="customStyle" :ripple="true"
							@click="oneCloseModalFlag = true">一键分闸</u-button> -->
						<u-button size="mini" type="primary" :custom-style="customStyle" :ripple="true" style="margin-right: 20rpx;"
							@click="showPwdModal({ method:sendOneSwitchFn,param:1 })">一键合闸</u-button>
						<u-button size="mini" type="primary" :custom-style="customStyle" :ripple="true" style="margin-right: 20rpx;"
							@click="showPwdModal({ method:sendOneSwitchFn,param:0 })">一键分闸</u-button>
					</view>
					<u-button size="mini" type="primary" :custom-style="customStyle" :ripple="true"
						@click="goParameterSetupFn">设备参数调整</u-button>
				</view>
				<scroll-view class="scroll-box" scroll-y="true">
					<view class="facility-list">
						<view class="facility-box"
							:class="[item.deviceState=='ONLINE'?'status-online':'status-offline',currentIndex==index?'active':'']"
							v-for="(item,index) in facilityList" :key='index'
							:style="{margin:(index+1) % 2 === 0?'':'0 20rpx 20rpx 0'}" @click="pickFacilityBoxFn(index)">
							<view class="device-id">
								ID:{{item.deviceKey}}
							</view>
							<view class="device-info">
								<view class="facility-box-text">
									<view class="facility-box-text-title pb10">
										{{item.deviceName}}
									</view>
									<view class="facility-box-text-value-box"><span
											class="facility-box-text-value">{{findDevice(item.realTimeData.params, 'power_limit') || "0"}}</span>瓦
									</view>
								</view>
								<tuiIcon class="facility-box-logo" :name="getDeviceTypeInfoFn(item)" size="57"></tuiIcon>
								<tuiIcon class="facility-box-logo-two" :name="getDeviceTypeInfoFn(item)" size="57"></tuiIcon>
								<!-- <view class="home-menu-item-bg-two" :class="['diconfont',item.icon]" :style="{color:item.twoColor}"></view> -->
							</view>
							<!-- {{item.realTimeData.params.switch}} -->
							<!-- <u-tag v-if="currentIndex==index" class="facility-box-state" :type="item.realTimeData?item.realTimeData.params.switch==1?'success':'error':'info'" :text="item.realTimeData?item.realTimeData.params.switch==0?'已断':'已通':'未知'" mode="dark" size="mini" /> -->
							<!-- <u-tag v-if="currentIndex==index" class="facility-box-state" :type="item.realTimeData.params.switch!==null?item.realTimeData.params.switch==1?'success':'error':'info'" :text="item.realTimeData.params.switch!==null?item.realTimeData.params.switch==0?'已断':'已通':'未知'" mode="dark" size="mini" />
							<u-icon v-if="currentIndex==index" size="36" class="facility-box-pick-icon" name="checkmark-circle-fill" :color="item.realTimeData.params.switch!==null?item.realTimeData.params.switch==1?'#60C13D':'#F6210A':'#999'"></u-icon> -->
							<u-tag v-if="currentIndex==index" class="facility-box-state"
								:type="item.deviceState=='ONLINE'?'success':'error'" :text="item.deviceState=='ONLINE'?'在线':'离线'"
								mode="dark" size="mini" />
							<u-icon v-if="currentIndex==index" size="36" class="facility-box-pick-icon" name="checkmark-circle-fill"
								:color="item.deviceState=='ONLINE'?'#60C13D':'#F6210A'"></u-icon>
						</view>
					</view>
				</scroll-view>

			</view>
			<view class="bottom-info"
				:class="currentFacilityData.deviceState!=='ONLINE'?'bottom-info-offline':''">
				<!-- <view class="bottom-info" style="background-color:#999"> -->
				<view class="bottom-info-header">
					<view class="" style="display: flex;" :style="{fontSize:currentFacilityData.deviceName.length>20?'26rpx':'34rpx'}">
						{{currentFacilityData.deviceName}}：{{currentFacilityData.deviceState=='ONLINE'?'在线':'离线'}}
					</view>
					<u-button v-if="currentFacilityData.deviceType == 'DOOR_SENSOR'"
						:customStyle="currentFacilityData.realTimeData.params.switch==1?customStyleGreen:customStyleRed"
						:type="currentFacilityData.realTimeData.params.switch==1?'success':'error'" :ripple="true"
						@click="showPwdModal({method: sendSwitchTopicFn,param:2 })">
						<span class="diconfont" style="margin-right: 6rpx;"
							:class="currentFacilityData.realTimeData.params.switch==1?'dicon-icon_fenzha':'dicon-icon_hezha'"></span>
						开锁
					</u-button>
					<u-button v-else-if="judgeBtnShow()"
						:customStyle="currentFacilityData.realTimeData.params.switch==1?customStyleRed:customStyleGreen"
						:type="currentFacilityData.realTimeData.params.switch==1?'error':'success'" :ripple="true"
						@click="showPwdModal({method: sendSwitchTopicFn})">
						<span class="diconfont" style="margin-right: 6rpx;"
							:class="currentFacilityData.realTimeData.params.switch==1?'dicon-icon_fenzha':'dicon-icon_hezha'"></span>
						{{currentFacilityData && currentFacilityData.realTimeData.params.switch==0?"合闸":"分闸"}}
					</u-button>

				</view>
				<!-- <view class="bottom-info-content" v-if="currentFacilityData.realTimeData.params">
					<view class="bottom-info-row" v-for="(value,key) in currentFacilityData.realTimeData.params" :key="key">
						<view class="label">{{deviceDataKeyObj[key].name}}</view>
						<view class="value" v-if="deviceDataKeyObj[key].type =='enum'">
							{{deviceDataKeyObj[key].enumData[value]}}
						</view>
						<view class="value" v-else>{{value}}{{deviceDataKeyObj[key].unit}}</view>
					</view>
				</view> -->

				<view v-if="currentFacilityData.prodKey=='UX0002' || currentFacilityData.prodKey=='UX0001'">
					<template v-if="currentFacilityData.realTimeData.params&&currentFacilityData.realTimeData.devId!==null">
						<view class="bottom-info-content">
							<view class="bottom-info-row" v-for="(item, index) in paramList" :key="index" v-if="currentFacilityData.realTimeData.params[item.key] !== null &&
								currentFacilityData.realTimeData.params[item.key] !== undefined &&
								currentFacilityData.realTimeData.params[item.key] !== ''">
								<view class="label">{{item.name}}</view>
								<view class="value" v-if="item.type =='enum'">
									{{item.enumData[currentFacilityData.realTimeData.params[item.key]]}}
								</view>
								<view class="value" v-else>{{currentFacilityData.realTimeData.params[item.key]}}{{item.unit}}</view>
							</view>
						</view>
					</template>
				</view>
				<view v-else>
					<template v-if="currentFacilityData.realTimeData.params&&currentFacilityData.realTimeData.devId!==null">
						<view class="bottom-info-content">
							<view class="bottom-info-row" v-for="(item, index) in paramList" :key="index" v-if="currentFacilityData.realTimeData.params[item.key] !== null &&
								currentFacilityData.realTimeData.params[item.funKey] !== undefined &&
								currentFacilityData.realTimeData.params[item.funKey] !== ''">
								<text class="label">{{item.funName}}</text>
								<text class="value" v-if="item.dataFormatType =='ENUM'">
									{{item.dataFormatObj[currentFacilityData.realTimeData.params[item.funKey]]||currentFacilityData.realTimeData.params[item.funKey]}}
								</text>
								<text class="value" v-else-if="item.dataFormatType =='TIME'">
									{{$u.timeFormat(currentFacilityData.realTimeData.params[item.funKey], 'yyyy-mm-dd hh:MM:ss')||currentFacilityData.realTimeData.params[item.funKey]}}
								</text>
								<text class="value"
									v-else>{{currentFacilityData.realTimeData.params[item.funKey]}}{{item.unitName || ''}}</text>
							</view>
						</view>
					</template>
				</view>
				<!-- <u-button type="primary" @click="moreInfoPopup = true">查看更多</u-button> -->
			</view>
		</view>
		<u-empty v-else-if="facilityList!=null && facilityList.length == 0" text="没有查询到设备">
			<u-button slot="bottom" type="primary" size="medium" throttle-time="1500" @click="getDeviceInfoListFn">
				刷新试试
			</u-button>
		</u-empty>

		<!-- <u-modal v-model="oneCloseModalFlag" title='温馨提示' :show-cancel-button="true" @confirm="showPwdModal({
				method: sendOneSwitchFn,
				param: 0,
			})" content="您确定一键关闭吗"></u-modal>
		<u-modal v-model="oneOpenModalFlag" title='温馨提示' :show-cancel-button="true" @confirm="showPwdModal({
				method: sendOneSwitchFn,
				param: 1,
			})" content="您确定一键开启吗"></u-modal>
		<u-modal v-model="bottomBtnModalFlag" v-if="currentFacilityData" title='温馨提示' :show-cancel-button="true"
			@confirm="showPwdModal({method: sendSwitchTopicFn})"
			:content="currentFacilityData.realTimeData.params.switch==0?'您确定开启吗':'您确定关闭吗'"></u-modal> -->

		<u-modal v-model="pwdModalFlag" :title='pwdTitle' :show-cancel-button="true"
			@confirm="$throttle(checkOk, currentMethod)">
			<view class="slot-content">
				<u-input v-model="password" :focus="true" border type="password"></u-input>
			</view>
		</u-modal>
		<!-- <u-popup v-model="moreInfoPopup" mode="center" width="80%" border-radius="20" height="80%">
			<view class="moreInfo-ctn">
				<view class="mordeInfo-row" v-for="(item,index) in 3" :key="index">
					<view class="mordeInfo-row-label">电压</view>
					<view class="mordeInfo-row-value">5V</view>
				</view>
			</view>
		</u-popup> -->
	</view>
</template>
<style lang="scss" scoped>
	.moreInfo-ctn {
		padding: 30rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;

		.mordeInfo-row {
			width: 49%;
			display: flex;
			justify-content: space-between;
			margin-bottom: 10rpx;
		}
	}
</style>
<script>
	let that;
	import deviceDataKey from "./deviceDataKey.js"
	import wsRequest from '@/utils/websocket.js'

	export default {
		data() {
			return {
				optionsObj: null,
				// mqttClient:null,
				wsSocket: null,
				sendTopic: "",
				timer: null,

				moreInfoPopup: false,
				deviceDataKeyObj: deviceDataKey,
				deviceId: "",
				prodKey: "",
				deviceKey: "",

				currentIndex: 0,
				currentFacilityData: null,
				oneCloseModalFlag: false,
				oneOpenModalFlag: false,
				bottomBtnModalFlag: false,
				facilityList: null,
				customStyle: {
					padding: '12rpx 24rpx',
					fontSize: '28rpx',
					background: 'linear-gradient(0deg, #45AAFF 0%, #2568FF 100%)',
					height: '65rpx',
					borderRadius: '20rpx',
				},
				customStyleGreen: {
					padding: '12rpx 24rpx',
					fontSize: '28rpx',
					background: 'linear-gradient(0deg, #1BC657 0%, #1C875D 100%)',
					borderRadius: '20rpx',
					height: '65rpx'
				},
				customStyleRed: {
					padding: '12rpx 24rpx',
					fontSize: '28rpx',
					background: 'linear-gradient(0deg, #FF7928 0%, #FF331F 100%)',
					borderRadius: '20rpx',
					height: '65rpx'
				},
				pwdModalFlag: false,
				password: '',
				currentMethod: {},
				gatewayWsSocket: '',
				pwdTitle: '',
				paramList: [],
			}
		},
		onLoad(e) {

			// 未连接:灰色 (未知)
			// 已连接：{
			// 已断0:绿色,
			// 已通1:红色
			// }
			console.log(e, "ee");
			that = this;
			this.deviceId = e.deviceId;
			this.prodKey = e.prodKey;
			this.deviceKey = e.deviceKey;
			this.sendTopic = `/sys/down/mlink/${this.prodKey}/${this.deviceKey}/`
			// this.getDeviceInfoListFn();
			// this.getDeviceConnectDataFn();
			this.getDeviceInfoListFn();
			if (this.timer) {
				clearInterval(this.timer);
				this.timer = setInterval(() => {
					this.setTimerSendMsgPublish();
				}, 100000)
			} else {
				this.timer = setInterval(() => {
					this.setTimerSendMsgPublish();
				}, 100000)
			}
		},
		onShow() {
			// console.log('timer: ', this.timer)
			// this.getDeviceInfoListFn();
			// if (this.timer) {
			// 	clearInterval(this.timer);
			// 	this.timer = setInterval(() => {
			// 		this.setTimerSendMsgPublish();
			// 	}, 100000)
			// } else {
			// 	this.timer = setInterval(() => {
			// 		this.setTimerSendMsgPublish();
			// 	}, 100000)
			// }
		},
		methods: {
			judgeBtnShow(){
				if(this.currentFacilityData.realTimeData.params.switch==null){
					return false;
				}else{
					return true;
				}
			},
			
			getGuid() {
				return "xxxxxxx_xxxxx_4xxx_yxxx_xxxxxxxxxxxx".replace(
					/[xy]/g,
					function(c) {
						var r = (Math.random() * 16) | 0,
							v = c == "x" ? r : (r & 0x3) | 0x8;
						return v.toString(16);
					}
				);
			},
			switchReturn(item, type) {
				let status = -1;
				if (item?.realTimeData) {
					if (item?.realTimeData?.params.switch == 0) {
						status = 0;
					} else {
						status = 1;
					}
				}
				switch (type) {
					case 'border':
						if (status == -1) {
							return '4rpx solid #60C13D';
						} else if (status == 0) {
							return '4rpx solid #F6210A';
						} else if (status == 1) {
							return '4rpx solid #999';
						}

						break;
					case n > 10:
						console.log(n);
						console.log(">10");
						break;
					default:
						console.log("都不是");
						break;
				}
			},
			checkOk(obj) {
				let {
					method,
					param
				} = obj;
				console.log(method, param);
				(param === undefined || param === null || param === '') ? method(): method(param);
			},
			showPwdModal(obj) {
				this.pwdModalFlag = true;
				this.currentMethod = obj;
				this.password = '';
				if (obj.param != undefined) {
					this.pwdTitle = obj.param == 1 ? '（一键合闸）请输入登录密码' : obj.param == 2 ? '（开锁）请输入登录密码' : '（一键分闸）请输入登录密码';
				} else {
					this.pwdTitle = this.currentFacilityData?.realTimeData?.params?.switch ? '（分闸）请输入登录密码' : '（合闸）请输入登录密码';
				}
			},
			sendSwitchTopicFn() {
				let sendMsgStr = {
					data: {
						cmd: "set_switch",
						params: {
							switch: that.currentFacilityData.realTimeData.params.switch == 0 ? 1 : 0,
							devId: that.currentFacilityData.deviceKey,
							pk: that.currentFacilityData.prodKey
						}
					},
					deviceId: that.currentFacilityData.deviceId,
					verifyKey: that.password
				};
				// 锁直接全部发开
				if(that.currentFacilityData.deviceType == 'DOOR_SENSOR'){
					sendMsgStr.data.params.switch = 0;
				}
				that.sendMsg(sendMsgStr);
				// let sendMsgStr = JSON.stringify({
				// 	action: "cloudSend",
				// 	msgId: new Date().getTime(),
				// 	pk: that.prodKey,
				// 	devId:that.deviceKey,
				// 	data: {
				// 		cmd: "set_switch",
				// 		params: {
				// 			switch: that.currentFacilityData.realTimeData.params.switch==0?1:0,
				// 			devId: that.currentFacilityData.deviceKey,
				// 			pk: that.currentFacilityData.prodKey
				// 		}
				// 	}
				// });
				// that.mqttClient.publish(that.sendTopic,sendMsgStr, error => {
				// 	console.log(error || '控制开关消息发布成功');
				// });
			},
			sendOneSwitchFn(type) {
				// let sendMsgStr = {
				// 	data: {
				// 		cmd: "set_all_switch",
				// 		params: {
				// 			switch: type
				// 		}
				// 	},
				// 	deviceId: that.deviceId,
				// 	verifyKey: that.password,
				// };
				// that.sendMsg(sendMsgStr);
				console.log("that.facilityList", that.facilityList)
				// that.facilityList.forEach((item,index)=>{
				// 	let sendMsgStr = {
				// 		data: {
				// 			cmd: "set_switch",
				// 			params: {
				// 				switch: type,
				// 				devId: item.deviceKey,
				// 				pk: item.prodKey
				// 			}
				// 		},
				// 		deviceId: item.deviceId,
				// 		verifyKey: that.password,
				// 	};
				// 	that.sendMsg(sendMsgStr);
				// })
				// 一键开启关闭延迟500毫秒（过滤设备非开关设备）
				let deviceList = that.facilityList.filter(item=>item.deviceType=='MINIATURE_BREAKER');
				deviceList.reduce((prevPromise, item, index) => {
					return prevPromise.then(() => {
						let sendMsgStr = {
							data: {
								cmd: "set_switch",
								params: {
									switch: type,
									devId: item.deviceKey,
									pk: item.prodKey
								}
							},
							deviceId: item.deviceId,
							verifyKey: that.password,
						};
						that.sendMsg(sendMsgStr);

						// 返回一个新的Promise来控制下一个迭代的延迟执行
						return new Promise(resolve => setTimeout(resolve, 50));
					});
				}, Promise.resolve()); // 初始值为已解决的Promise



				// let sendMsgStr = JSON.stringify({
				// 	action: "cloudSend",
				// 	msgId: new Date().getTime(),
				// 	pk: that.prodKey,
				// 	devId:that.deviceKey,
				// 	data: {
				// 		cmd: "all_switch",
				// 		params: {
				// 			switch: type
				// 		}
				// 	}
				// });
				// console.log(sendMsgStr,"sendOneSwitchFn");
				// that.mqttClient.publish(that.sendTopic,sendMsgStr, error => {
				// 	console.log(error || '控制一键开关消息发布成功');
				// });
			},
			getDeviceConnectDataFn(deviceId) {
				this.$get("/app/common/connect", {
					connectAuthType: "PHYSICS",
					deviceId: deviceId
				}).then((res) => {
					if (res.code === 200) {
						this.optionsObj = res.data;
						// this.socketConnet();
						this.initWebSocket();
					}
				})
			},
			initWebSocket() {
				let {
					username,
					password,
					clientId
				} = this.optionsObj;
				if(this.wsSocket){
					this.wsSocket.is_open_socket = false;
					this.wsSocket.close()
				}
				this.wsSocket = new wsRequest(this.gatewayWsSocket, 2000);
				this.socketConnet();
			},
			socketConnet() {
				// let {
				// 	username,
				// 	password,
				// 	clientId
				// } = this.optionsObj;
				// let url = `${this.$config.wsUrl}/ws/dev/live/${clientId}/${username}/${password}`

				// this.wsSocket = new wsRequest(this.gatewayWsSocket, 5000);
				this.wsSocket.socketTask.onOpen((res) => {
					console.log('打开正常');
					clearTimeout(this.wsSocket.reconnectTimeOut);
					clearTimeout(this.wsSocket.heartbeatInterval);
					this.wsSocket.is_open_socket = true;
					this.setTimerSendMsgPublish();
					// this.timer = setInterval(()=>{
					// 	this.setTimerSendMsgPublish();
					// },100000)

					this.wsSocket.socketTask.onMessage((res) => {
						// console.log("socket数据"+ this.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),res)
						let result = JSON.parse(res.data);
						let deviceKey = '';
						if (result.deviceId || result.deviceKey) {
							deviceKey = result.deviceId ? result.deviceId : result.deviceKey ? result.deviceKey : ''
						}
						// 网关状态
						if (deviceKey == this.deviceKey) {
							if (result.deviceState !== undefined) {
								let device = this.facilityList.map((item, index) => {
									item.deviceState = result.deviceState;
									return item
								})
								this.$nextTick(() => {
									this.$set(this, 'facilityList', device)
								})
							}
						} else {
							// 设备状态
							let device = this.facilityList.map((item, index) => {
								if (deviceKey == item.deviceKey) {
									item.realTimeData.params = {
										...item.realTimeData.params,
										...result
									};
									if (result.deviceState !== undefined) {
										item.deviceState = result.deviceState;
									}
									// 适配美卡数据
									if (result.state !== undefined && result.switch == undefined) {
										item.realTimeData.params.switch = result.state;
										item.realTimeData.params.switch = result.switch_state;
										item.realTimeData.params.pw = result.tpower;
										item.realTimeData.params.ps = (result.thpower / 1000).toFixed(2);
										item.realTimeData.params.pf = result.spowerfactor;
									}
									if (result.switch_state !== undefined && result.switch == undefined) {
										item.realTimeData.params.switch = result.switch_state;
									}
									item.realTimeData.devId = item.deviceKey;
									if (item.cmd) {
										item.realTimeData.cmd = item.cmd;
									}
									if (item.pk) {
										item.realTimeData.pk = item.pk;
									}
								}
								return item;
							})
							this.$nextTick(() => {
								this.$set(this, 'facilityList', device)
							})
							// console.log("facilityList2", this.facilityList)
						}
						// result.data.forEach((item,index)=>{
						// item.params.sort();
						// this.facilityList.forEach((obj,i)=>{
						// 	if(result.devId == obj.deviceKey){
						// 		// console.log('接收消息', item);
						// 		// obj['realTimeData'] = item;
						// 		this.$set(obj, 'realTimeData', result);
						// 		// this.$set(this.facilityList[i],'realTimeData', result);
						// 	}
						// })
						// });
						this.currentFacilityData = this.facilityList[this.currentIndex];
					})
				})
				
			  this.wsSocket.socketTask.onError((err) => {
					console.error('WebSocket error:', err);
					// this.wsSocket.is_open_socket = false;
					this.initWebSocket();
				});
		
				this.wsSocket.socketTask.onClose((res) => {
					console.log('WebSocket closed:', res);
					this.wsSocket.is_open_socket = false;
					if(res.code != 4000){ //不是主动关闭就重连
						this.initWebSocket();
					}
				});

				// this.setTimerSendMsgPublish();
				// this.wsSocket.onOpen().then((res) => {
				// 	console.log('res', res)
				// }).catch(err => {
				// 	console.log(err, 'err')
				// })

			},
			// 定时发送指令
			setTimerSendMsgPublish() {
				// let idList = this.facilityList.map(item => {
				// 	return item.deviceId;
				// })
				// let idStr = idList.join();
				// let sendMsgStr = {
				// 	data: {
				// 		params: {
				// 			ltime: 15,
				// 			dtime: 1200,
				// 		},
				// 	},
				// 	// deviceId: idStr,
				// 	// deviceId: this.deviceId,
				// 	deviceId: this.facilityList[2].deviceId,
				// };
				// // this.sendMsg(sendMsgStr);
				// this.$post('/iot/dev/opt/livetime', sendMsgStr);
				
				
				
				
				this.facilityList.forEach((item,index) => {
					setTimeout(()=>{
						let sendMsgStr = {
							data: {
								params: {
									ltime: 15,
									dtime: 1200,
								},
							},
							deviceId: item.deviceId,
						};
						this.$post('/iot/dev/opt/livetime', sendMsgStr);
					},500)
				})
				
				// let sendMsgStr = JSON.stringify({
				// 	"devId":that.deviceKey,
				// 	"data":{
				// 		"params":{
				// 			"ltime":100,
				// 		},
				// 		"cmd":"set_live_time",
				// 	},
				// 	"msgId":new Date().getTime(),
				// 	"action":"cloudSend",
				// 	"pk":that.prodKey,
				// });
				// that.mqttClient.publish(that.sendTopic,sendMsgStr, error => {
				// 	console.log(error || '消息发布成功');
				// });
			},
			sendMsg(str) {
				this.$post('/iot/dev/opt/down', str);
			},
			getDeviceTypeInfoFn(item) {
				// 空调,照明,普插,线路
				if (item.deviceName.indexOf("空调") != -1) {
					return "kongdiao";
				} else if (item.deviceName.indexOf("照明") != -1) {
					return "zhihuiyongdian";
				} else if (item.deviceName.indexOf("普插") != -1) {
					return "chazuo";
				} else if (item.deviceName.indexOf("总路") != -1) {
					return "xinpian";
				} else if (item.deviceType == 'DOOR_SENSOR') {
					return "mima";
				} else {
					return "dianluquanding"
				}
			},
			async getParamList(item) {
				let res = await this.$get(
					`/iot/dev/prod/fun/list?deviceId=${item.deviceId}&cmdKey=param&deviceKey=${item.deviceKey}`)
				if (res.data.length > 0) {
					let list = res.data.filter(item => item.show == true);
					this.paramList = list.map(item => {
						if (item.dataFormat) {
							let dataFormat = JSON.parse(item.dataFormat);
							item.dataFormatType = dataFormat.type;
							if (dataFormat.list && dataFormat.type == 'ENUM') {
								try {
									item.dataFormatObj = JSON.parse(dataFormat.list.replace(/\\/g, ''));
								} catch (e) {
									item.dataFormatObj = {};
								}
							}
						}

						return item;
					});
				} else {
					this.paramList = []
				}

			},
			getDeviceInfoListFn() {
				// let obj = {
				// 	deviceId:this.deviceId
				// }
				this.$get(`/app/device/children/${this.deviceId}`).then((res) => {
					console.log(res, "Res");
					if (res.data.length > 0) {
						// 初始化realTimeData
						let list = [];
						// 设备key列表
						let deviceKeyList = [this.deviceKey];
						res.data.forEach((item, index) => {
							deviceKeyList.push(item.deviceKey)
							let obj = item;
							obj.realTimeData = {
								"devId": null,
								"params": {
									"t4": null,
									"ps": null,
									"in": null,
									"pw": null,
									"freq": null,
									"i": null,
									"eq": null,
									"switch": null,
									"q": null,
									"s": null,
									"u": null,
									"pf": null,
									"t1": null,
									"t2": null,
									"t3": null,
									"timestamp": null
								},
								"cmd": null,
								"pk": null
							};
							list.push(obj)
						})
						let deviceKeyUrl = deviceKeyList.join(',');
						this.getParamList(list[0])
						this.gatewayWsSocket = `${this.$config.wsUrl}/ws/dev/projectDeviceLive/${this.getGuid()}/${deviceKeyUrl}`
						console.log("this.gatewayWsSocket", this.gatewayWsSocket)
						this.facilityList = list;
						console.log("facilityList", list)
						// this.facilityList = res.data;
						this.currentFacilityData = this.facilityList[this.currentIndex];
						console.log(this.facilityList)
						this.getDeviceConnectDataFn(this.currentFacilityData.deviceId);


					} else {
						this.facilityList = []
					}
				}).catch(() => {
					this.facilityList = []
				})
			},
			// 跳转参数设备调整
			goParameterSetupFn() {
				// let currentFacilityDataStr = JSON.stringify(this.currentFacilityData);
				// console.log(currentFacilityDataStr,"currentFacilityDataStr");
				uni.navigateTo({
					// url:`./parameterSetup?deciveInfo=${currentFacilityDataStr}`
					url: `./parameterSetup?deviceId=${this.currentFacilityData.deviceId}&deviceKey=${this.currentFacilityData.deviceKey}`
				})
			},
			// 选择设备
			pickFacilityBoxFn(index) {
				// this.wsSocket.close();
				this.currentIndex = index;
				this.currentFacilityData = this.facilityList[this.currentIndex];
				this.getParamList(this.facilityList[this.currentIndex])
				// this.getDeviceConnectDataFn(this.currentFacilityData.deviceId);
				console.log(this.currentFacilityData, "currentFacilityData");
			},
			findDevice(Obj, key) {
				if (!Obj) {
					return ''; // 或者返回一个默认值
				}
				if ('Psum' in Obj) {
					return Obj.Psum;
				} else if ('Pa' in Obj) {
					return Obj.Pa;
				}else{
					return ''
				}
			}
		},
		onUnload() {
			clearInterval(this.timer);
			this.wsSocket.close();
		}
	}
</script>

<style>
	page {
		height: 100%;
	}
</style>
<style lang='scss' scoped>
	.scroll-box {
		height: calc(100vh - var(--status-bar-height) - 48px - 500rpx);
		/* #ifdef APP-PLUS */
		height: calc(100vh - var(--status-bar-height) - 44px - 500rpx);
		/* #endif */
	}

	.realTime {
		font-family: Source Han Sans CN;
		width: 100%;
		height: 100%;
		background-color: #F9F9F9;

		:not(not) {
			box-sizing: border-box;
		}

		.realTime-content {
			/* padding: 40rpx 45rpx; */

			&-btn {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;
				padding: 40rpx 45rpx 0 45rpx;
			}
		}

		.facility-list {
			display: flex;
			flex-wrap: wrap;
			padding: 0 45rpx 0 45rpx;
			/* margin-bottom: 300rpx; */
		}

		.facility-box {
			border-radius: 20rpx;
			width: 320rpx;
			height: 200rpx;
			background-color: #fff;
			padding: 20rpx;
			position: relative;

			/* border: px solid transparent; */
			.device-id {
				font-weight: 400;
				font-size: 18rpx;
				color: #999999;
				padding: 0rpx 0 10rpx 0;
				white-space: nowrap;
				/* 确保文本在一行内显示 */
				overflow: hidden;
				/* 隐藏溢出的内容 */
				text-overflow: ellipsis;
				/* 使用省略号表示文本溢出 */
			}

			.device-info {
				display: flex;
				align-items: center;

				.facility-box-logo ::v-deep .tui-icon {
					position: absolute;
					right: 30rpx;
					bottom: 62rpx;
					color: transparent;
					background-image: linear-gradient(0deg, #999999, #D6D6D6);
					-webkit-background-clip: text;
					z-index: 99;
				}

				.facility-box-logo-two ::v-deep .tui-icon {
					position: absolute;
					right: 37rpx;
					bottom: 62rpx;
					z-index: 98;
					color: rgba(153, 153, 153, 0.1);
				}
			}



			&-text {
				display: flex;
				flex-direction: column;
				justify-content: center;

				&-title {
					font-weight: 500;
					font-size: 28rpx;
					color: #000000;
					width: 200rpx;
					white-space: nowrap;
					/* 确保文本在一行内显示 */
					overflow: hidden;
					/* 隐藏溢出的内容 */
					text-overflow: ellipsis;
					/* 使用省略号表示文本溢出 */
				}

				.facility-box-text-value-box {
					font-weight: 400;
					font-size: 18rpx;
					color: #000000;

					.facility-box-text-value {
						font-weight: bold;
						font-size: 30rpx;
						margin-right: 6rpx;
					}
				}
			}

			&-state {
				position: absolute;
				left: 16rpx;
				bottom: 6rpx;
			}

			&-pick-icon {
				position: absolute;
				right: 10rpx;
				bottom: 10rpx;
			}

			&.active {
				border: 1px solid #989898;
			}

			&.status-online {
				background: linear-gradient(0deg, #ADFFE1 0%, #FFFFFF 100%);

				/*  */
				&.active {
					border: 1px solid #19BE6B;
				}

				.device-info {
					display: flex;
					align-items: center;

					.facility-box-logo ::v-deep .tui-icon {
						position: absolute;
						right: 30rpx;
						bottom: 62rpx;
						color: transparent;
						background-image: linear-gradient(0deg, #00985D, #02E151);
						-webkit-background-clip: text;
						z-index: 99;
					}

					.facility-box-logo-two ::v-deep .tui-icon {
						position: absolute;
						right: 37rpx;
						bottom: 62rpx;
						z-index: 98;
						color: rgba(0, 152, 93, 0.1);
					}
				}
			}

			&.status-offline {
				background: linear-gradient(0deg, #FFADAD 0%, #FFFFFF 100%);

				/*  */
				&.active {
					border: 1px solid #ff3545;
				}

				.device-info {
					display: flex;
					align-items: center;

					.facility-box-logo ::v-deep .tui-icon {
						position: absolute;
						right: 30rpx;
						bottom: 62rpx;
						color: transparent;
						background-image: linear-gradient(0deg, #FF2C43, #FF8F52);
						-webkit-background-clip: text;
						z-index: 99;
					}

					.facility-box-logo-two ::v-deep .tui-icon {
						position: absolute;
						right: 37rpx;
						bottom: 62rpx;
						z-index: 98;
						color: rgba(255, 44, 67, 0.1);
					}
				}
			}
		}

		.facilityBoxAction {
			border: 2rpx solid #60C13D;
		}

		.bottom-info {
			position: fixed;
			left: 0;
			bottom: 0;
			width: 100%;
			border-radius: 60rpx 60rpx 0px 0px;
			background: linear-gradient(0deg, #DDDDDD 0%, #FFFFFF 100%);
			padding: 24rpx 30rpx 0 30rpx;
			color: #000;
			box-shadow: 0px 0px 18px 2px rgba(0, 0, 0, 0.2);

			&-header {
				font-weight: 500;
				font-size: 34rpx;
				border-bottom: 1px solid #e5e5e5;
				padding: 0 10rpx;
				padding-bottom: 20rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 64rpx;
			}

			&-content {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				padding: 12rpx 0;
				padding-bottom: 20rpx;
				height: 390rpx;
				overflow-y: auto;
				font-size: 24rpx;

				.bottom-info-row {
					width: 50%;
					display: flex;
					margin-bottom: 6rpx;

					.label {
						color: #666;
						font-size: 20rpx;
						margin-right: 20rpx;
						width: 120rpx;
						text-align: right;
					}
				}

			}
			&.bottom-info-offline{
				background: linear-gradient(0deg, #FF495D 0%, #FF9186 100%);
				color: #fff;
				/* .bottom-info-header{
					color: #fff;
				} */
				.bottom-info-row{
					.label {
						color: #fff;
					}
				}
			}
		}
	}

	.slot-content {
		padding: 30rpx;
	}
</style>