<template>
	<view style="height: 100vh">
		<view class="">
			<u-navbar title="策略下发" :is-back="true" :background="background" :border-bottom="false"
				:custom-back="toback">
			</u-navbar>
		</view>
		<view class="policeForm">
			<view class="" v-for="(item, index) in smallArr" :key="index">
				<view class="" v-if="item.type == 'Input'">
					<u-form-item :label="item[`label_${lang}`]" :prop="item.prop">
						<u-input :min="item.min" :max="item.max" v-model.number="item.value" type="number"
							:placeholder="item[`place_${lang}`]" @input="handleInput(item, $event)" />
					</u-form-item>
				</view>
				<view class="" v-if="item.type == 'Switch'">
					<u-form-item :label="item[`label_${lang}`]" :prop="item.prop">
						<u-switch :size="40" v-model="item.value"></u-switch>
					</u-form-item>
				</view>
				<view class="" v-if="item.type == 'Select'" @click="selectShow(item, index)">
					<u-form-item :label="item[`label_${lang}`]" :prop="item.prop">
						<view class="" v-show="false">
							<u-input v-model="item.value" disabled @click="selectShow(item, index)" />
						</view>
						<view class="">
							{{ item.selectLabel || $t("homePage.alarm.placeSelect") }}
						</view>
						<u-select :key="item.prop" @confirm="confirm($event, item)" v-model="item.isShow"
							:list="getSelectList(item)"></u-select>
					</u-form-item>
				</view>
			</view>

			<button @click="submitDevice" type="success" size="mini" style="
          background-color: #009458;
          padding: 10rpx 0;
          color: #fff;
          margin-top: 40rpx;
          width: 100%;
        ">
				{{ $t("homePage.mine.submit") }}
			</button>
		</view>
	</view>
</template>

