import { computed, inject, provide, ref, watch, type InjectionKey } from 'vue' import { useRoute } from 'vue-router' import router from '@/router' import { loading } from '@/utils' import { getFundTransactionTable } from '@/api/fund' import { getOneProductWallet } from '@/api/products' import type { Product } from '@/models/products' import type { TableInput, TableOutput } from '@/models/table' import type { Transaction } from '@/models/transaction' export interface FundInfoPageContext { info: ReturnType> items: ReturnType> infoId: ReturnType> goBack: () => void } export const FUND_INFO_PAGE_KEY: InjectionKey = Symbol('fundInfoPage') function parseRouteProductId(raw: string | string[] | undefined): number | null { const value = Array.isArray(raw) ? raw[0] : raw if (value == null || value === '') return null const id = Number.parseInt(String(value), 10) return Number.isFinite(id) && id > 0 ? id : null } export function useFundInfoPage() { const route = useRoute() const info = ref() const items = ref([]) const tableOutput = ref | null>(null) const pagination = ref({}) const infoId = computed(() => parseRouteProductId(route.params.id)) async function initTable() { if (!info.value?.wallet?.id) return try { loading.value = true items.value = [] Object.assign(pagination.value, { wallet_id: info.value.wallet.id }) tableOutput.value = await getFundTransactionTable(pagination.value) items.value.push(...(tableOutput.value?.rows ?? [])) } catch (e) { console.log(e) } finally { loading.value = false } } async function initInfo() { const id = infoId.value if (id == null) { console.error('Invalid fund product id in route') return } try { loading.value = true info.value = await getOneProductWallet(id) await initTable() } catch (e) { console.log(e) } finally { loading.value = false } } watch(infoId, (id) => { if (id != null) void initInfo() }, { immediate: true }) function goBack() { router.back() } const context: FundInfoPageContext = { info, items, infoId, goBack, } provide(FUND_INFO_PAGE_KEY, context) return context } export function useFundInfoPageContext() { const context = inject(FUND_INFO_PAGE_KEY) if (!context) throw new Error('useFundInfoPageContext must be used within useFundInfoPage') return context }