<template>
	<view class="iotControl">
		<view class="device-type">
			<view v-for="(item,index) in deviceType" :key="index" @click="deviceTypeFun(item)">
				<img :src="item.img">
				<view>{{item.hardwareName}}</view>
				<img :src="imagesUrl('commonality/icon_wdwg_gd.png')">
			</view>
		</view>
		<!-- 传感器监测 -->
		<view class="small-title" v-if="sensorData[0]">
			<view></view>
			<view>传感器监测</view>
		</view>
		<view class="sensor">
			<view class="sensor-min" v-for="(item,index) in sensorData" :key="index">
				<img class="sensor-l" :src="baseUrl+item.icon" />
				<view class="sensor-r" :class="item.type?'color-B':'color-A'">{{item.deviceName}}:
					{{item.deviceValue?item.deviceValue:''}}{{item.unit?item.unit:''}}
				</view>
			</view>
		</view>
		<!-- 智能控制 -->
		<view class="small-title" v-if="labHardwareVOList[0]">
			<view></view>
			<view>智能控制</view>
		</view>
		<view class="intelligent-control">
			<view v-for="(item,index) in labHardwareVOList" :key="index" v-if="item.hardwareTypeKey !='airConditioner'&&item.hardwareTypeKey !='evacuationLight'">
				<view class="for-button-p">{{item.hardwareName}}
					<text v-if="item.reservedThree">({{item.reservedThree}})</text>
				</view>
				<img v-if="item.operatingState" :src="imagesUrl('manage/icon_10.png')"
					@click="buttonClick('switch',item,'0')">
				<img v-if="!item.operatingState" :src="imagesUrl('manage/icon_11.png')"
					@click="buttonClick('switch',item,'1')">
				<!-- <view class="for-button-p" v-if="!item.online">离线</view> -->
			</view>
		</view>
		<!-- 智能终端 -->
		<view class="small-title" v-if="terminalData[0]">
			<view></view>
			<view>智能终端</view>
		</view>
		<view class="intelligent-control">
			<view v-for="(item,index) in terminalData" :key="index">
				<view class="for-button-p">{{item.deviceName}}</view>
				<view class="for-button-p" v-if="!item.online">离线</view>
				<view class="for-button-p" v-if="item.online" style="color:#0183FA;">在线</view>
			</view>
		</view>

	</view>
</template>