<script>
	import {
		formList
	} from "@/common/form.js";
	import {
		Langlist
	} from "@/common/lang";
	import MQTTClient from "@/static/lib/mqtt.js";
	export default {

		data() {
			return {
				formList: formList,
				background: {
					backgroundColor: "#0EA17E",
				},
				lang: 'en',
				mqttClient: null,
				backData: {},
				smallArr: [],
				mqttConfig: {
					host: '13.39.200.14',
					port: 8083,
					clientId: 'mqttx_' + Date.now(),
					username: 'admin',
					password: 'zzkj@688737',
					path: 'mqtt',
					protocolVersion: 4, // 4 for MQTT 3.1.1
					clean: false,
					cleanStart: false, // for MQTT 5.0
					keepAlive: 60,
					sessionExpiryInterval: 4294967295,
					connectTimeout: 10000,
					reconnectPeriod: 3000

				},

			};
		},
		computed: {
			language() {
				return this.$store.state.vuex_language
			},
			currentStation() {
				console.log(this.vuex_currentStation)
				return this.vuex_currentStation;
			},
		},

		onShow() {
			this.connect()
		},

		methods: {
			initMQTTClient() {
				this.mqttClient = new MQTTClient(this.mqttConfig)
				console.log(this.mqttClient);
				// 监听连接事件
				this.mqttClient.on('connect', () => {
					console.log('MQTT 连接成功')
					this.publish({
						topic: '/test',
						message: {
							fun: 'GET',
							type: 'WJ_Get_NewControlSystem',
							content: 0
						},
						qos: 0
					})
				})

				// 监听断开事件
				this.mqttClient.on('disconnect', (res) => {
					this.connectionStatus = 'disconnected'
					console.log('连接已关闭')
				})

				// 监听错误事件
				this.mqttClient.on('error', (error) => {
					console.log(error)
				})

				// 监听状态变化
				this.mqttClient.on('statusChange', (status) => {
					console.log(status)
				})

				// 监听消息事件
				this.mqttClient.on('message', (msg) => {
					console.log(msg)
				})

				// 监听订阅成功事件
				this.mqttClient.on('subscribed', (packetId) => {
					this.addLog('success', `订阅成功 (包ID: ${packetId})`)
					uni.showToast({
						title: '订阅成功',
						icon: 'success'
					})
				})

				// 监听取消订阅成功事件
				this.mqttClient.on('unsubscribed', (packetId) => {
					this.addLog('success', `取消订阅成功 (包ID: ${packetId})`)
					uni.showToast({
						title: '取消订阅成功',
						icon: 'success'
					})
				})
			},


			publish(publishConfig) {
				const {
					topic,
					message,
					qos
				} = publishConfig

				if (!topic) {
					uni.showToast({
						title: '请输入主题',
						icon: 'none'
					})
					return
				}

				if (this.mqttClient) {
					this.mqttClient.publish(topic, message, qos)
				}
			},

			subscribe() {

				if (this.mqttClient) {
					this.mqttClient.subscribe({
						topic: '/test',
						qos: 0
					})
				}
			},

			connect() {
				const {
					host
				} = this.mqttConfig

				if (!host) {
					uni.showToast({
						title: '请输入主机地址',
						icon: 'none'
					})
					return
				}

				console.log('开始连接 MQTT 服务器...')


				// 如果客户端未初始化，重新初始化
				if (!this.mqttClient) {
					this.initMQTTClient()
				}
				this.mqttClient.reSetconstructor(this.mqttConfig)

				this.mqttClient.connect()
			},




			decodeGzipBase64(base64Str) {
				// 1. base64 → Uint8Array
				const binaryStr = atob(base64Str);
				const len = binaryStr.length;
				const bytes = new Uint8Array(len);

				for (let i = 0; i < len; i++) {
					bytes[i] = binaryStr.charCodeAt(i);
				}

				// 2. gunzip 解压
				const decompressed = pako.ungzip(bytes, {
					to: "string"
				});
				// 3. 转 JSON（如果是 JSON）
				return JSON.parse(decompressed);
			},
			getSelectList(item) {
				if (item.selectArr && item.selectArr.length > 0) {
					return item.selectArr.map(option => ({
						value: option.value.toString(),
						label: option[`label_${this.lang}`] || option.label
					}))
				}
				return []
			},
			control(NewControlSystemShow_data) {
				this.formList.forEach(item => {
					if (item.type == "Switch") {
						item.value = NewControlSystemShow_data?.params[item.prop] ? true : false
					} else {
						item.value = NewControlSystemShow_data?.params[item.prop] || item.default
					}
					if (item.type == 'Select') {
						item.selectLabel = item.selectArr.find(v => v.value == item.value)?.[`label_${this.lang}`]
					}
					item.isShow = false
				})
				this.backData = NewControlSystemShow_data
				this.smallArr = this.formList.filter(v => NewControlSystemShow_data?.smallScreen.includes(v.prop))
			},
			confirm(val, item) {
				if (val && val.length > 0) {
					item.value = val[0].value
					item.selectLabel = val[0].label
				}
				item.isShow = false
			},
			handleInput(item, event) {
				try {
					let inputValue = event.detail.value;
					let iptval = String(inputValue).replace(/[^0-9.]/g, '');
					const parts = iptval.split('.');
					if (parts.length > 2) {
						iptval = parts[0] + '.' + parts.slice(1).join('');
					}
					if (!iptval || iptval === '.') {
						item.value = 0;
						return;
					}
					let numVal = Number(iptval);
					if (item.min !== undefined && item.min !== null) {
						numVal = Math.max(numVal, item.min);
					}
					if (item.max !== undefined && item.max !== null) {
						numVal = Math.min(numVal, item.max);
					}
					numVal = isNaN(numVal) ? 0 : numVal;
					item.value = numVal;
				} catch (error) {
					console.log('handleInput方法错误:', error);
				}
			},

			toback() {
				uni.navigateBack()
			},
			selectShow(val, index) {
				val.isShow = true
			},
			submitDevice() {
				let smallParam = this.smallArr.reduce((pre, cur) => {
					pre[cur.prop] = cur.type == "Switch" ? cur.value ? 1 : 0 : cur.value
					pre[cur.prop] = Number(pre[cur.prop])
					return pre
				}, {})
				this.publish({
					topic: '/test',
					message: {
						fun: 'SET',
						type: 'WJ_Set_NewControlSystem',
						content: {
							...this.backData,
							params: {
								...this.backData.params,
								...smallParam
							}
						}
					},
					qos: 0
				})

			},
		},
	};
</script>

<style lang="scss" scoped>
	.policeForm {
		margin: 22rpx;
		padding: 22rpx;
		background-color: #fff;
		box-shadow: 0px 4rpx 16rpx rgba(0, 0, 0, 0.1);
		border-radius: 8rpx;
	}
</style>