95 lines
2.7 KiB
JavaScript
95 lines
2.7 KiB
JavaScript
import { bindDeviceAPIV2 } from "@/apis";
|
|
|
|
export function useDeviceBinding({
|
|
token,
|
|
confirmBindTip,
|
|
binding,
|
|
updateDevice,
|
|
deviceDetails,
|
|
}) {
|
|
const showBindFailurePage = () => {
|
|
uni.hideToast();
|
|
uni.navigateTo({
|
|
url: "/pages/device/device-bind-failure",
|
|
fail: (error) => {
|
|
console.error("打开绑定失败页失败", error);
|
|
uni.showToast({ title: "二维码不正确,请重新扫码", icon: "none" });
|
|
},
|
|
});
|
|
};
|
|
|
|
const showAlreadyBoundPage = () => {
|
|
uni.navigateTo({
|
|
url: "/pages/device/device-already-bound",
|
|
fail: (error) => {
|
|
console.error("打开设备已绑定页失败", error);
|
|
uni.showToast({ title: "设备已绑定其他账号,请解绑后再绑定", icon: "none" });
|
|
},
|
|
});
|
|
};
|
|
|
|
const handleScan = () => {
|
|
uni.scanCode({
|
|
onlyFromCamera: true,
|
|
scanType: ["qrCode"],
|
|
success: (result) => {
|
|
if (!result?.result) {
|
|
showBindFailurePage();
|
|
return;
|
|
}
|
|
token.value = result.result;
|
|
confirmBindTip.value = true;
|
|
},
|
|
fail: (error) => {
|
|
const message = String(error?.errMsg || error?.message || "");
|
|
if (/cancel|取消/i.test(message)) return;
|
|
showBindFailurePage();
|
|
},
|
|
});
|
|
};
|
|
|
|
const confirmBind = async () => {
|
|
if (!token.value || binding.value) return;
|
|
binding.value = true;
|
|
try {
|
|
const result = await bindDeviceAPIV2(token.value);
|
|
confirmBindTip.value = false;
|
|
if (result?.binded) {
|
|
token.value = "";
|
|
showAlreadyBoundPage();
|
|
return;
|
|
}
|
|
const deviceId = String(result?.deviceId || "").trim();
|
|
const deviceName = String(result?.name || result?.deviceName || "").trim();
|
|
if (!deviceId || !deviceName) {
|
|
confirmBindTip.value = false;
|
|
token.value = "";
|
|
showBindFailurePage();
|
|
return;
|
|
}
|
|
const applyBoundDevice = () => {
|
|
updateDevice(deviceId, deviceName);
|
|
deviceDetails.value = result || {};
|
|
};
|
|
uni.navigateTo({
|
|
url: `/pages/device/device-bind-success?deviceId=${encodeURIComponent(deviceId)}`,
|
|
success: applyBoundDevice,
|
|
fail: (navigationError) => {
|
|
applyBoundDevice();
|
|
console.error("打开绑定成功页失败", navigationError);
|
|
uni.showToast({ title: "绑定成功,请返回查看设备", icon: "none" });
|
|
},
|
|
});
|
|
} catch (error) {
|
|
console.error("绑定设备失败", error);
|
|
confirmBindTip.value = false;
|
|
token.value = "";
|
|
showBindFailurePage();
|
|
} finally {
|
|
binding.value = false;
|
|
}
|
|
};
|
|
|
|
return { confirmBind, handleScan, showBindFailurePage };
|
|
}
|