代客下单

This commit is contained in:
磷叶 2026-06-02 16:54:54 +08:00
parent 7569e6d560
commit a199ab7d08
4 changed files with 1083 additions and 15 deletions

View File

@ -95,6 +95,17 @@
:display-deposit="displayDeposit"
@update:visible="priceDetailShow = $event"
/>
<BluetoothProcessPanel
:visible="btProcessVisible"
:progress="btProgress"
:step-message="btStepMessage"
:error-message="btErrorMessage"
:error-type="btErrorType"
@close="btProcessVisible = false"
@go-phone-setting="goPhoneBluetoothSetting"
@go-wechat-auth="openWechatBluetoothAuthSetting"
/>
</view>
</template>
@ -109,8 +120,11 @@ import DeviceSelectorPopup from './components/DeviceSelectorPopup.vue';
import InsuranceSelector from './components/InsuranceSelector.vue';
import PayChannelSelector from './components/PayChannelSelector.vue';
import PriceDetailPopup from './components/PriceDetailPopup.vue';
import BluetoothProcessPanel from './components/BluetoothProcessPanel.vue';
import merchantDeviceUnlockMixin from './mixins/merchantDeviceUnlockMixin.js';
export default {
mixins: [merchantDeviceUnlockMixin],
components: {
PackageSelector,
VehicleCard,
@ -120,7 +134,8 @@ import PriceDetailPopup from './components/PriceDetailPopup.vue';
DeviceSelectorPopup,
InsuranceSelector,
PayChannelSelector,
PriceDetailPopup
PriceDetailPopup,
BluetoothProcessPanel
},
data() {
return {
@ -226,9 +241,7 @@ import PriceDetailPopup from './components/PriceDetailPopup.vue';
this.pollPayResult(payNo)
return
}
this.submitting = false
uni.showToast({ title: '下单成功', icon: 'success', duration: 1500 })
setTimeout(() => { uni.navigateBack() }, 1500)
this.handlePaymentSuccess()
return
}
this.submitting = false
@ -549,9 +562,7 @@ import PriceDetailPopup from './components/PriceDetailPopup.vue';
const status = res && res.data ? res.data.status : ''
if (status === 'PAYED') {
uni.hideLoading()
this.submitting = false
uni.showToast({ title: '收款成功', icon: 'success', duration: 1500 })
setTimeout(() => { uni.navigateBack() }, 1500)
this.handlePaymentSuccess()
return
}
if (status === 'CANCELED' || status === 'REFUNDED') {
@ -657,21 +668,29 @@ import PriceDetailPopup from './components/PriceDetailPopup.vue';
}
this.$u.post('/bst/order/agentCreate', data).then(res => {
if (res.code === 200) {
const createResult = res.data || {}
if (createResult.needPay === false) {
uni.hideLoading()
this.handlePaymentSuccess()
return
}
if (isOfflinePay) {
uni.hideLoading()
this.submitting = false
this.handleOfflinePay(res.data || {})
this.handleOfflinePay(createResult)
return
}
const payNo = res.data && res.data.pay ? res.data.pay.no : ''
const payNo = createResult.pay ? createResult.pay.no : ''
if (payNo) {
uni.showLoading({ title: '等待支付结果...', mask: true })
this.pollPayResult(payNo)
} else {
} else if (createResult.needPay === true) {
uni.hideLoading()
this.submitting = false
uni.showToast({ title: '下单成功', icon: 'success', duration: 1500 })
setTimeout(() => { uni.navigateBack() }, 1500)
uni.showToast({ title: '支付单信息异常,请稍后在订单中查看', icon: 'none', duration: 2500 })
} else {
uni.hideLoading()
this.handlePaymentSuccess()
}
} else {
uni.hideLoading()
@ -684,6 +703,34 @@ import PriceDetailPopup from './components/PriceDetailPopup.vue';
uni.showToast({ title: '网络异常,请重试', icon: 'none', duration: 2000 })
})
},
handlePaymentSuccess() {
this.submitting = true
uni.showToast({ title: '收款成功', icon: 'success', duration: 1500 })
this.startAdminUnlockAfterPay({
deviceInfo: this.deviceInfo,
adminFinalStatus: '3',
onComplete: (success) => {
this.submitting = false
this.finishAgentOrderFlow(success)
}
})
},
finishAgentOrderFlow(unlockSuccess) {
if (unlockSuccess === false) {
uni.showModal({
title: '开锁未完成',
content: '支付已成功,但车辆开锁失败。请前往车辆详情页手动开锁。',
showCancel: false,
success: () => {
uni.navigateBack()
}
})
return
}
setTimeout(() => {
uni.navigateBack()
}, 1500)
},
handleOfflinePay(data) {
const applyNo = data.payParams && data.payParams.no ? String(data.payParams.no) : ''
const payNo = data.pay && data.pay.no ? String(data.pay.no) : ''

View File

@ -0,0 +1,504 @@
<template>
<view>
<u-mask :show="visible" :z-index="101" duration="0" />
<view v-if="visible" class="bt-process-panel" :class="{ 'bt-process-panel--error': !!errorMessage }">
<view class="bt-process-panel__accent"></view>
<view class="bt-process-panel__glow"></view>
<view class="bt-process-panel__inner">
<view class="bt-process-panel__visual" v-if="!errorMessage">
<view class="bt-process-panel__orbit">
<view class="bt-process-panel__ring bt-process-panel__ring--a"></view>
<view class="bt-process-panel__ring bt-process-panel__ring--b"></view>
<view class="bt-process-panel__sweep"></view>
<view class="bt-process-panel__core">
<image class="bt-process-panel__icon" src="https://api.ccttiot.com/smartmeter/img/static/uCdHjNaNfD9aikVg9Cuk" mode="aspectFit" />
</view>
</view>
</view>
<view class="bt-process-panel__visual bt-process-panel__visual--err" v-else>
<view class="bt-process-panel__core bt-process-panel__core--err">
<image class="bt-process-panel__icon" src="https://api.ccttiot.com/smartmeter/img/static/uCdHjNaNfD9aikVg9Cuk" mode="aspectFit" />
</view>
</view>
<view class="bt-process-panel__head">
<text class="bt-process-panel__title">{{ errorMessage ? '连接异常' : '蓝牙连接' }}</text>
<view class="bt-process-panel__status-pill">
<view class="bt-process-panel__status-dot"></view>
<text class="bt-process-panel__message">{{ stepMessage }}</text>
</view>
</view>
<view class="bt-process-panel__progress-card" v-if="!errorMessage">
<view class="bt-process-panel__progress-top">
<text class="bt-process-panel__progress-label">连接进度</text>
<view class="bt-process-panel__progress-num-wrap">
<text class="bt-process-panel__progress-num">{{ progress }}</text>
<text class="bt-process-panel__progress-unit">%</text>
</view>
</view>
<view class="bt-process-panel__progress-track">
<view class="bt-process-panel__progress-bar" :style="'width:' + progress + '%;'">
<view class="bt-process-panel__progress-shine"></view>
</view>
</view>
</view>
<view v-if="errorMessage" class="bt-process-panel__alert">
<view class="bt-process-panel__alert-icon">!</view>
<text class="bt-process-panel__alert-text">{{ errorMessage }}</text>
</view>
<view v-if="errorMessage" class="bt-process-panel__actions">
<view v-if="errorType === 'phone_bluetooth_off'" class="bt-process-panel__btn bt-process-panel__btn--accent" @click="$emit('go-phone-setting')">去设置</view>
<view v-if="errorType === 'wechat_auth_denied'" class="bt-process-panel__btn bt-process-panel__btn--accent" @click="$emit('go-wechat-auth')">去授权</view>
<view class="bt-process-panel__btn bt-process-panel__btn--main" @click="$emit('close')">我知道了</view>
</view>
<view v-if="errorMessage" class="bt-process-panel__hint">
<text class="bt-process-panel__hint-icon"></text>
<text>蓝牙操作中请靠近车辆</text>
</view>
</view>
</view>
</view>
</template>
<script>
export default {
name: 'BluetoothProcessPanel',
props: {
visible: {
type: Boolean,
default: false
},
progress: {
type: Number,
default: 0
},
stepMessage: {
type: String,
default: ''
},
errorMessage: {
type: String,
default: ''
},
errorType: {
type: String,
default: ''
}
}
}
</script>
<style lang="scss" scoped>
@keyframes bt-orbit-spin {
from { transform: translate(-50%, -50%) rotate(0deg); }
to { transform: translate(-50%, -50%) rotate(360deg); }
}
@keyframes bt-orbit-spin-rev {
from { transform: translate(-50%, -50%) rotate(360deg); }
to { transform: translate(-50%, -50%) rotate(0deg); }
}
@keyframes bt-sweep-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes bt-core-breathe {
0%, 100% {
box-shadow:
0 0 0 1rpx rgba(255, 255, 255, 0.8),
0 10rpx 32rpx rgba(46, 73, 117, 0.14);
}
50% {
box-shadow:
0 0 0 1rpx rgba(255, 255, 255, 1),
0 14rpx 40rpx rgba(76, 151, 231, 0.22);
}
}
@keyframes bt-progress-shine-move {
0% { left: -55%; }
100% { left: 130%; }
}
@keyframes bt-status-dot-blink {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.5; transform: scale(0.9); }
}
@keyframes bt-panel-enter {
0% {
opacity: 0;
transform: translate(-50%, -48%) scale(0.97);
}
100% {
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}
}
.bt-process-panel {
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 102;
width: 608rpx;
box-sizing: border-box;
overflow: hidden;
border-radius: 30rpx;
background: #ffffff;
border: 1rpx solid #e8ecf1;
box-shadow:
0 0 0 1rpx rgba(255, 255, 255, 0.6) inset,
0 20rpx 50rpx rgba(46, 73, 117, 0.1),
0 8rpx 24rpx rgba(46, 73, 117, 0.06);
animation: bt-panel-enter 0.38s cubic-bezier(0.22, 1, 0.36, 1) forwards;
}
.bt-process-panel__accent {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 6rpx;
background: linear-gradient(90deg, #2679d1 0%, #4c97e7 50%, #7eb8ff 100%);
pointer-events: none;
z-index: 4;
}
.bt-process-panel__glow {
position: absolute;
left: 50%;
top: 80rpx;
width: 320rpx;
height: 200rpx;
margin-left: -160rpx;
background: radial-gradient(ellipse at 50% 50%, rgba(76, 151, 231, 0.09) 0%, transparent 72%);
pointer-events: none;
}
.bt-process-panel__inner {
position: relative;
z-index: 2;
padding: 56rpx 48rpx 48rpx;
}
.bt-process-panel__visual {
display: flex;
justify-content: center;
margin-bottom: 44rpx;
}
.bt-process-panel__visual--err {
margin-bottom: 36rpx;
}
.bt-process-panel__orbit {
position: relative;
width: 216rpx;
height: 216rpx;
&::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
width: 216rpx;
height: 216rpx;
margin: -108rpx 0 0 -108rpx;
border-radius: 50%;
border: 1rpx solid rgba(46, 73, 117, 0.06);
box-sizing: border-box;
}
}
.bt-process-panel__ring {
position: absolute;
left: 50%;
top: 50%;
border-radius: 50%;
border: 2rpx solid transparent;
transform: translate(-50%, -50%);
}
.bt-process-panel__ring--a {
width: 208rpx;
height: 208rpx;
border-top-color: rgba(76, 151, 231, 0.45);
border-right-color: rgba(76, 151, 231, 0.08);
animation: bt-orbit-spin 4.8s linear infinite;
}
.bt-process-panel__ring--b {
width: 172rpx;
height: 172rpx;
border-top-color: rgba(38, 121, 209, 0.28);
border-left-color: rgba(38, 121, 209, 0.06);
animation: bt-orbit-spin-rev 3.8s linear infinite;
}
.bt-process-panel__sweep {
position: absolute;
left: 50%;
top: 50%;
width: 208rpx;
height: 208rpx;
margin: -104rpx 0 0 -104rpx;
border-radius: 50%;
background: conic-gradient(from 0deg, transparent 0deg, transparent 284deg, rgba(76, 151, 231, 0.05) 300deg, rgba(76, 151, 231, 0.18) 360deg);
animation: bt-sweep-spin 4.2s linear infinite;
}
.bt-process-panel__core {
position: absolute;
left: 50%;
top: 50%;
z-index: 3;
width: 108rpx;
height: 108rpx;
margin: -54rpx 0 0 -54rpx;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(160deg, #ffffff 15%, #e8f2fc 50%, #4c97e7 100%);
animation: bt-core-breathe 3.2s ease-in-out infinite;
}
.bt-process-panel__core--err {
position: relative;
left: auto;
top: auto;
margin: 0 auto;
background: linear-gradient(160deg, #ffffff 15%, #fceeee 55%, #e57373 100%);
animation: none;
box-shadow: 0 10rpx 32rpx rgba(180, 90, 90, 0.14);
}
.bt-process-panel__icon {
width: 48rpx;
height: 48rpx;
}
.bt-process-panel--error {
.bt-process-panel__accent {
background: linear-gradient(90deg, #c75c5c 0%, #e57373 50%, #f0a8a8 100%);
}
.bt-process-panel__glow {
background: radial-gradient(ellipse at 50% 50%, rgba(200, 100, 100, 0.08) 0%, transparent 72%);
}
.bt-process-panel__title {
color: #c75c5c;
}
.bt-process-panel__status-pill {
background: #fdf9f9;
border-color: #f5e0e0;
}
.bt-process-panel__status-dot {
background: #e57373;
}
.bt-process-panel__message {
color: #9a7070;
}
}
.bt-process-panel__head {
text-align: center;
margin-bottom: 0;
}
.bt-process-panel__title {
display: block;
font-size: 34rpx;
font-weight: 600;
color: #2e4975;
line-height: 1.35;
letter-spacing: 1rpx;
}
.bt-process-panel__status-pill {
display: inline-flex;
align-items: center;
justify-content: center;
max-width: 100%;
margin-top: 20rpx;
padding: 14rpx 28rpx;
background: #f7fafe;
border: 1rpx solid #e3ebf5;
border-radius: 999rpx;
box-sizing: border-box;
}
.bt-process-panel__status-dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
margin-right: 12rpx;
flex-shrink: 0;
background: #4c97e7;
animation: bt-status-dot-blink 2s ease-in-out infinite;
}
.bt-process-panel__message {
font-size: 26rpx;
font-weight: 400;
color: #7c7c7c;
line-height: 1.55;
}
.bt-process-panel__progress-card {
margin-top: 36rpx;
padding: 32rpx 30rpx 30rpx;
background: linear-gradient(180deg, #f7fafe 0%, #f3f6fa 100%);
border: 1rpx solid #e3ebf5;
border-radius: 20rpx;
}
.bt-process-panel__progress-top {
display: flex;
align-items: flex-end;
justify-content: space-between;
margin-bottom: 24rpx;
}
.bt-process-panel__progress-label {
font-size: 24rpx;
font-weight: 500;
color: #808080;
padding-bottom: 6rpx;
}
.bt-process-panel__progress-num-wrap {
display: flex;
align-items: baseline;
}
.bt-process-panel__progress-num {
font-size: 44rpx;
font-weight: 600;
color: #2e4975;
font-variant-numeric: tabular-nums;
line-height: 1;
}
.bt-process-panel__progress-unit {
margin-left: 6rpx;
font-size: 26rpx;
font-weight: 500;
color: #4c97e7;
}
.bt-process-panel__progress-track {
position: relative;
height: 10rpx;
background: #dce4ee;
border-radius: 999rpx;
overflow: hidden;
box-shadow: inset 0 1rpx 3rpx rgba(46, 73, 117, 0.08);
}
.bt-process-panel__progress-bar {
position: relative;
height: 100%;
min-width: 0;
border-radius: 999rpx;
background: linear-gradient(90deg, #7eb8ff 0%, #4c97e7 100%);
transition: width 0.42s cubic-bezier(0.22, 1, 0.36, 1);
overflow: hidden;
}
.bt-process-panel__progress-shine {
position: absolute;
top: 0;
bottom: 0;
width: 36%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.5), transparent);
animation: bt-progress-shine-move 2.6s ease-in-out infinite;
pointer-events: none;
}
.bt-process-panel__alert {
display: flex;
align-items: flex-start;
margin-top: 32rpx;
padding: 24rpx 22rpx;
background: #fdf9f9;
border: 1rpx solid #f5e0e0;
border-radius: 16rpx;
}
.bt-process-panel__alert-icon {
flex-shrink: 0;
width: 38rpx;
height: 38rpx;
margin-right: 14rpx;
border-radius: 50%;
background: #e57373;
color: #fff;
font-size: 24rpx;
font-weight: 600;
line-height: 38rpx;
text-align: center;
}
.bt-process-panel__alert-text {
flex: 1;
font-size: 26rpx;
color: #9a5a5a;
line-height: 1.6;
}
.bt-process-panel__actions {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 20rpx;
margin-top: 32rpx;
}
.bt-process-panel__btn {
min-width: 200rpx;
height: 76rpx;
line-height: 76rpx;
padding: 0 40rpx;
text-align: center;
border-radius: 8rpx;
font-size: 28rpx;
font-weight: 500;
color: #fff;
box-sizing: border-box;
}
.bt-process-panel__btn--accent {
background: #5a9a6b;
box-shadow: 0 6rpx 18rpx rgba(90, 154, 107, 0.22);
}
.bt-process-panel__btn--main {
background: #4c97e7;
box-shadow: 0 8rpx 22rpx rgba(76, 151, 231, 0.28);
}
.bt-process-panel__hint {
display: flex;
align-items: center;
justify-content: center;
margin-top: 24rpx;
padding: 0;
font-size: 22rpx;
color: #ababab;
line-height: 1.5;
}
.bt-process-panel__hint-icon {
margin-right: 8rpx;
font-size: 24rpx;
color: #b0b0b0;
}
</style>

View File

@ -241,7 +241,7 @@
</view>
<view class="dangeanniu" @click="toAgentOrder()">
<view class="pic">
<image src="https://api.ccttiot.com/smartmeter/img/static/um8ShZ4cBnh0weV1Qtz3" mode=""></image>
<image src="https://api.ccttiot.com/%E4%BB%A3%E7%90%86%E4%B8%8B%E5%8D%95-1780390380377.png" mode=""></image>
</view>
代客下单
</view>
@ -459,8 +459,7 @@
</template>
<script>
import { showLoading } from "../../components/blufi/util"
const app = getApp()
const app = getApp()
var xBlufi = require("@/components/blufi/xBlufi.js")
let _this = null
export default {

View File

@ -0,0 +1,518 @@
var xBlufi = require('@/components/blufi/xBlufi.js')
/** 设备状态:骑行中 */
var ADMIN_FINAL_STATUS_IN_USE = '3'
export default {
data() {
return {
unlockDeviceId: '',
unlockSn: '',
mac: '',
adminFinalStatus: ADMIN_FINAL_STATUS_IN_USE,
ver_dataflag: 1,
deviceid: '',
devicename: '',
devicesarr: [],
findDeviceTimer: null,
jieliuflag: true,
jiance: false,
shibainum: 0,
lat: null,
lon: null,
btProcessVisible: false,
btProgress: 0,
btStepMessage: '',
btErrorMessage: '',
btErrorType: '',
btAdapterAvailable: null
}
},
onUnload() {
this.clearUnlockRuntimeState()
},
onHide() {
if (!this.pendingOfflineAudit) {
this.clearUnlockRuntimeState()
}
},
methods: {
initBluetoothStack() {
xBlufi.initXBlufi(1)
xBlufi.notifyStartDiscoverBle({ isStart: true })
xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent)
this.bindBluetoothAdapterStateChange()
},
clearUnlockRuntimeState() {
const oldDeviceId = this.deviceid
const oldDeviceName = this.devicename
this.unbindBluetoothAdapterStateChange()
try {
uni.hideLoading()
} catch (e) {}
this.btProcessVisible = false
this.btProgress = 0
this.btStepMessage = ''
this.btErrorMessage = ''
this.btErrorType = ''
this.shibainum = 0
this.ver_dataflag = 1
this.jieliuflag = true
this.jiance = false
this.btAdapterAvailable = null
if (this.findDeviceTimer) {
clearTimeout(this.findDeviceTimer)
this.findDeviceTimer = null
}
try {
xBlufi.notifyConnectBle({
isStart: false,
deviceId: oldDeviceId,
name: oldDeviceName
})
xBlufi.notifyStartDiscoverBle({ isStart: false })
xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent)
} catch (e) {}
this.deviceid = ''
this.devicename = ''
this.devicesarr = []
},
bindBluetoothAdapterStateChange() {
if (!uni.onBluetoothAdapterStateChange) {
return
}
if (uni.offBluetoothAdapterStateChange) {
try {
uni.offBluetoothAdapterStateChange(this.handleBluetoothAdapterStateChange)
} catch (e) {}
}
uni.onBluetoothAdapterStateChange(this.handleBluetoothAdapterStateChange)
},
unbindBluetoothAdapterStateChange() {
if (!uni.offBluetoothAdapterStateChange) {
return
}
try {
uni.offBluetoothAdapterStateChange(this.handleBluetoothAdapterStateChange)
} catch (e) {}
},
handleBluetoothAdapterStateChange(res) {
const available = !!(res && res.available)
if (available) {
this.btAdapterAvailable = true
return
}
const wasAvailable = this.btAdapterAvailable
this.btAdapterAvailable = false
this.ver_dataflag = 1
this.shibainum = 0
this.deviceid = ''
this.devicename = ''
if (this.btProcessVisible) {
this.showBtStepError('手机蓝牙未开启,请去系统设置打开', 'phone_bluetooth_off')
}
if (wasAvailable !== false) {
this.ver_dataflag = 1
uni.showToast({
title: '检测到手机蓝牙已关闭,连接已断开',
icon: 'none',
duration: 2000
})
}
},
resetBtProcessUI() {
this.btProcessVisible = true
this.btProgress = 0
this.btStepMessage = '准备开始蓝牙自检'
this.btErrorMessage = ''
this.btErrorType = ''
},
setBtProgress(stage) {
if (stage === 'scan') {
this.btProgress = 50
this.btStepMessage = '正在搜索设备...'
} else if (stage === 'connect') {
this.btProgress = 80
this.btStepMessage = '已搜索到设备,正在建立蓝牙连接...'
} else if (stage === 'send') {
this.btProgress = 100
this.btStepMessage = '蓝牙已连接,正在发送命令...'
}
},
showBtStepError(message, type) {
this.btErrorMessage = message
this.btErrorType = type || ''
this.btStepMessage = '蓝牙自检未通过'
this.ver_dataflag = 1
this.shibainum = 0
this.jieliuflag = true
},
openWechatBluetoothAuthSetting() {
uni.openSetting({
success: () => {},
fail: () => {
uni.showToast({
title: '请在微信设置中开启蓝牙权限',
icon: 'none',
duration: 2000
})
}
})
},
goPhoneBluetoothSetting() {
// #ifdef MP-WEIXIN
if (typeof wx !== 'undefined' && wx.openSystemBluetoothSetting) {
wx.openSystemBluetoothSetting({
success: () => {},
fail: () => {
uni.showToast({
title: '无法直接跳转,请手动打开手机蓝牙',
icon: 'none',
duration: 2000
})
}
})
return
}
// #endif
uni.showToast({
title: '请手动进入系统设置打开蓝牙',
icon: 'none',
duration: 2000
})
},
waitForCondition(checker, timeout, interval) {
timeout = timeout || 6000
interval = interval || 250
return new Promise((resolve) => {
const start = Date.now()
const timer = setInterval(() => {
if (checker()) {
clearInterval(timer)
resolve(true)
return
}
if (Date.now() - start >= timeout) {
clearInterval(timer)
resolve(false)
}
}, interval)
})
},
sleep(ms) {
ms = ms || 300
return new Promise((resolve) => setTimeout(resolve, ms))
},
async connectMatchedDeviceWithRetry(matchedDevice, maxRetry) {
maxRetry = maxRetry || 3
for (let attempt = 1; attempt <= maxRetry; attempt++) {
this.btStepMessage = '已搜索到设备,正在连接...(第' + attempt + '/' + maxRetry + '次)'
this.ver_dataflag = 2
try {
if (this.deviceid) {
xBlufi.notifyConnectBle({
isStart: false,
deviceId: this.deviceid,
name: this.devicename || matchedDevice.name
})
await this.sleep(250)
}
} catch (e) {}
xBlufi.notifyConnectBle({
isStart: true,
deviceId: matchedDevice.deviceId,
name: matchedDevice.name
})
this.deviceid = matchedDevice.deviceId
this.devicename = matchedDevice.name
const connected = await this.waitForCondition(() => this.ver_dataflag === 3, 12000, 300)
if (connected) {
return true
}
const recheckConnected = await this.waitForCondition(() => this.ver_dataflag === 3, 2000, 200)
if (recheckConnected) {
return true
}
if (attempt < maxRetry) {
await this.sleep(500)
}
}
return false
},
safeIotPut(url, data, timeoutMs) {
timeoutMs = timeoutMs || 12000
const reqPromise = this.$u.put(url, data).catch(() => ({
code: 500,
msg: '网络异常,请稍后重试'
}))
const timeoutPromise = new Promise((resolve) => {
setTimeout(() => {
resolve({ code: 20003, msg: '请求超时' })
}, timeoutMs)
})
return Promise.race([reqPromise, timeoutPromise])
},
_isIotTimeoutLike(res) {
return !!(res && (res.code == 20001 || res.code == 20002 || res.code == 20003))
},
iotRequestTwiceBeforeBle(url, data) {
return this.safeIotPut(url, data).then((res) => {
if (res && res.code == 200) {
return { type: 'success', res: res }
}
if (this._isIotTimeoutLike(res)) {
return this.safeIotPut(url, data).then((res2) => {
if (res2 && res2.code == 200) {
return { type: 'success', res: res2 }
}
if (this._isIotTimeoutLike(res2)) {
return { type: 'ble' }
}
return { type: 'error', res: res2 }
})
}
return { type: 'error', res: res }
})
},
openBtAdapter() {
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
success: () => resolve(true),
fail: (err) => reject(err || {})
})
})
},
getBtAuthState() {
return new Promise((resolve) => {
uni.getSetting({
success: (res) => {
const authSetting = (res && res.authSetting) || {}
resolve(authSetting['scope.bluetooth'])
},
fail: () => resolve(undefined)
})
})
},
authorizeBt() {
return new Promise((resolve) => {
uni.authorize({
scope: 'scope.bluetooth',
success: () => resolve(true),
fail: () => resolve(false)
})
})
},
async runPreciseBluetoothSelfCheck() {
this.resetBtProcessUI()
try {
await this.openBtAdapter()
} catch (err) {
const errMsg = (err && err.errMsg) || ''
if (errMsg.indexOf('auth deny') > -1 || errMsg.indexOf('authorize no response') > -1) {
this.showBtStepError('微信蓝牙未授权,请去微信授权', 'wechat_auth_denied')
} else {
this.showBtStepError('手机蓝牙未开启,请去系统设置打开', 'phone_bluetooth_off')
}
return { ok: false, step: 1 }
}
let authState = await this.getBtAuthState()
if (authState === false) {
this.showBtStepError('微信蓝牙未授权,请去微信授权', 'wechat_auth_denied')
return { ok: false, step: 2 }
}
if (typeof authState === 'undefined') {
const authorized = await this.authorizeBt()
if (!authorized) {
this.showBtStepError('微信蓝牙未授权,请去微信授权', 'wechat_auth_denied')
return { ok: false, step: 2 }
}
}
this.setBtProgress('scan')
xBlufi.notifyStartDiscoverBle({ isStart: true })
const found = await this.waitForCondition(() => {
return this.devicesarr.some((device) => {
const name = (device && device.name) || ''
const mac = this.mac || ''
return name && mac && name.slice(-12) === mac.slice(-12)
})
}, 8000, 400)
if (!found) {
this.showBtStepError('未搜索到目标设备,请检查设备是否开机', 'device_not_found')
return { ok: false, step: 3 }
}
const matchedDevice = this.devicesarr.find((device) => {
const name = (device && device.name) || ''
const mac = this.mac || ''
return name && mac && name.slice(-12) === mac.slice(-12)
})
if (!matchedDevice) {
this.showBtStepError('未搜索到目标设备,请检查设备是否开机', 'device_not_found')
return { ok: false, step: 3 }
}
this.setBtProgress('connect')
xBlufi.notifyStartDiscoverBle({ isStart: false })
const connected = await this.connectMatchedDeviceWithRetry(matchedDevice, 3)
if (!connected) {
this.showBtStepError('已找到设备,但连接失败,请重试', 'connect_failed')
return { ok: false, step: 4 }
}
this.btStepMessage = '蓝牙已连接,正在准备发送命令...'
await this.sleep(2000)
this.setBtProgress('send')
return { ok: true }
},
_buildUnlockPayload(overrides) {
overrides = overrides || {}
const macList = this.devicesarr.map((item) => (item.name || '').slice(-12)).filter(Boolean)
return {
id: this.unlockDeviceId,
requiredIot: true,
lat: this.lat,
lon: this.lon,
macList: macList,
sendIot: overrides.sendIot !== undefined ? overrides.sendIot : true,
adminFinalStatus: String(this.adminFinalStatus)
}
},
_merchantUnlockBluetoothSequence(onComplete) {
uni.hideLoading()
this.runPreciseBluetoothSelfCheck().then((checkRes) => {
if (!checkRes.ok) {
if (onComplete) {
onComplete(false)
}
return
}
setTimeout(() => {
xBlufi.notifySendCustomData({ customData: '11opensub5@' })
this.btProcessVisible = false
this.jieliuflag = true
}, 1000)
const datas = this._buildUnlockPayload({ sendIot: false })
this.safeIotPut('/bst/device/iot/unlock', datas).then((res) => {
if (res.code == 200) {
uni.showToast({ title: '开锁成功', icon: 'success', duration: 1500 })
const logData = {
mac: this.mac,
reason: '代客下单开锁',
command: '11opensub5@',
longitude: this.lon,
latitude: this.lat,
result: '成功'
}
this.$u.post('/app/commandLog/bluetooth', logData).then(() => {})
if (onComplete) {
onComplete(true)
}
} else {
uni.showToast({
title: res.msg || '蓝牙开锁失败',
icon: 'none',
duration: 2500
})
if (onComplete) {
onComplete(false)
}
}
})
}).catch(() => {
this.showBtStepError('已找到设备,但连接失败,请重试', 'connect_failed')
if (onComplete) {
onComplete(false)
}
})
},
_doAdminIotUnlock(onComplete) {
const payload = this._buildUnlockPayload()
this.iotRequestTwiceBeforeBle('/bst/device/iot/unlock', payload).then((out) => {
if (out.type === 'ble') {
this._merchantUnlockBluetoothSequence(onComplete)
return
}
if (out.type === 'error') {
this._merchantUnlockBluetoothSequence(onComplete)
return
}
const res = out.res
if (res.data && res.data.db == 1 && res.data.iot === false) {
this._merchantUnlockBluetoothSequence(onComplete)
return
}
uni.hideLoading()
uni.showToast({ title: '开锁成功', icon: 'success', duration: 1500 })
if (onComplete) {
onComplete(true)
}
})
},
startAdminUnlockAfterPay(options) {
options = options || {}
const deviceInfo = options.deviceInfo || this.deviceInfo
const onComplete = options.onComplete
const adminFinalStatus = options.adminFinalStatus || ADMIN_FINAL_STATUS_IN_USE
if (!deviceInfo || (deviceInfo.id == null && !this.deviceId)) {
uni.showToast({ title: '车辆信息异常,无法开锁', icon: 'none', duration: 2500 })
if (onComplete) {
onComplete(false)
}
return
}
this.unlockDeviceId = deviceInfo.id != null ? deviceInfo.id : this.deviceId
this.unlockSn = deviceInfo.sn || ''
this.mac = deviceInfo.mac || ''
this.adminFinalStatus = adminFinalStatus
this.initBluetoothStack()
uni.showLoading({ title: '车辆开锁中...', mask: true })
uni.getLocation({
type: 'gcj02',
isHighAccuracy: true,
success: (res) => {
this.lat = res.latitude
this.lon = res.longitude
this._doAdminIotUnlock(onComplete)
},
fail: () => {
this.lat = null
this.lon = null
this._doAdminIotUnlock(onComplete)
}
})
},
funListenDeviceMsgEvent(options) {
switch (options.type) {
case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
if (!options.result) {
this.ver_dataflag = 1
this.deviceid = ''
this.devicename = ''
}
break
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
if (options.result) {
this.devicesarr = options.data
}
break
case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
if (options.result === true) {
this.ver_dataflag = 3
this.jiance = false
xBlufi.notifyInitBleEsp32({ deviceId: this.deviceid })
this.deviceid = options.data && options.data.deviceId ? options.data.deviceId : this.deviceid
}
break
case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
this.ver_dataflag = 3
this.jiance = false
break
case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
if (!options.result) {
this.jiance = true
}
break
}
}
}
}