MerchantSelector.tsx 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import React from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
  4. import { merchantClient } from '../api/merchantClient';
  5. interface MerchantSelectorProps {
  6. value?: number;
  7. onChange?: (value: number) => void;
  8. placeholder?: string;
  9. disabled?: boolean;
  10. testId?: string;
  11. }
  12. export const MerchantSelector: React.FC<MerchantSelectorProps> = ({
  13. value,
  14. onChange,
  15. placeholder = "选择商户",
  16. disabled,
  17. testId
  18. }) => {
  19. const { data: merchants, isLoading } = useQuery({
  20. queryKey: ['merchants'],
  21. queryFn: async () => {
  22. const res = await merchantClient.$get({
  23. query: {
  24. page: 1,
  25. pageSize: 100
  26. }
  27. });
  28. if (res.status !== 200) throw new Error('获取商户列表失败');
  29. const result = await res.json();
  30. return result.data;
  31. }
  32. });
  33. return (
  34. <Select
  35. value={value?.toString() || ''}
  36. onValueChange={(val) => onChange?.(parseInt(val))}
  37. disabled={disabled || isLoading}
  38. >
  39. <SelectTrigger data-testid={testId}>
  40. <SelectValue placeholder={placeholder} />
  41. </SelectTrigger>
  42. <SelectContent>
  43. {isLoading ? (
  44. <SelectItem value="loading" disabled>加载中...</SelectItem>
  45. ) : merchants && merchants.length > 0 ? (
  46. merchants.map((merchant) => (
  47. <SelectItem key={merchant.id} value={merchant.id.toString()}>
  48. {merchant.name}
  49. </SelectItem>
  50. ))
  51. ) : (
  52. <SelectItem value="no-merchants" disabled>暂无商户</SelectItem>
  53. )}
  54. </SelectContent>
  55. </Select>
  56. );
  57. };