Files

40 lines
1.7 KiB
JavaScript

import { computed, onUnmounted, reactive } from 'vue'
import { onHide, onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
import { PAGE_PATHS } from '@/config/api'
import { fetchWechatNoticeStatus, startWechatBinding, fetchWechatBindingSession, confirmWechatBinding } from '@/api/wechat-notices'
import { createWechatBindingFlow, initialBindingState } from '@/utils/wechatBindingFlow'
export function useWechatBinding() {
const user = useUserStore()
const bindingState = reactive(initialBindingState())
let active = false
const bindingAccount = computed(() => user.userInfo?.realName || user.userInfo?.username || '当前登录账号')
const flow = createWechatBindingFlow({
state: bindingState,
getSessionKey: () => user.isLoggedIn ? user.token : '',
isActive: () => active,
api: { status: fetchWechatNoticeStatus, start: startWechatBinding, session: fetchWechatBindingSession, confirm: confirmWechatBinding },
openAuthorization: (authorizeUrl) => new Promise((resolve, reject) => {
uni.navigateTo({
url: PAGE_PATHS.wechatBindingAuthorize,
success: (result) => {
result.eventChannel.emit('wechatBindingAuthorize', { authorizeUrl })
resolve()
},
fail: () => reject(new Error('打开授权页面失败,请重新绑定'))
})
})
})
onShow(() => {
active = true
user.checkLoginStatus()
if (!user.isLoggedIn) { uni.reLaunch({ url: PAGE_PATHS.login }); return }
void flow.refresh()
})
const stop = () => { active = false; flow.cancel() }
onHide(stop)
onUnmounted(stop)
return { bindingState, bindingAccount, startBinding: flow.start, refreshBinding: flow.refresh }
}