pay.ts 1.33 KB
/*
 * @Author: 赵丽婷
 * @Date: 2026-01-08 14:56:53
 * @LastEditors: 赵丽婷
 * @LastEditTime: 2026-01-08 15:19:04
 * @FilePath: \LinkMed\linkmed-vue3\src\stores\pay.ts
 * @Description:
 * Copyright (c) 2026 by 北京连心医疗科技有限公司, All Rights Reserved.
 */
import { defineStore } from "pinia";
import { ref } from "vue";
import { getBeansBalance } from "@/api/pay";

export const usePayStore = defineStore("pay", () => {
  // 领医豆余额(null 表示尚未加载或加载失败)
  const beansBalance = ref<number | null>(null);
  const loading = ref(false);
  const error = ref<string | null>(null);

  /**
   * 获取当前用户领医豆余额
   * - 默认具有幂等性:如果正在加载中则直接返回
   */
  const fetchBeansBalance = async () => {
    if (loading.value) return;

    try {
      loading.value = true;
      error.value = null;
      const res = await getBeansBalance();
      beansBalance.value = res.data?.balance ?? 0;
    } catch (err: any) {
      console.error("获取领医豆余额失败:", err);
      error.value = err?.message || "获取领医豆余额失败";
      // 失败时置为 0,避免后续逻辑因 null 报错
      beansBalance.value = 0;
    } finally {
      loading.value = false;
    }
  };

  return {
    beansBalance,
    loading,
    error,
    fetchBeansBalance,
  };
});