| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247 |
- import { computed, onBeforeUnmount } from 'vue'
- import { storeToRefs } from 'pinia'
- import { closeToast, showLoadingToast } from 'vant'
- import { useWalletRechargeStore } from '~/stores/walletRecharge'
- import { walletApi } from '~/api/wallet'
- import { useAuth } from './useAuth'
- import { useTopupPopup } from './useTopupPopup'
- import { formatNumber } from '~/utils/helpers'
- // 充值流程组合式函数
- // - 从后端加载充值配置并缓存在 Pinia
- // - 把后端字段映射到 Topup 弹窗所需的档位结构
- // - 统一通过 useTopupPopup 打开充值弹窗
- export const useRecharge = () => {
- const walletRechargeStore = useWalletRechargeStore()
- const { items, loading } = storeToRefs(walletRechargeStore)
- const route = useRoute()
- const router = useRouter()
- const { t } = useI18n()
- const { wallet, refreshUser } = useAuth()
- const { open: openTopupPopup } = useTopupPopup()
- const { handleTopupOpen: handlePaybackResultTopupOpen } = usePaybackResultPopup()
- const hasConfig = computed(() => items.value.length > 0)
- let topupPollTimer: ReturnType<typeof setInterval> | null = null
- const stopTopupPolling = () => {
- if (topupPollTimer) {
- clearInterval(topupPollTimer)
- topupPollTimer = null
- }
- }
- onBeforeUnmount(() => {
- stopTopupPolling()
- })
- const ensureConfig = async (force = false) => {
- if (!force && walletRechargeStore.initialized && items.value.length > 0)
- return
- await walletRechargeStore.loadConfig(force)
- }
- /**
- * 提交充值并打开收银台页面
- * - 将选中的 package.id 传给后端
- * - 使用返回的 result 字符串作为收银台链接新开页面
- */
- const submitRecharge = async (packageId: string | number, redirect?: string) => {
- const id = String(packageId)
- try {
- const res = await walletApi.submitRecharge(id, redirect || '')
- const url = res?.result
- if (!url) {
- console.error('Recharge submit response has no result url')
- return
- }
- if (import.meta.client) {
- window.location.href = url
- }
- }
- catch (error) {
- console.error('Failed to submit wallet recharge:', error)
- }
- }
- /**
- * 打开充值弹窗:
- * - 确保已经加载充值配置
- * - 按照 Topup 弹窗要求的结构构建档位数据
- */
- const openRecharge = async () => {
- await ensureConfig()
- const configItems = items.value
- if (!configItems || configItems.length === 0) {
- console.warn('Wallet recharge config is empty')
- return
- }
- const balance = wallet.value?.goldCoin ?? 0
- const packages = configItems.map(item => ({
- id: item.id,
- coins: item.coinRechargeAmount,
- priceLabel: formatNumber(item.amount),
- }))
- // 支付方式目前前端写死;如果后端后续下发支付方式,可以从接口映射
- const methods = [
- { id: 'dukpay', name: 'DukPay', icon: '/vendor/dukpay-logo.png' },
- ]
- openTopupPopup({
- balance,
- packages,
- methods,
- defaultPackageId: packages[0]?.id,
- defaultMethodId: methods[0]?.id,
- })
- }
- const normalizeCreateTime = (value: number) => {
- // Backend docs say int64 timestamp; some envs may return seconds.
- if (!value) return 0
- return value < 1e12 ? value * 1000 : value
- }
- const finalizeTopupResult = (success: boolean, coins: number) => {
- stopTopupPolling()
- closeToast()
- handlePaybackResultTopupOpen({
- status: success,
- coins,
- })
- refreshUser()
- }
- const startTopupPolling = async (orderNo: string, coins: number) => {
- stopTopupPolling()
- let finished = false
- let inFlight = false
- const requestOnce = async () => {
- try {
- return await walletApi.checkRechargeOrderState(orderNo)
- }
- catch (error) {
- console.error('Failed to check recharge order state:', error)
- return null
- }
- }
- const first = await requestOnce()
- if (!first) return
- if (first.status === 2) {
- finalizeTopupResult(true, coins)
- return
- }
- if (first.status === 0 || first.status === 3 || first.status === 4) {
- finalizeTopupResult(false, coins)
- return
- }
- // status === 1 => start polling
- const createTime = normalizeCreateTime(first.createTime)
- const deadline = (createTime || Date.now()) + 30 * 1000
- const tick = async () => {
- if (finished || inFlight) return
- inFlight = true
- try {
- if (Date.now() >= deadline) {
- finished = true
- finalizeTopupResult(false, coins)
- return
- }
- const res = await requestOnce()
- if (!res) return
- if (res.status === 2) {
- finished = true
- finalizeTopupResult(true, coins)
- }
- else if (res.status === 0 || res.status === 3 || res.status === 4) {
- finished = true
- finalizeTopupResult(false, coins)
- }
- }
- finally {
- inFlight = false
- }
- }
- // Poll every 1 seconds for up to 30 seconds from createTime.
- topupPollTimer = setInterval(() => {
- void tick()
- }, 1 * 1000)
- }
- const handleTopupResult = (rechargeData: string) => {
- try {
- const rechargeStr = window.atob(rechargeData)
- const rechargeJson = JSON.parse(rechargeStr)
- const query = { ...route.query }
- delete query.rechargeCallback
- router.replace({
- path: route.path,
- query,
- })
- if (rechargeJson.loopState && rechargeJson.orderNo) {
- const orderNo = rechargeJson.orderNo
- const coins = rechargeJson.coinRechargeAmount || 0
- showLoadingToast({
- message: t('payback.titles.topupPending'),
- duration: 30 * 1000,
- forbidClick: true,
- })
- void startTopupPolling(orderNo, coins)
- }
- else {
- handlePaybackResultTopupOpen({
- status: rechargeJson.status,
- coins: rechargeJson.coinRechargeAmount || 0,
- })
- refreshUser()
- }
- }
- catch (error) {
- console.error('Failed to parse recharge data:', error)
- }
- }
- const handleRechargeCallback = () => {
- const rechargeCallback = route.query.rechargeCallback as string | undefined
- if (rechargeCallback) {
- handleTopupResult(rechargeCallback)
- }
- }
- return {
- // state
- loading,
- items,
- hasConfig,
- // actions
- ensureConfig,
- openRecharge,
- submitRecharge,
- handleRechargeCallback,
- }
- }
|