ZYC-mobile/pagesA/list/home/deviceAdd.vue
2025-05-22 16:24:05 +08:00

594 lines
14 KiB
Vue
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<template>
<page-meta><navigation-bar :title="$tt('deviceAdd.addDevice')" title-align="center"
background-color="#007AFF" /></page-meta>
<view class="container">
<view class="card">
<u--form labelPosition="left" :model="form" ref="form" labelWidth="80" labelAlign="center">
<view style="padding:10px 0;;border-bottom:1px solid #EFEFEF;display:flex;">
<u--text prefixIcon="grid-fill" iconStyle="font-size: 16px;color:#606266"
:text="$tt('deviceAdd.fillcontent')" bold color="#606266"></u--text>
<u-button type="success" :text="$tt('linkDevice.scan')" icon="scan" size="small"
customStyle="margin-left:20px;width:90px;" @click="openScan(form.serialNumber)"></u-button>
</view>
<u-form-item :label="$tt('deviceAdd.productname')" prop="SSID">
<u-input v-model="form.deviceName" :placeholder="$tt('deviceAdd.inputdevicename')">
</u-input>
</u-form-item>
<u-form-item :label="$tt('deviceAdd.Product')" prop="productId">
<uni-data-select v-model="form.productId" :localdata="list"
:placeholder="$tt('deviceAdd.inputproduct')" @change="handleProductChange" />
</u-form-item>
<u-form-item :label="$tt('deviceAdd.equipment')" prop="imei">
<u-input v-model="form.serialNumber" :placeholder="$tt('deviceAdd.inputequipment')"
:type="passwordShow ? 'text' : 'password'">
</u-input>
</u-form-item>
<u-form-item :label="$tt('deviceAdd.longitude')" prop="longitude">
<u-input v-model="form.longitude" :placeholder="$tt('deviceAdd.inputlongitude')"
:type="passwordShow ? 'text' : 'password'">
</u-input>
</u-form-item>
<u-form-item :label="$tt('deviceAdd.latitude')" prop="latitude">
<u-input v-model="form.latitude" :placeholder="$tt('deviceAdd.inputlatitude')"
:type="passwordShow ? 'text' : 'password'">
</u-input>
</u-form-item>
<!-- 修改分组选择/输入组件 -->
<u-form-item label="设备分组" prop="groupId">
<uni-data-select v-model="form.groupId" :localdata="groupListWithOther" :placeholder="'请选择分组'"
@change="handleGroupChange" />
</u-form-item>
<!-- 新增一个独立的表单项用于其他分组名称输入 -->
<u-form-item v-if="showCustomGroupInput" label="分组名称" prop="groupName">
<u-input v-model="form.groupName" placeholder="请输入新分组名称" />
</u-form-item>
<u-form-item>
<u-button type="primary" @click="getCurrentLocation">获取当前位置</u-button>
</u-form-item>
<u-form-item>
<u-button type="primary" @click="phoneadddevice">添加</u-button>
</u-form-item>
</u--form>
</view>
</view>
</template>
<script>
import {
getProfile
} from '@/apis/modules/common';
import {
getProductList
} from '@/apis/modules/product';
import {
addDevice
} from '@/apis/modules/device.js';
import {
getGroupList,
updateDeviceGroups,
addGroup
} from '@/apis/modules/group';
export default {
data() {
return {
// 是否为微信小程序
isWeChat: false,
// 复选框配置remeber、advance
checkboxConfigs: ['remeber'],
// 配网模式选项卡索引
tabIndex: 0,
// wifi密码可见性
passwordShow: true,
// 用户编号是否可编辑
userIdDisabled: true,
// form: {
// productId: 0,
// status: 1,
// locationWay: 3,
// firmwareVersion: 1.0,
// serialNumber: '',
// deviceType: 1,
// isSimulate: 0,
// productName: '',
// deviceId: "0",
// },
form: {
productId: 0,
status: 1,
locationWay: 3,
firmwareVersion: 1,
serialNumber: "",
deviceType: 2,
isSimulate: 0,
deviceId: "0",
deviceName: "",
productName: "",
tenantId: 0,
tenantName: "",
longitude: "",
latitude: "",
groupId: '', // 添加分组ID字段
groupName: '', // 添加分组名称字段
},
queryParams: {
pageNum: 1,
pageSize: 12,
productName: null,
categoryId: null,
categoryName: null,
tenantId: null,
tenantName: null,
isSys: null,
status: 2, //已发布
// deviceType: 3, // 监控设备
networkMethod: null,
},
list: [], // 产品列表
// 计数
count: {
// 进度定时器
timer: {},
// 显示文本
text: this.$tt('deviceAdd.noDevice'),
// 文字类型
type: 'warning'
},
// 发现设备计时器
discoverTimer: {},
// 单设备配网进度
progress: 0,
// 单设备配网步骤
step: 1,
// wifi列表加载
loading: false,
// wifi列表
mstep: 0,
// 更新WIFI按钮
updateDisable: false,
groupList: [], // 分组列表
isNewGroup: false, // 是否新建分组
showCustomGroupInput: false, // 控制自定义分组输入框显示
};
},
computed: {
// 添加"其他"选项到分组列表
groupListWithOther() {
return [
...this.groupList,
{
value: 'other',
text: '其他分组'
}
]
}
},
created() {
// #ifdef MP-WEIXIN
// this.initInWeChat();
this.tabIndex = 1;
this.isWeChat = true;
// #endif
// #ifndef MP-WEIXIN
this.tabIndex = 0;
// #endif
//获取登录用户信息
// 获取登录用户信息
if (this.profile == null) {
this.getProfile();
} else {
this.form.tenantId = this.profile.userId;
this.form.tenantName = this.profile.userName;
console.log("profile:", JSON.stringify(this.profile)); // 打印出用户ID
}
this.getList();
// 断开Mqtt连接
this.endMqtt();
// 获取WIFI信息
// this.getWifi();
// if (this.tabIndex == 0) {
// // 发现设备
// this.discoverDevice();
// }
this.getGroupList(); // 获取分组列表
},
onUnload() {
clearInterval(this.discoverTimer);
// 页面卸载时连接mqtt
this.connectMqtt();
},
methods: {
/* 断开Mqtt消息服务器 */
async endMqtt() {
await this.$mqttTool.end();
},
/* 连接Mqtt消息服务器 */
async connectMqtt() {
if (this.$mqttTool.client == null) {
console.log('连接mqtt...');
await this.$mqttTool.connect(this.vuex_token);
}
},
getCurrentLocation() {
console.log('获取位置函数开始执行');
uni.getLocation({
type: 'gcj02', // 尝试使用 gcj02 类型
success: (res) => {
console.log('获取位置成功', res);
this.$set(this.form, 'longitude', String(res.longitude));
this.$set(this.form, 'latitude', String(res.latitude));
uni.showToast({
title: '定位成功',
icon: 'success'
});
},
fail: (err) => {
console.error('获取定位失败:', err);
uni.showToast({
title: '定位失败',
icon: 'none'
});
}
});
},
phoneadddevice() {
// 验证分组信息
if (this.form.groupId === 'other' && !this.form.groupName) {
uni.showToast({
icon: 'none',
title: '请输入新分组名称'
});
return;
}
if (!this.form.groupId && !this.form.groupName) {
uni.showToast({
icon: 'none',
title: '请选择或输入分组'
});
return;
}
// 如果选择了"其他分组",先创建新分组
if (this.form.groupId === 'other') {
this.createNewGroup().then(newGroupId => {
if (newGroupId) {
this.form.groupId = newGroupId; // 使用新分组的ID
this.addDeviceToGroup(); // 添加设备并分组
} else {
uni.showToast({
icon: 'none',
title: '创建分组失败'
});
}
});
} else {
this.addDeviceToGroup(); // 直接添加设备并分组
}
},
// 创建新分组
async createNewGroup() {
try {
const newGroup = {
groupName: this.form.groupName
};
const res = await addGroup(newGroup); // 调用 addGroup API
if (res.code === 200) {
// 重新获取分组列表
await this.getGroupList();
// 从分组列表中查找新创建的分组
const newGroupItem = this.groupList.find(item => item.text === this.form.groupName);
if (newGroupItem) {
return newGroupItem.value; // 返回新分组的 ID
} else {
console.error('新分组未在分组列表中找到:', this.form.groupName);
return null;
}
} else {
console.error('API 返回错误:', res);
return null;
}
} catch (error) {
console.error('创建分组错误:', error);
return null;
}
},
// 添加设备并分组
addDeviceToGroup() {
addDevice(this.form).then(res => {
if (res.code === 200) {
const newDeviceId = parseInt(res.data.deviceId || res.data);
if (this.form.groupId && this.form.groupId !== 'other') {
const deviceGroup = {
groupId: this.form.groupId,
deviceIds: [newDeviceId]
};
updateDeviceGroups(deviceGroup).then(response => {
if (response.code === 200) {
uni.showToast({
icon: 'none',
title: '设备添加并分组成功'
});
} else {
uni.showToast({
icon: 'none',
title: '设备分组失败'
});
}
}).catch(error => {
console.error('分组更新错误:', error);
uni.showToast({
icon: 'none',
title: '设备分组失败'
});
});
} else {
uni.showToast({
icon: 'none',
title: '添加成功'
});
}
uni.reLaunch({
url: '/'
});
} else {
uni.showToast({
icon: 'none',
title: '添加失败,请重试'
});
}
}).catch(error => {
console.error(error);
uni.showToast({
icon: 'none',
title: '网络错误,请稍后再试'
});
});
},
getList() {
getProductList(this.queryParams)
.then(res => {
const {
rows,
total
} = res;
console.log(JSON.stringify(res))
// 将 productId 作为 valueproductName 作为 text
const productList = rows.map(item => ({
value: item.productId,
text: item.productName
}));
this.list = this.list.concat(productList); // 将新数据拼接到 list 中
this.total = total; // 更新总数
console.log(JSON.stringify(this.list)); // 打印 list 数据
})
.catch(err => {
console.log(err);
});
},
handleProductChange(selected) {
console.log('Selected Value:', selected)
const selectedItem = this.list.find(item => item.value === selected);
if (selectedItem) {
this.form.productName = selectedItem.text;
console.log('Product Name:', selectedItem.text);
} else {
console.log('Selected item not found in list.');
}
},
// 获取登录用户信息
getProfile() {
// 调用用户信息接口
getProfile().then(res => {
// 打印回复信息
console.log("Response:", JSON.stringify(res));
// 存储用户信息TODO 需要调用一次,不然其他页面调用返回空
console.log("Profile Data:", JSON.stringify(res.data));
uni.$u.vuex('profile', res.data);
// 更新 this.profile
this.profile = res.data;
// 设置用户ID
this.form.userId = this.profile.userId;
console.log("User ID:", this.profile.userId); // 打印出用户ID
}).catch(err => {
this.$u.toast(err.msg);
});
},
// 单击选显卡
tabClick(item) {
this.tabIndex = item.index;
if (this.tabIndex == 0) {
// 发现设备
this.discoverDevice();
} else {
// 清除发现设备定时器
clearInterval(this.discoverTimer);
}
},
// 返回
goBack() {
getApp().globalData.operate = 'operate';
uni.navigateBack({
delta: 1
});
},
// 扫码
// 扫码
openScan(item) {
// #ifndef MP-WEIXIN || APP-PLUS
uni.showToast({
icon: 'none',
title: this.$tt('user.scanning')
});
return;
// #endif
// 允许从相机和相册扫码
uni.scanCode({
success: res => {
console.log(JSON.stringify(regosu));
console.log('条码类型:' + res.scanType);
console.log('条码内容:' + res.result);
// if (res.result.substr(0, 1) != '{') {
// console.log('坑点:解析二维码后第一个位置包含一个特殊字符,大部分编译器和调试工具识别不了这个特殊字符');
// res.result = res.result.substring(1);
// }
// 解析JSON
try {
// 使用分号分割字符串并获取第一项
let resultArray = res.result.split(';');
this.form.serialNumber = resultArray[0]; // 取第一项赋值给serialNumber
// 显示成功提示
uni.showToast({
icon: 'none',
title: '扫码成功'
});
} catch (error) {
uni.showToast({
icon: 'none',
title: '解析二维码失败'
});
}
}
});
},
// 获取分组列表
async getGroupList() {
try {
// 创建查询参数
const query = {
pageNum: 1,
pageSize: 100 // 设置一个较大的数值以获取所有分组
};
const res = await getGroupList(query);
if (res.code === 200) {
// 转换数据格式为 uni-data-select 所需的格式
this.groupList = res.rows.map(item => ({
value: item.groupId,
text: item.groupName
}));
console.log('分组列表:', this.groupList); // 调试用
} else {
uni.showToast({
icon: 'none',
title: '获取分组列表失败'
});
}
} catch (error) {
console.error('获取分组列表错误:', error);
uni.showToast({
icon: 'none',
title: '获取分组列表失败'
});
}
},
// 处理分组选择变化
handleGroupChange(value) {
console.log('选择的值:', value); // 调试用
if (value === 'other') {
this.showCustomGroupInput = true;
this.form.groupId = '';
this.form.groupName = '';
} else {
this.showCustomGroupInput = false;
this.form.groupId = value;
const selectedGroup = this.groupList.find(item => item.value === value);
if (selectedGroup) {
this.form.groupName = selectedGroup.text;
}
}
},
// 处理分组名称输入
handleGroupNameInput(value) {
if (value) {
this.form.groupId = ''; // 清空选择的分组ID
}
},
},
};
</script>
<style lang="scss">
page {
// background: #eef3f7;
background: linear-gradient(30deg, #46e9a9 30%, #007aff 70%);
background-size: 100% 100%;
background-attachment: fixed;
}
.container {
padding-bottom: 50px;
}
.card {
box-shadow: 0 1px 0px 0 rgba(0, 0, 0, 0.1);
border-radius: 6px;
background-color: #fff;
margin: 10px;
margin-bottom: 15px;
padding: 15px 10px;
}
</style>