| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import { computed } from 'vue'
- import { storeToRefs } from 'pinia'
- 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 { wallet } = useAuth()
- const { open: openTopupPopup } = useTopupPopup()
- const hasConfig = computed(() => items.value.length > 0)
- 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,
- })
- }
- return {
- // state
- loading,
- items,
- hasConfig,
- // actions
- ensureConfig,
- openRecharge,
- submitRecharge,
- }
- }
|