Files
bodyWeight/components/configureDevice_2/configureDevice_2.js
T

309 lines
12 KiB
JavaScript

const app = getApp();
import $ from "../../utils/request";
/**
* 根据生日计算年龄
* @param {string} birthday 生日字符串,如 "1990-05-20"
* @returns {number|null} 年龄,无法计算时返回 null
*/
function calcAge(birthday) {
if (!birthday) return null;
let birthDate = new Date(birthday.replace(/-/g, '/'));
if (isNaN(birthDate.getTime())) return null;
let today = new Date();
let age = today.getFullYear() - birthDate.getFullYear();
let monthDiff = today.getMonth() - birthDate.getMonth();
// 未过生日则减一岁
if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Component({
data: {
BLUE_STATE: {},
device: null,
connectState: "",
userList: [],
},
// 存储回调函数的引用,以便在 detached 时取消监听
_connectStateWatcher: null,
lifetimes: {
attached() {
console.log(`[Component] connectState 获取: ${app.globalData.ppScale.device.connectState}`);
this.setData({
BLUE_STATE: app.globalData.ppScale.plugin.BLUE_STATE,
connectState: app.globalData.ppScale.device.connectState,
device: app.globalData.ppScale.device.connection
})
this._connectStateWatcher = (newValue, oldValue) => {
console.log(`[Component] connectState 变化: ${oldValue} -> ${newValue}`);
this.setData({
connectState: newValue || ''
});
};
app.watch('ppScale.device.connectState', this._connectStateWatcher);
this.fetchUserList();
},
detached() {
if (this._connectStateWatcher) {
app.unwatch('ppScale.device.connectState', this._connectStateWatcher);
}
}
},
// 组件的方法
methods: {
// 长按型号区域初始化设备
onDeviceLongPress() {
wx.showModal({
title: "提示",
content: "确定要初始化设备吗?将清除设备中的所有数据(用户信息、历史数据、配网数据、设置信息)。",
success: (res) => {
if (res.confirm) {
if (!app.globalData.ppScale.activeProtocol) {
wx.showToast({ title: "设备未连接,请重试", icon: "none" });
return;
}
wx.showLoading({ title: "正在初始化设备...", mask: true });
app.globalData.ppScale.activeProtocol.codeClearDeviceData("00", (status) => {
wx.hideLoading();
if (status == 0) {
wx.showToast({ title: "设备初始化成功", icon: "success" });
// 断开蓝牙连接并返回上一页
app.globalData.ppScale.plugin.Blue.stop();
setTimeout(() => {
wx.navigateBack({ delta: 1 });
}, 1500);
} else {
wx.showToast({ title: "设备初始化失败,请重试", icon: "none" });
}
});
}
}
});
},
// 手动重连设备
connectedDevice() {
app.resetReconnectCount();
this.triggerEvent('connectedDeviceEvent', {
device: this.data.device
});
},
addUser() {
if (this.data.userList.length >= 10) {
wx.showToast({
title: "超过最大用户数",
icon: "none"
});
return;
}
// 列表为空时,第一个用户只能是员工(主用户)
const isFirstUser = this.data.userList.length === 0;
this.selectComponent("#configureDevice2AddUser").showModal(isFirstUser);
},
getAddUserInfo() {
this.fetchUserList();
},
// 获取设备绑定的用户列表
fetchUserList() {
if (!app.globalData.ppScale.device.mac) {
wx.showToast({ title: '设备 MAC 地址为空,请重新连接', icon: 'none' });
return;
}
let sn = app.globalData.ppScale.device.mac.replace(/:/g, '');
$.ajax("weighingScale/v2/select/user", { sn }, "GET", true, "正在获取用户列表...").then(res => {
if (res.result && res.result.length) {
let list = res.result.map(user => {
// 没有 age 时通过 birthday 计算
if (!user.age && user.birthday) {
user.age = calcAge(user.birthday);
}
return user;
});
this.setData({ userList: list });
} else {
this.setData({ userList: [] });
}
}).catch(() => {
wx.showToast({
title: "用户列表获取失败",
icon: "none"
})
})
},
// 删除用户
delUserClick(e) {
let id = e.currentTarget.dataset.id;
const userList = this.data.userList;
const target = userList.find(u => u.id === id);
// 主用户(userType=1)有子用户时不允许删除
if (target && target.userType === 1) {
const hasSubUser = userList.some(u => u.userType === 0);
if (hasSubUser) {
wx.showToast({ title: "请先删除所有普通用户", icon: "none" });
return;
}
}
wx.showModal({
title: "提示",
content: "确定要删除该用户吗?",
success: (res) => {
if (res.confirm) {
$.ajax("weighingScale/v2/del/user", { id }, "DELETE", true, "正在删除...", "application/x-www-form-urlencoded").then(() => {
wx.showToast({
title: "删除成功",
icon: "success"
})
setTimeout(() => {
this.fetchUserList();
}, 1500)
}).catch(() => {
wx.showToast({
title: "删除失败,请重试",
icon: "none"
})
})
}
}
})
},
setUserInfo() {
if (this.data.connectState != this.data.BLUE_STATE.CONNECTSUCCESS && this.data.connectState != this.data.BLUE_STATE.WIFISUCCESS) {
wx.showToast({
title: "设备连接失败,请重试。",
icon: "none"
})
return;
}
let userList = this.data.userList;
if (!userList.length) {
wx.showToast({
title: "暂无用户信息,请先添加用户",
icon: "none"
})
return;
}
// 找出主用户,所有用户下发时 userID 统一使用主用户的 userId
const mainUser = userList.find(u => u.userType === 1);
if (!mainUser) {
wx.showToast({ title: "未找到主用户,请先添加员工用户", icon: "none" });
return;
}
const mainUserId = mainUser.userId;
wx.showLoading({ title: "正在同步用户数据...", mask: true });
// 第一步:清除秤上所有用户信息
app.globalData.ppScale.activeProtocol.codeClearDeviceData("01", (clearRes) => {
console.log("codeClearDeviceData res", clearRes);
if (clearRes !== 0x00) {
wx.hideLoading();
wx.showToast({ title: "同步用户失败,请重试", icon: "none" });
return;
}
// 第二步:全量下发本地用户列表
let syncIndex = 0;
let syncTimer = null;
// 清除超时定时器
const clearSyncTimer = () => {
if (syncTimer) {
clearTimeout(syncTimer);
syncTimer = null;
}
};
// 重置超时定时器,10秒无响应则认定失败
const resetSyncTimer = () => {
clearSyncTimer();
syncTimer = setTimeout(() => {
console.log("dataSyncUserInfo 超时,第" + (syncIndex + 1) + "个用户下发超时");
wx.hideLoading();
wx.showToast({ title: "用户信息下发超时,请重试", icon: "none" });
}, 15000);
};
const syncNext = () => {
if (syncIndex >= userList.length) {
// 全部下发完成,清除定时器
clearSyncTimer();
wx.hideLoading();
wx.showToast({ title: "用户信息同步成功", icon: "success" });
setTimeout(() => {
this._checkWifiAndNext();
}, 1500);
return;
}
const user = userList[syncIndex];
// 主用户 memberID 为空,子用户 memberID 为子用户自己的 userId
const memberID = user.userId === mainUserId ? "" : user.userId;
wx.showLoading({ title: "正在下发第" + (syncIndex + 1) + "/" + userList.length + "个用户...", mask: true });
// 每次下发前重置10秒超时定时器
resetSyncTimer();
app.globalData.ppScale.activeProtocol.dataSyncUserInfo({
userID: mainUserId,
userName: user.realname,
memberID: memberID,
age: user.age || '',
gender: user.sex === 2 ? 0 : user.sex,
height: user.height || '',
isAthleteMode: 0,
deviceHeaderIndex: syncIndex,
currentWeight: user.weight || '',
targetWeight: "",
idealWeight: "",
recentData: [],
}, (res) => {
console.log("dataSyncUserInfo res", res, "user:", user.realname, "userID:", mainUserId, "memberID:", memberID);
if (res == 0) {
// 成功:重置定时器,继续下发下一个用户
resetSyncTimer();
syncIndex++;
syncNext();
} else {
// 失败自动重试当前用户,重置定时器
resetSyncTimer();
syncNext();
}
});
};
syncNext();
});
},
/**
* 同步完成后检测配网状态,决定跳转到哪一步
* 已配网(0x01) → progressIndex: 3,跳过配网步骤
* 未配网 → progressIndex: 2,进入配网步骤
*/
_checkWifiAndNext() {
wx.showLoading({ title: "正在检测配网状态...", mask: true });
app.globalData.ppScale.activeProtocol.codeFetchWifiConfig((res) => {
wx.hideLoading();
if (res === undefined || res === null) {
// 获取失败,自动重试
this._checkWifiAndNext();
return;
}
// 0x01 表示已配网,跳过配网步骤直接进入下一步
const progressIndex = res === 0x01 ? 3 : 2;
this.triggerEvent('deviceEvent', { status: true, progressIndex });
});
},
}
});