<template>
	<page-meta>
		<navigation-bar :title="$tt('navBar.deviceDetails')" title-align="center" background-color="#F1F3F9"
			front-color="#000000">
		</navigation-bar>
	</page-meta>
	<view class="device-detail">
		<u--form labelPosition="left" :model="deviceForm" :rules="deviceRules" ref="deviceForm" labelWidth="90"
			labelAlign="left">
			<view class="card">
				<view class="card-title-wrap">
					<u--text :text="$tt('deviceDetail.basicMsg')" bold color="#000000"></u--text>
				</view>
				<u-form-item :label="$tt('deviceDetail.deviceName')" prop="deviceName" borderBottom>
					<view class="item-right" slot="right">
						<u--input v-model="deviceForm.deviceName" clearable border="none" inputAlign="right"></u--input>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.position')" prop="locationWay" borderBottom>
					<view class="item-right" slot="right">
						<uni-data-select v-model="deviceForm.locationWay" clearable :localdata="locationList"
							:clear="false" style="width: 150rpx;">
						</uni-data-select>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.longitude')" borderBottom v-if="deviceForm.locationWay === 3">
					<view class="item-right" slot="right">
						<u--input v-model="deviceForm.longitude" type="digit"
							:placeholder="$tt('deviceDetail.inputLongitude')" border="none"
							inputAlign="right"></u--input>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.latitude')" borderBottom v-if="deviceForm.locationWay === 3">
					<view class="item-right" slot="right">
						<u--input v-model="deviceForm.latitude" type="digit"
							:placeholder="$tt('deviceDetail.inputLatitude')" border="none"
							inputAlign="right"></u--input>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.address')" borderBottom v-if="deviceForm.locationWay === 3">
					<u--input v-model="deviceForm.networkAddress" border="none" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.shadow')" borderBottom>
					<view class="item-right" slot="right"><u-switch v-model="deviceForm.isShadow" activeColor="#3c9cff"
							:inactiveValue="0" :activeValue="1" size="20"></u-switch>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.disabledDevice')" borderBottom>
					<view class="item-right" slot="right"><u-switch v-model="deviceDisable" activeColor="#f56c6c"
							:inactiveValue="0" :activeValue="1" size="20"></u-switch>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.remark')">
				</u-form-item>
				<u-textarea v-model="deviceForm.remark" height="40" fontSize="14"
					:placeholder="$tt('deviceDetail.inputMsg')" style="background-color: #F7F7F7;"
					confirmType="done"></u-textarea>

				<view style="margin-top: 20px; display: flex; gap: 10px;">
					<u-button v-if="!profile.deptId" @tap="handleGoToShare" size="small" color='#CCCCCC'
						:customStyle="{fontSize: '30rpx',height: '88rpx',borderRadius: '10rpx'}">{{$tt('deviceDetail.share')}}</u-button>
					<u-button type="primary" @tap="handleSubmitForm" size="small"
						:customStyle="{fontSize: '30rpx',height: '88rpx',borderRadius: '10rpx'}">{{$tt('deviceDetail.preserve')}}</u-button>
				</view>
			</view>
			<view class="card">
				<u-form-item borderBottom>
					<u-row>
						<!-- #ifdef H5 -->
						<u-col :span="7.5">
						<!--  #endif-->
							<!-- #ifndef H5 -->
							<u-col :span="2.5">
							<!--  #endif-->
								<u--text :text="$tt('deviceDetail.deviceStatus')" bold color="#000000"></u--text>
							</u-col>
							<u-col :span="2"><u-button :text="$tt('home.notActive')" type="warning" size="mini" plain
									v-if="deviceForm.status == 1"
									customStyle="width:50px;margin-left:12rpx;"></u-button>
								<u-button :text="$tt('home.disabled')" type="error" size="mini" plain
									v-if="deviceForm.status == 2"
									customStyle="width:50px;margin-left:12rpx;"></u-button>
								<u-button :text="$tt('home.onLine')" type="success" size="mini" plain
									v-if="deviceForm.status == 3" customStyle="width:50px;"></u-button>
								<u-button :text="$tt('home.offline')" type="info" size="mini" plain
									v-if="deviceForm.status == 4"
									customStyle="width:50px;margin-left:12rpx;"></u-button>
							</u-col>
					</u-row>

					<view slot="right" @click="handleDeleteDevice">
						<u-icon name="trash" color="#f85959" size="23"></u-icon>
					</view>
				</u-form-item>

				<u-form-item :label="$tt('deviceDetail.serialNumber')" borderBottom>
					<view slot="right">
						<u--text :text="deviceForm.serialNumber"></u--text>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.belongingProducts')" borderBottom>
					<view slot="right"><u--text :text="deviceForm.productName"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.firmwareVersion')" borderBottom>
					<view slot="right"><u--text :text="formatVersion(deviceForm.firmwareVersion)"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.positionMethod')" v-if="deviceForm.deviceType === 3"
					borderBottom>
					<view slot="right"><u--text :text="deviceForm.locationWayInfo.name"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.longitude')"
					v-if="deviceForm.longitude && deviceForm.locationWay !== 3" borderBottom>
					<view slot="right"><u--text :text="deviceForm.longitude"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.latitude')"
					v-if="deviceForm.latitude && deviceForm.locationWay !== 3" borderBottom>
					<view slot="right"><u--text :text="deviceForm.latitude"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.equipmentSignal')" borderBottom>
					<view slot="right"><u--text :text="$tt('deviceDetail.veryGood')" type="success"
							v-if="deviceForm.rssi >= '-55'"></u--text>
						<u--text :text="$tt('deviceDetail.excellent')" type="success"
							v-else-if="deviceForm.rssi >= '-70' && deviceForm.rssi < '-55'"></u--text>
						<u--text :text="$tt('deviceDetail.good ')" type="success"
							v-else-if="deviceForm.rssi >= '-85' && deviceForm.rssi < '-70'"></u--text>
						<u--text :text="$tt('deviceDetail.average ')" type="warning"
							v-else-if="deviceForm.rssi >= '-100' && deviceForm.rssi < '-85'"></u--text>
						<u--text :text="$tt('deviceDetail.poor')" type="error" v-else></u--text>
					</view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.address')"
					v-if="deviceForm.networkAddress && deviceForm.locationWay !== 3" borderBottom>
					<view slot="right"><u--text :text="deviceForm.networkAddress"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.networkAddress')" borderBottom>
					<view slot="right"><u--text :text="deviceForm.networkIp"></u--text></view>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.activationTime')">
					<view slot="right"><u--text :text="deviceForm.activeTime"></u--text>
					</view>
				</u-form-item>
				<u--image :src="imageUrl" radius="10" mode="aspectFill" width="100%" height="200">
					<view slot="error" style="font-size: 18rpx;">{{$tt('deviceDetail.loadingFail')}}</view>
					<template v-slot:loading>
						<u-loading-icon></u-loading-icon>
					</template>
				</u--image>
			</view>
		</u--form>
		<u-modal :show="show" :title="$tt('deviceDetail.remove')" :content="content" showCancelButton
			@confirm="handleConfirmDelete" @cancel="show = false"></u-modal>

	</view>