<script>
	import {
		itoOrVideoLimits
	} from '@/utils/index'
	import $mqtt from '@/utils/mqtt.min.js';
	import {
		iotAppSensorFindBySubId,
		iotAppHardwareFindByType,
		iotAppHardwareOperatingHardware,
		iotAppDeviceFindByType,
	} from '@/pages_manage/api/index.js'
	import {
		config
	} from '@/api/request/config.js'
	export default {
		name: "iotControl",
		props: {
			subjectData: {},
		},
		data() {
			return {
				baseUrl: config.base_url,
				//MQTT请求参数-传感器
				mtopic: "iot/device/sensor/sub/",
				//MQTT请求参数-智能控制
				mtopicOne: "iot/hardware/all/sub/",
				client: {},
				newData: {},
				subId: '',
				deviceType: [],
				sensorData: [],
				labHardwareVOList: [],
				terminalData: [{
					name: '智能管控一体机',
					pcType: 1,
				}],
				planSensorList: [],
			}
		},
		created() {
			this.planSensorList = uni.getStorageSync("planSensorList");
		},
		mounted() {
			this.$set(this, 'newData', this.subjectData);
			this.$set(this, 'subId', this.subjectData.subId);
			this.iotAppSensorFindBySubId();
			this.iotAppHardwareFindByType();
			this.iotAppDeviceFindByType();
			this.offMQTT('on');
		},
		methods: {
			//物联控制设备
			deviceTypeFun(item) {
				if (item.type == 'video') {
					if (!itoOrVideoLimits(this.newData.adminId)) {
						uni.showToast({
							title: '没有相关操作权限,请联系管理员',
							icon: "none",
							mask: true,
							duration: 2000
						});
						return
					}
					// #ifdef WEB
					this.$parent.$parent.goVideoPage();
					// #endif
					// #ifdef MP-WEIXIN
					this.$parent.goVideoPage();
					// #endif
				} else {
					if (!itoOrVideoLimits(this.newData.adminId)) {
						uni.showToast({
							title: '没有相关操作权限,请联系管理员',
							icon: "none",
							mask: true,
							duration: 2000
						});
						return
					}
					if (item.type == 'speech') {
						//语音广播弹窗开启
						// #ifdef WEB
						this.$parent.$parent.buttonClick('broadcastOpen', '');
						// #endif
						// #ifdef MP-WEIXIN
						this.$parent.buttonClick('broadcastOpen', '');
						// #endif
					} else if (item.type == 'conditioning') {
						//空调弹窗开启
						// #ifdef WEB
						this.$parent.$parent.buttonClick('conditioningOpen', item);
						// #endif
						// #ifdef MP-WEIXIN
						this.$parent.buttonClick('conditioningOpen', item);
						// #endif
					}
				}
			},
			buttonClick(type, row, status) {
				if (!itoOrVideoLimits(this.newData.adminId)) {
					uni.showToast({
						title: '没有相关操作权限,请联系管理员',
						icon: "none",
						mask: true,
						duration: 2000
					});
					return
				}
				let self = this;
				if (type == 'switch') {
					//开关
					let text = '';
					if (status == '0') {
						text = '关闭';
					} else if (status == '1') {
						text = '开启';
					}
					uni.showModal({
						content: '确认要' + text + '吗?',
						cancelColor: "#999",
						confirmColor: "#0183FA",
						success: function(res) {
							if (res.confirm) {
								self.mangerControl(row, status);
								setTimeout(function() {
									self.iotAppHardwareFindByType();
								}, 200)

								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}

			},
			//设备开关
			async mangerControl(item, status) {
				let obj = {
					hardwareNo: item.hardwareNo,
					command: status,
				};
				const {
					data
				} = await iotAppHardwareOperatingHardware(obj);
				if (data.code == 200) {
					uni.showToast({
						title: '操作成功',
						icon: "none",
						mask: true,
						duration: 2000
					});
				}
			},
			//查询传感器状态
			async iotAppSensorFindBySubId() {
				let self = this;
				const {
					data
				} = await iotAppSensorFindBySubId({
					subId: this.subId
				});
				if (data.code == 200) {
					data.data.forEach((item) => {
						let num = 0;
						if (self.planSensorList[0]) {
							self.planSensorList.forEach((minItem) => {
								if (item.deviceNo == minItem) {
									num++
								}
							})
						}

						item.type = num != 0;
					})
					this.$set(this, 'sensorData', data.data);
				}
			},
			//查询硬件设备
			async iotAppHardwareFindByType() {
				const {
					data
				} = await iotAppHardwareFindByType({
					subjectId: this.subId
				});
				if (data.code == 200) {
					let VOList = [];
					data.data.forEach((item) => {
						if (item.hardwareTypeKey == 'airConditioner') {
							if (item.reservedThree == 0) {
								item.switchType = 0;
							} else if (item.reservedThree == 2) {
								item.switchType = 1;
								item.functionType = 3;
							} else if (item.reservedThree.indexOf('-') != -1) {
								let list = item.reservedThree.split('-');
								item.switchType = 1;
								item.functionType = list[0] == 3 ? 1 : (list[0] == 4 ? 2 : '');
								item.orderType = list[1] ? list[1] : '';
							} else {
								item.switchType = '';
								item.functionType = '';
								item.orderType = '';
							}
						}else{
							VOList.push(item)
						}
					})
					this.$set(this, 'labHardwareVOList', VOList);
					let list = [{
							type: 'video',
							hardwareName: '视频监控',
							img: this.imagesUrl('manage/icon_xq_spjk.png'),
						},
						{
							type: 'speech',
							hardwareName: '语音广播',
							img: this.imagesUrl('commonality/icon_sskz_xz.png'),
						},
					];
					for (let i = 0; i < data.data.length; i++) {
						if (data.data[i].hardwareTypeKey == 'airConditioner') {
							data.data[i].type = 'conditioning';
							data.data[i].img = this.imagesUrl('manage/icon_xq_kt.png');
							list.push(data.data[i])
						}
					}
					this.$set(this, 'deviceType', list);
				}
			},
			//查询物联设备
			async iotAppDeviceFindByType() {
				const {
					data
				} = await iotAppDeviceFindByType({
					subjectId: this.subId,
					typeKeyList: ['aio']
				});
				if (data.code == 200) {
					this.$set(this, 'terminalData', data.data);
				}
			},
			//MQTT订阅
			sensorMQTT() {
				let self = this;
				this.client = $mqtt.connect(
				// #ifdef WEB
				'wss://' + uni.getStorageSync('mqttUrl')
				// #endif
				// #ifdef MP-WEIXIN
				'wxs://' + uni.getStorageSync('mqttUrl')
				// #endif
				, {
					username: uni.getStorageSync('mqttUser'),
					password: uni.getStorageSync('mqttPassword')
				});
				this.client.on("connect", e => {
					this.client.subscribe(this.mtopic + self.subId, (err) => {
						if (!err) {
							console.log("传感器订阅成功:" + this.mtopic + self.subId);
						} else {
							// console.log("连接错误:" + err);
						}
					});
					this.client.subscribe(this.mtopicOne + self.subId, (err) => {
						if (!err) {
							console.log("智能控制订阅成功:" + this.mtopicOne + self.subId);
						} else {
							// console.log("连接错误:" + err);
						}
					});
				});
				this.client.on("message", (topic, message) => {
					if (message) {
							console.log('topic',topic)
							console.log('传感器',this.mtopic + this.subId)
							console.log('智能控制',this.mtopicOne + this.subId)
						if (topic == this.mtopic + this.subId) {
							//传感器
							let data = JSON.parse(message)
							let list = JSON.parse(JSON.stringify(this.sensorData))
							console.log('传感器data',data)
							console.log('传感器list',list)
							list.forEach((item) => {
								data.forEach((minItem) => {
									if (item.deviceNo == minItem.deviceNo) {
										item.deviceValue = minItem.deviceValue;
										item.online = minItem.online;
									}
								})
							})
							this.$set(this, 'sensorData', list);
						} else if (topic == this.mtopicOne + this.subId) {
							//智能控制
							let data = JSON.parse(message)
							let list = JSON.parse(JSON.stringify(this.labHardwareVOList))
							console.log('智能控制data',data)
							console.log('智能控制list',list)
							list.forEach((item) => {
								if (item.hardwareNo == data.hardwareNo) {
									if (item.hardwareTypeKey == 'airConditioner') {
										if (data.command == 0) {
											item.switchType = 0;
											item.functionType = '';
											item.orderType = '';
										} else if (data.command == 2) {
											item.switchType = 1;
											item.functionType = 3;
											item.orderType = '';
										} else if (data.command.indexOf('-') != -1) {
											let list = data.command.split('-');
											item.switchType = 1;
											item.functionType = list[0] == 3 ? 1 : (list[0] == 4 ? 2 : '');
											item.orderType = list[1] ? list[1] : '';
										} else {
											item.switchType = '';
											item.functionType = '';
											item.orderType = '';
										}
									} else {
										item.operatingState = data.operatingState;
										item.online = data.online;
									}
								}
							})
							this.$set(this, 'labHardwareVOList', list);
						}

					}
				});
			},
			//取消订阅关闭MQTT连接
			offMQTT(type) {
				let self = this;
				if (self.client.unsubscribe) {
					self.client.unsubscribe(self.mtopicOne + self.subId, error => {
						if (error) {
							// console.log('mqtt关闭连接错误:', error)
						}
					})
					self.client.end();
					this.$set(this, 'client', {});
				}
				//判断传入参数如果存在 发起一次新的连接
				if (type) {
					this.sensorMQTT();
				}
			},


		},
		onHide() {
			//清除定时器
			let self = this;
			self.offMQTT();
		},
		beforeDestroy() {
			//清除定时器
			let self = this;
			self.offMQTT();
		},
	}
</script>

<style lang="stylus" scoped>
	.iotControl {
		flex:1;
		display: flex;
		flex-direction: column;
		overflow-y: scroll !important;
		width: 750rpx;

		.device-type {
			background: #fff;
			padding: 24rpx 20rpx;
			box-sizing: border-box;
			display: flex;
			justify-content: flex-start;
			flex-wrap: wrap;

			>view {
				//width: 356rpx;
				height: 80rpx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				padding-left: 10rpx;
				padding-right: 10rpx;
				box-sizing: border-box;

				>img:nth-of-type(1) {
					width: 42rpx;
					height: 42rpx;
					margin-right: 12rpx;
				}

				>view {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #222222;
					line-height: 80rpx;
					width: 244rpx;
					display:block;
					overflow:hidden;
					text-overflow:ellipsis;
					white-space:nowrap;
				}

				>img:nth-of-type(2) {
					width: 24rpx;
					height: 22rpx;
				}
			}

			>view:nth-child(2n) {
				border-right: none;
				padding-left: 20rpx;
				box-sizing: border-box;
			}

			>view:nth-last-child(1) {
				border-bottom: none;
			}

			>view:nth-last-child(2) {
				border-bottom: none;
			}
		}

		.small-title {
			height: 80rpx;
			border-bottom: 1rpx solid #E0E0E0;
			background: #FFFFFF;
			margin-top: 20rpx;
			display: flex;
			align-items: center;

			>view:nth-of-type(1) {
				width: 4rpx;
				height: 34rpx;
				background: #0D97EB;
				margin: 0rpx 24rpx 0 20rpx;
			}

			>view:nth-of-type(2) {
				font-family: PingFang SC;
				font-weight: 500;
				font-size: 32rpx;
				color: #333333;
				line-height: 80rpx;
			}

		}

		.sensor {
			display: flex;
			justify-content: flex-start;
			flex-wrap: wrap;
			background: #fff;
			padding: 30rpx 20rpx 0;
			box-sizing: border-box;

			.sensor-min {

				min-height: 66rpx;
				width: 690rpx;
				display: flex;
				justify-content: flex-start;
				align-content: center;

				.sensor-l {
					flex-shrink: 0;
					width: 42rpx;
					height: 42rpx;
					margin-right: 20rpx;
				}

				.sensor-r {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;

					line-height: 30rpx;
					overflow: hidden;

					text-overflow: ellipsis;

					white-space: nowrap;
				}

				.color-A {
					color: #222222;
				}

				.color-B {
					color: red;
				}
			}
		}

		.intelligent-control {
			background: #fff;
			padding: 0 20rpx;
			box-sizing: border-box;

			>view {
				display flex;
				border-bottom: 1rpx solid #e0e0e0;

				.for-button-p {
					flex: 1;
					line-height: 90rpx;
					color: #333333;
					font-size: 28rpx;

					>text {
						font-size: 28rpx;
						color: #0183FA;
					}
				}

				>img {
					height: 50rpx;
					width: 100rpx;
					margin: 20rpx 0 20rpx 0;
				}

				view:nth-child(2) {
					text-align right;
					color: #999;
				}

				.pcType-button {
					width: 120rpx;
					line-height: 42rpx;
					border: 4rpx solid #0183FA;
					border-radius: 30rpx;
					color: #0183FA !important;
					font-size: 24rpx;
					text-align center !important;
					margin: 20rpx 0 20rpx 0;
				}
			}

			>view:nth-last-child(1) {
				border-bottom: none;
			}
		}
	}
</style>
