<template>
	<view class="device-detail">
		<u--form labelPosition="left" :model="deviceForm" :rules="deviceRules" ref="deviceForm" labelWidth="90"
			labelAlign="center">
			<view class="card">
				<view class="card-title-wrap">
					<u--text prefixIcon="grid-fill" iconStyle="font-size: 16px;color:#606266"
						:text="$tt('deviceDetail.basicMsg')" bold color="#606266"></u--text>
				</view>
				<u-form-item :label="$tt('deviceDetail.deviceName')" prop="deviceName">
					<u--input v-model="deviceForm.deviceName"></u--input>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.position')" prop="locationWay">
					<uni-data-select v-model="deviceForm.locationWay" :localdata="locationList" :clear="false">
					</uni-data-select>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.longitude')" v-if="deviceForm.locationWay === 3">
					<u--input v-model="deviceForm.longitude" type="digit"
						:placeholder="$tt('deviceDetail.inputLongitude')"></u--input>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.latitude')" v-if="deviceForm.locationWay === 3">
					<u--input v-model="deviceForm.latitude" type="digit"
						:placeholder="$tt('deviceDetail.inputLatitude')"></u--input>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.address')" v-if="deviceForm.locationWay === 3">
					<u--input v-model="deviceForm.networkAddress"></u--input>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.shadow')">
					<u-switch v-model="deviceForm.isShadow" activeColor="#3c9cff" :inactiveValue="0" :activeValue="1"
						size="20"></u-switch>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.disabledDevice')">
					<u-switch v-model="deviceDisable" activeColor="#f56c6c" :inactiveValue="0" :activeValue="1"
						size="20"></u-switch>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.remark')">
					<u-textarea v-model="deviceForm.remark" height="40" fontSize="14"
						:placeholder="$tt('deviceDetail.inputMsg')" confirmType="done"></u-textarea>
				</u-form-item>
				<view style="margin-top:10px;display:flex;">
					<u-button type="success" v-if="profile.deptId==null" @tap="handleGoToShare" size="small"
						customStyle="margin:10px;">{{$tt('deviceDetail.share')}}</u-button>
					<u-button type="primary" @tap="handleSubmitForm" size="small"
						customStyle="margin:10px;">{{$tt('deviceDetail.preserve')}}</u-button>
				</view>
			</view>
			<view class="card">
				<view style="margin:10px;">
					<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-item :label="$tt('deviceDetail.deviceStatus')">
					<u-button :text="$tt('home.notActive')" type="warning" size="mini" plain
						v-if="deviceForm.status == 1" customStyle="width:50px;margin:0;"></u-button>
					<u-button :text="$tt('home.disabled')" type="error" size="mini" plain v-if="deviceForm.status == 2"
						customStyle="width:50px;margin:0;"></u-button>
					<u-button :text="$tt('home.onLine')" type="success" size="mini" plain v-if="deviceForm.status == 3"
						customStyle="width:50px;margin:0;"></u-button>
					<u-button :text="$tt('home.offline')" type="info" size="mini" plain v-if="deviceForm.status == 4"
						customStyle="width:50px;margin:0;"></u-button>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.serialNumber')">
					<u--text :text="deviceForm.serialNumber"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.belongingProducts')">
					<u--text :text="deviceForm.productName"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.firmwareVersion')">
					<u--text :text="formatVersion(deviceForm.firmwareVersion)"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.positionMethod')" v-if="deviceForm.deviceType === 3">
					<u--text :text="deviceForm.locationWayInfo.name"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.longitude')"
					v-if="deviceForm.longitude && deviceForm.locationWay !== 3">
					<u--text :text="deviceForm.longitude"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.latitude')"
					v-if="deviceForm.latitude && deviceForm.locationWay !== 3">
					<u--text :text="deviceForm.latitude"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.equipmentSignal')">
					<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>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.address')"
					v-if="deviceForm.networkAddress && deviceForm.locationWay !== 3">
					<u--text :text="deviceForm.networkAddress"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.networkAddress')">
					<u--text :text="deviceForm.networkIp"></u--text>
				</u-form-item>
				<u-form-item :label="$tt('deviceDetail.activationTime')">
					<u--text :text="deviceForm.activeTime"></u--text>
				</u-form-item>

				<view style="margin-top:10px;display:flex;">
					<u-modal :show="show" title="删除警告" :content="content" showCancelButton
						@confirm="handleConfirmDelete" @cancel="show = false"></u-modal>
					<u-button type="error" @click="handleDeleteDevice" size="small"
						customStyle="margin:10px;">{{$tt('deviceDetail.deleteDevice')}}</u-button>
				</view>
			</view>
		</u--form>
	</view>
</template>

<script>
	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: '', // 对话框内容
			};
		},
		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" scoped>
	.device-detail {
		padding-bottom: 100rpx;

		.card {
			box-shadow: 0 1px 0px 0 rgba(0, 0, 0, 0.1);
			border-radius: 6px;
			background-color: #fff;
			margin: 10px;
			padding: 10px;

			.card-title-wrap {
				display: flex;
				padding: 6px;
				padding-left: 0;
				border-bottom: 1px solid #efefef;
			}
		}
	}
</style>