<template>
	<view class="iotControl">
		<view class="device-type">
			<view v-for="(item,index) in deviceType" @click="deviceTypeFun(item)">
				<img :src="item.img">
				<view>{{item.hardwareName}}</view>
				<img src="@/images/basicsModules/icon_wdwg_gd.png">
			</view>
		</view>
		<!-- 传感器监测 -->
		<view class="small-title">
			<view></view>
			<view>传感器监测</view>
		</view>
		<view class="sensor">
			<view v-for="(item,index) in sensorData">
				<img :src="baseUrl+item.icon">
				<veiw>{{item.deviceName}}: {{item.deviceValue?item.deviceValue:''}}{{item.unit?item.unit:''}}</veiw>
			</view>
		</view>
		<!-- 智能控制 -->
		<view class="small-title">
			<view></view>
			<view>智能控制</view>
		</view>
		<view class="intelligent-control">
			<view  v-for="(item,index) in labHardwareVOList" :key="index" v-if="item.hardwareTypeKey !='airConditioner'">
			  <view class="for-button-p">{{item.hardwareName}}
				<text v-if="item.reservedThree">({{item.reservedThree}})</text>
			  </view>
			  <img v-if="item.online && item.operatingState" src="@/images/basicsModules/icon_10.png" @click="buttonClick('switch',item,'0')">
			  <img v-if="item.online && !item.operatingState" src="@/images/basicsModules/icon_11.png" @click="buttonClick('switch',item,'1')">
			  <view class="for-button-p" v-if="!item.online">离线</view>
			</view>
		</view>
		<!-- 智能终端 -->
		<view class="small-title">
			<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 $mqtt from '@/utils/mqtt.min.js';
	import {iotAppSensorFindBySubId,iotAppHardwareFindByType,
	iotAppHardwareOperatingHardware,
	iotAppDeviceFindByType,
	} from '@/api/basicsModules/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:[
					{
						type:'video',
						hardwareName:'视频监控',
						img: require('@/images/basicsModules/icon_xq_spjk.png'),
					},
					{
						type:'speech',
						hardwareName:'语音广播',
						img: require('@/images/basicsModules/icon_sskz_xz.png'),
					},
				],
				sensorData:[],
				labHardwareVOList:[],
				terminalData:[
					{
						name:'智能管控一体机',
						pcType:1,
					}
				],
			}
		},
		created() {

		},
		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'){

				}else if(item.type=='speech'){
					//语音广播弹窗开启
					this.$parent.buttonClick('broadcastOpen','');
				}else if(item.type=='conditioning'){
					//空调弹窗开启
					this.$parent.buttonClick('conditioningOpen','');
				}
			},
			buttonClick(type,row,status){
			    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);
							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(){
				const {data} = await iotAppSensorFindBySubId({subId:this.subId});
				if(data.code == 200){
					this.$set(this, 'sensorData',data.data);
				}
			},
			//查询硬件设备
			async iotAppHardwareFindByType(){
				const {data} = await iotAppHardwareFindByType({subId:this.subId});
				if(data.code == 200){
					this.$set(this, 'labHardwareVOList',data.data);
					for(let i=0;i<data.data.length;i++){
						if(data.data[i].hardwareTypeKey=='airConditioner'){
							data.data[i].type='conditioning';
							data.data[i].img=require('@/images/basicsModules/icon_xq_kt.png');
							this.deviceType.push(data.data[i])
						}
					}
				}
			},
			//查询物联设备
			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('wxs://' +uni.getStorageSync('mqttUrl'), {
				  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){
					if(topic==this.mtopic+this.subId){
						//传感器
						let data = JSON.parse(message)
						let list = JSON.parse(JSON.stringify(this.sensorData))
						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))
						list.forEach((item)=>{
						  if(item.hardwareNo == data.hardwareNo){
							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();
				}
			},


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

<style lang="stylus" scoped>
	.iotControl {
		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;
				border-right: 1px dashed #E0E0E0;
				border-bottom: 1px dashed #E0E0E0;
				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;
				}
				>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: 12rpx 20rpx 30rpx;
			box-sizing: border-box;
			>view{
				display: flex;
				justify-content: flex-start;
				align-items: center;
				height: 66rpx;
				width: 355rpx;
				>img{
					width: 42rpx;
					height: 42rpx;
					margin-right: 20rpx;
				}
				>view{
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 28rpx;
					color: #222222;
					line-height: 30rpx;
				}
			}
		}
		.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>
