import { computed, inject, provide, ref, type ComputedRef, type InjectionKey, type Ref } from 'vue' import { loading } from '@/utils' import { registerCodeGiftCard } from '@/api/giftCard' import { message } from 'ant-design-vue' export interface GiftCardPageContext { form: Ref<{ code: string }> disableButton: ComputedRef loading: typeof loading registerGiftCard: () => Promise } export const GIFT_CARD_PAGE_CONTEXT_KEY: InjectionKey = Symbol('giftCardPageContext') export function useGiftCardPage() { const form = ref<{ code: string }>({ code: '', }) const disableButton = computed(() => { if (!loading.value) { return !form.value.code || form.value.code.trim().length === 0 } return true }) async function registerGiftCard() { try { loading.value = true await registerCodeGiftCard(form.value.code) message.success('کد کارت هدیه با موفقیت ثبت شد') form.value.code = '' } catch (e: any) { message.error(e?.response?.data?.message || 'خطا در ثبت کد کارت هدیه') } finally { loading.value = false } } const context: GiftCardPageContext = { form, disableButton, loading, registerGiftCard, } provide(GIFT_CARD_PAGE_CONTEXT_KEY, context) return context } export function useGiftCardPageContext() { const context = inject(GIFT_CARD_PAGE_CONTEXT_KEY) if (!context) { throw new Error('useGiftCardPageContext must be used within a page that calls useGiftCardPage()') } return context }