import { create } from "zustand";
import { business } from "@/services";

type State = {
  tabBar?: {
    selected?: number;
  };
  loading?: boolean;
  userRoleVO?: AuthAPI.UserRoleVO;
  costItemVOList?: BusinessAPI.CostItemVO[];
  costVOList?: BusinessAPI.CostVO[];
};

type Action = {
  setTabBar: (selected: number) => void;
  setLoading: (loading: boolean) => void;
  setUserRoleVO: (userRoleVO: AuthAPI.UserRoleVO) => void;
  fetchCosts: () => Promise<void>;
  fetchCostItems: () => Promise<void>;
};

export const globalStore = create<State & Action>((set) => ({
  setTabBar: (selected) => {
    set(() => ({
      tabBar: {
        selected: selected,
      },
    }));
  },
  setLoading: (loading: boolean) => {
    set(() => ({
      loading: loading,
    }));
  },
  setUserRoleVO: (userRoleVO: AuthAPI.UserRoleVO) => {
    set(() => ({
      userRoleVO: userRoleVO,
    }));
  },
  fetchCosts: async () => {
    try {
      const { data } = await business.cost.listCost({
        costListQry: {
          status: true,
        },
      });
      set({ costVOList: data.data || [] });
    } catch (error) {
      console.error("获取费用列表失败:", error);
    }
  },
  fetchCostItems: async () => {
    try {
      const { data } = await business.costItem.listCostItem({
        costItemListQry: {
          status: true,
        },
      });
      set({ costItemVOList: data.data || [] });
    } catch (error) {
      console.error("获取费用项目列表失败:", error);
    }
  },
}));
