<template>
	<view>
		<text>这是实时监测页面</text>
		<view class="u-demo-block__content">
			<u-row customStyle="margin-bottom: 10px">
				<u-col span="6" style="margin: 0rpx 10rpx 0rpx 10rpx;padding: 25rpx">
					<view class="demo-layout bg-purple-light">
						<u-button type="primary" :text="connectText" @click="clickConnectOrNot()"></u-button>
						<!-- <view class="uni-row connect-btn" @click="clickConnectOrNot()">
						    <text>{{connectText}}</text>
						</view> -->
					</view>
				</u-col>
				<u-col span="6" >
					<view class="state">
						{{state}}
					</view>
				</u-col>
			</u-row>
			  
			<u-row customStyle="margin-bottom: 10px">
				<u-col span="6" style="margin: 0rpx 10rpx 0rpx 10rpx;padding: 25rpx">
					<u-button type="primary" text="发送" @click="clickSend()"></u-button>
				</u-col>
				
			</u-row>
			<u-row customStyle="margin-bottom: 10px">
				<u-col span="6" style="margin: 0rpx 10rpx 0rpx 10rpx;padding: 25rpx">
					<view class="state">
						<text>监测状态</text>
					</view>
				</u-col>
				<u-col span="6" style="margin: 0rpx 10rpx 0rpx 10rpx;padding: 25rpx">
					<view class="demo-layout bg-purple-light">
						<u-switch v-model="value3" size="28" :disabled="!mqttConnected"></u-switch>
					</view>
				</u-col>
			</u-row>
		
		</view>
		<view class="uni-column" style="padding: 20rpx;border: 3px solid green;">
		    <view class="uni-column" v-for="(item,index) in list">
		        <view class="uni-row" style="margin: 10rpx;" v-show="item.gravity=='left'">
		            <text>{{item.content}}</text>
		        </view>
		        <view class="uni-row" style="width: 100%;margin: 10rpx;" v-show="item.gravity=='right'">
		            <text style="width: 100%;text-align: end;">{{item.content}}</text>
		        </view>
		    </view>
		</view>
		<view class="">
			<u-popup :show="showMqttEditConfig" mode="bottom" @close="closeEditConfig" @open="openEditConfig">
				<view style="height: 300rpx;">
					<u-button type="info" @click="readConfig()">读取json</u-button>
					<u-button type="info" @click="savejson()">保存json</u-button>
					<u-button type="info" @click="resetConfig()">重置json</u-button>
				</view>
			</u-popup>
			<!-- <view class="btn" @click="showMqttEditConfig = true">打开弹出层</view> -->
		</view>
	
		<view class="showMqttEdit" @click="showMqttEditConfig = true">
			<u-icon name="setting" size="28" color="#fff"></u-icon>
		</view>
	</view>
</template>

