accountStore.ts 2.12 KB
import { create } from 'zustand';
import type { Account, AccountCreate, AccountUpdate, PaginatedResponse } from '../types';
import { accountService } from '../services/accountService';

interface AccountState {
  accounts: Account[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
  loading: boolean;
  selectedAccount: Account | null;

  fetchAccounts: (params?: {
    page?: number;
    page_size?: number;
    provider_id?: string;
    status?: string;
    keyword?: string;
  }) => Promise<void>;
  createAccount: (data: AccountCreate) => Promise<void>;
  updateAccount: (id: string, data: AccountUpdate) => Promise<void>;
  toggleAccountStatus: (id: string, status: 'active' | 'disabled') => Promise<void>;
  deleteAccount: (id: string) => Promise<void>;
  setSelectedAccount: (account: Account | null) => void;
}

export const useAccountStore = create<AccountState>((set, get) => ({
  accounts: [],
  total: 0,
  page: 1,
  pageSize: 20,
  totalPages: 0,
  loading: false,
  selectedAccount: null,

  fetchAccounts: async (params) => {
    set({ loading: true });
    try {
      const p = { ...params };
      if (!p.page) p.page = get().page;
      if (!p.page_size) p.page_size = get().pageSize;
      const res: PaginatedResponse<Account> = await accountService.list(p);
      set({
        accounts: res.items,
        total: res.total,
        page: res.page,
        pageSize: res.page_size,
        totalPages: res.total_pages,
        loading: false,
      });
    } catch (e) {
      console.error('获取账号列表失败:', e);
      set({ loading: false });
    }
  },

  createAccount: async (data) => {
    await accountService.create(data);
    await get().fetchAccounts();
  },

  updateAccount: async (id, data) => {
    await accountService.update(id, data);
    await get().fetchAccounts();
  },

  toggleAccountStatus: async (id, status) => {
    await accountService.updateStatus(id, status);
    await get().fetchAccounts();
  },

  deleteAccount: async (id) => {
    await accountService.delete(id);
    await get().fetchAccounts();
  },

  setSelectedAccount: (account) => set({ selectedAccount: account }),
}));