</template>

<script>
	import projectConfig from '@/env.config.js';
	import { getDevice, updateDevice, delDevice } from '@/apis/modules/device';
	import { getLocationWayInfo } from '@/helpers/common.js';

	export default {
		name: "deviceDetail",
		data() {
			return {
				// 设备详情
				deviceForm: {
					isShadow: 0,
				},
				// 表单校验
				deviceRules: {
					deviceName: [{
						required: true,
						message: this.$tt('deviceDetail.deviceCheck'),
						trigger: ['blur', 'change']
					}]
				},
				// 定位方式
				locationList: [{
					value: 1,
					text: this.$tt('deviceDetail.autoPosition')
				}, {
					value: 2,
					text: this.$tt('deviceDetail.devicePosition')
				}, {
					value: 3,
					text: this.$tt('deviceDetail.customLocation')
				}],
				deviceDisable: 0, // 设备状态（1=禁用，0=不禁用）
				imageUrl: '', // 图片地址
				show: false, // 删除设备模态框
				content: '', // 对话框内容
				buttonWrap: {
					fontSize: '30rpx',
					width: '301rpx',
					height: '88rpx',
					borderRadius: '10rpx',
					margin: '20rpx'
				},
			};
		},
		onLoad(option) {
			const deviceId = option.deviceId;
			this.getDeviceDetails(deviceId);
		},
		methods: {
			// 连接Mqtt消息服务器
			async connectMqtt() {
				if (this.$mqttTool.client === null) {
					await this.$mqttTool.connect(this.vuex_token);
				}
				this.mqttCallback();
			},
			// Mqtt回调处理
			mqttCallback() {
				this.$mqttTool.client.on('message', (topic, message, buffer) => {
					let topics = topic.split('/');
					let productId = topics[1];
					let deviceNum = topics[2];
					message = JSON.parse(message.toString());
					if (!message) {
						return;
					};
					if (topics[3] == 'status' || topics[2] == 'status') {
						console.log('接收到【设备状态-详情】主题：', topic);
						console.log('接收到【设备状态-详情】内容：', message);
						// 更新列表中设备的状态
						if (this.deviceForm.serialNumber == deviceNum) {
							this.deviceForm.status = message.status;
						}
					};
				});
			},
			getDeviceDetails(deviceId) {
				getDevice(deviceId).then(res => {
					let data = res.data;
					this.imageUrl = data.imgUrl;
					if (this.imageUrl != null && this.imageUrl != '') {
						this.imageUrl = projectConfig.baseUrl + this.imageUrl;
					} else {
						this.imageUrl = '/static/common/device.png';
					}
					// 禁用状态
					if (data.status == 2) {
						this.deviceDisable = 1;
					}
					// 获取定位方式
					data.locationWayInfo = getLocationWayInfo(data.locationWay);
					this.deviceForm = data;
					this.connectMqtt();
				});
			},
			// 格式化版本显示
			formatVersion(version) {
				return `Version ${version}`;
			},
			// 调转到分享
			handleGoToShare() {
				const { deviceId, productId, deviceName } = this.deviceForm;
				uni.$u.route('/pagesA/device/share/list', {
					deviceId,
					productId,
					deviceName
				});
			},
			// 提交按钮
			handleSubmitForm() {
				this.$refs.deviceForm.validate().then(e => {
					if (this.deviceForm.deviceId !== 0) {
						this.setDeviceStatus(); // 设置设备状态
						let device = {
							...this.deviceForm
						};
						updateDevice(device).then(res => {
							if (res.code === 200) {
								uni.showToast({
									icon: 'success',
									title: this.$tt('deviceDetail.updateSuccess')
								});
							}
						});
					}
				});
			},
			// 设置设备的状态（1-未激活，2-禁用，3-在线，4-离线）
			setDeviceStatus() {
				if (this.deviceDisable == 1) {
					this.deviceForm.status = 2;
				} else {
					// 禁用状态，启用后状态是离线
					if (this.deviceForm.status == 2) {
						this.deviceForm.status = 4;
					}
				}
			},
			// 删除设备按钮操作
			handleDeleteDevice() {
				this.content = '是否确认删除 ' + this.deviceForm.deviceName + ' ？';
				this.show = true;
			},
			// 确认删除设备
			handleConfirmDelete() {
				this.show = false;
				delDevice(this.deviceForm.deviceId).then(res => {
					if (res.code == 200) {
						// 跳转主页,通过globalData传递参数
						getApp().globalData.operate = 'operate';
						uni.switchTab({
							url: '/pages/tabBar/home/index'
						});
					} else if (res.code == 500) {
						uni.showToast({
							icon: 'none',
							title: res.msg
						});
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: $uni-bg-color-grey;
	}
</style>
<style lang="scss" scoped>
	.device-detail {
		padding-bottom: 30rpx;

		.card {
			background-color: #fff;
			padding: 29rpx;
			border-radius: 20rpx;
			margin: 30rpx;

			.item-right {
				display: flex;
				flex-direction: row;
			}

			::v-deep .u-form-item__body {
				height: 80rpx;
			}

			.card-title-wrap {
				display: flex;
				padding: 20rpx 0;
				border-bottom: 1px solid #efefef;
			}
		}
	}

	::v-deep .uni-select[data-v-6b64008e] {
		border: none;

	}
</style>