<script>
	const mqttModule = uni.requireNativePlugin("jushi-MqttPlugin");
	import mqttconfig from '@/static/mqttconfig.json';
	import ConfigManager from '@/utils/configManager.js';
	import EditMqttConfig from '../edit-mqtt-config/edit-mqtt-config.vue'
	// 默认配置
	const defaultConfig = {
		"host": "ws://101.126.7.123:8083",
		"userName": "taytest",
		"psw": "txgy1929",
		"clientId": "123@jk1bh0"
	};
	export default {
		components: {
			EditMqttConfig
		},
		data() {
			return {
				list: [],
				sendMsg: [],
				value3:false,
				showMqttEditConfig: false,
				monitorStatus:false,
				state: 'mqtt未连接',
				mqttConnected:false,
				connectText: '开始连接',
				stateColor: "#666666",
				currentMqttConfig : {
					host: '',
					userName: '',
					psw: '',
					clientId: ''
				},
				inputValue: '手机发送的数据'
			}
		},
		created() {
			this.readConfig();
			console.log('读取配置');
			this.mqttCallback()
			// mqttModule.enabledDebug(true)//开启日志输出，需要用Android studio才能查看插件日志
		},		
		methods: {
			change(e) {
				console.log('change', e);
			},
			openEditConfig() {
				this.showMqttEditConfig = true;
			},
			closeEditConfig() {
				this.showMqttEditConfig = false;
				// console.log('close');
			},
			mqttCallback() { //mqtt回调监听
				mqttModule.addCallback(res => {
					console.log("回调结果：" + res)
					
					var json = JSON.parse(res)
					switch (parseInt(json.code)) {
						case 0: //mqtt连接成功
							this.toSubscribe()
							this.state = "mqtt已连接"
							this.stateColor = "#008577"
							this.connectText = "断开连接"
							this.mqttConnected=true;
							
							break
						case -2: //手动断开连接
							this.state = "mqtt未连接"
							this.stateColor = "#666666"
							this.connectText = "开始连接"
							this.mqttConnected=false;
							break
						case 2: //收到消息（对方发的和自己发的都会走到这里）
							this.handleMsg(json)
							break
					}
				})
			},
			clickConnectOrNot() {
				mqttModule.isConnected(res => {
					console.log("mqtt是否已连接：" + res)
					if (res) {
						mqttModule.disconnect()
					} else {
						var sever = "ws://101.126.7.123:8083";									
						var userName = "taytest";
						var psw = "txgy1929";
						var clientId = "123@jk1bh0";
						// mqttModule.connect(sever, userName, psw, clientId) //mqtt连接方法1
						this.connectMqtt(sever, userName, psw, clientId) //mqtt连接方法2
					}
				})
			},
			connectMqtt(sever, userName, psw, clientId) {
				mqttModule.connectUseJson({
					sever: sever, //服务地址 示例：wss://ip:port
					userName: userName, //用户名
					password: psw, //密码
					clientId: clientId, //客户端id
					autoReconnect: true, //是否自动重连，默认是true，也可以使用setAutoReconnect(true/false)函数设置
					isCleanSession: true, //是否持久会话，默认为true
					connectionTimeout: 20, //连接超时时间 默认20s 
					keepAliveInterval: 10 //心跳时间 默认10s 
				})
			},
			toSubscribe() { //连接成功，订阅主题
				mqttModule.subscribe("testtopic/1")
			},
			toUnsubscribe() { //取消订阅
				mqttModule.unsubscribe("testtopic/1")
			},
			clickSend() { //点击发送
				mqttModule.isConnected(res => {
					if (!res) {
						this.toast("MQTT未连接")
						return
					}
					var msg = JSON.stringify(this.inputValue)
					this.sendMsg.push(msg)
					mqttModule.publish(msg, "testtopic/1")
					this.inputValue = ''
				})
			},
			toast(msg) {
				uni.showToast({
					icon: "none",
					title: msg
				})
			},
			handleMsg(json) { //处理收到的消息（对方发的和自己发的都会走到这里）
				var isSend = false
				for (var i = 0; i < this.sendMsg.length; i++) {
					if (this.sendMsg[i] == json.data.message) {
						isSend = true
						break
					}
				}
				var data = {
					content: `Topic：${json.data.topic}\n ${json.data.message}`,
					gravity: isSend ? "right" : "left"
				}
				this.list.push(data)
			},
			// 1. 初始化配置文件
			initializeConfig() {
				ConfigManager.initializeConfigFile(defaultConfig, (error, config) => {
					if (error) {
						console.error('初始化配置文件失败:', error);
					} else {
						console.log('配置文件已初始化:', config);
					}
				});
			},
			// 2. 读取配置文件
			readConfig() {
				ConfigManager.readConfigFile((error, config) => {
					if (error) {
						console.error('读取配置文件失败:', error);
					} else {
						console.log('当前配置:', config);
						this.currentMqttConfig=config;
					}
				});
			},
			// 3. 修改并保存配置文件
			saveConfig(newConfig) {
				ConfigManager.saveConfigFile(newConfig, (error) => {
					if (error) {
						console.error('保存配置文件失败:', error);
					} else {
						console.log('配置文件已更新:', newConfig);
					}
				});
			},
			// 4. 重置配置文件
			resetConfig() {
				ConfigManager.resetConfigFile(defaultConfig, (error) => {
					if (error) {
						console.error('重置配置文件失败:', error);
					} else {
						console.log('配置文件已重置为默认内容:', defaultConfig);
					}
				});
			},
			savejson() {				
				this.saveConfig(this.currentMqttConfig);
			}
		}
	}
</script>

<style lang="scss">	
	.connect-btn {
	    width: 100%;
	    justify-content: center;
	    border-radius: 10rpx;
	    border: 1rpx solid #aaaaaa;
	    font-size: 30rpx;
	    padding: 5rpx 20rpx 5rpx 20rpx;
	}
	.showMqttEdit {
		width: 100rpx;
		height: 100rpx;
		background: #2196F3;
		color: #fff;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		font-size: 60rpx;
		position: fixed;
		right: 60rpx;
		bottom: 120rpx;
		box-shadow: 0 0 20 rpx rgba(43, 153, 57, 0.6);
	}
	.state{
		margin: 0rpx 10rpx 0rpx 10rpx;
		padding: 70rpx 0;
		text-align: center;
		font-size: 36rpx;
	}
</style>