select.tsx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { StatusBadge } from '@/components/ui/status-badge';
  2. import { Colors } from '@/constants/theme';
  3. import type { ListResponse } from '@/utils/api';
  4. import api from '@/utils/api';
  5. import { getApiCache } from '@/utils/storage';
  6. import { ActivityIndicator, Toast } from '@ant-design/react-native';
  7. import { Ionicons } from '@expo/vector-icons';
  8. import { useRoute } from '@react-navigation/native';
  9. import clsx from 'clsx';
  10. import { Stack, useNavigation } from 'expo-router';
  11. import { useCallback, useEffect, useRef, useState } from 'react';
  12. import { FlatList, Pressable, Text, TextInput, View } from 'react-native';
  13. import { useSafeAreaInsets } from 'react-native-safe-area-context';
  14. import type { Customer, CustomerLoanStatus } from '../(tabs)/customer';
  15. const PAGE_SIZE = 15;
  16. const CACHE_KEY = 'customer_first';
  17. export const CustomerLoanStatusText: Record<NonNullable<CustomerLoanStatus>, string> = {
  18. idle: '待匹配',
  19. completed: '已完成',
  20. unmatch: '匹配失败',
  21. all: '所有',
  22. unknow: '未知'
  23. };
  24. export default function CustomerSelectScreen() {
  25. const insets = useSafeAreaInsets();
  26. const navigation = useNavigation();
  27. const route = useRoute();
  28. const [searchKey, setSearchKey] = useState('');
  29. const [list, setList] = useState<Customer[]>([]);
  30. const [loading, setLoading] = useState(true);
  31. const [activeStatus, setActiveStatus] = useState<CustomerLoanStatus>('idle');
  32. const startRef = useRef(0);
  33. const loanStatusRef = useRef<CustomerLoanStatus>('idle');
  34. const hasMoreRef = useRef(false);
  35. const loadingRef = useRef(false);
  36. const searchTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  37. const load = useCallback(async (start: number, loanStatus: CustomerLoanStatus, q?: string) => {
  38. if (loadingRef.current) return;
  39. loadingRef.current = true;
  40. loanStatusRef.current = loanStatus;
  41. startRef.current = start;
  42. setLoading(true);
  43. try {
  44. const res = await api.post<ListResponse<Customer>>('customer/list', {
  45. start,
  46. size: PAGE_SIZE,
  47. loanStatus,
  48. q,
  49. });
  50. if (loanStatusRef.current !== loanStatus) return;
  51. const next = res?.list ?? [];
  52. if (start === 0 && !loanStatus && next.length) {
  53. getApiCache().setObject(CACHE_KEY, res, 60);
  54. }
  55. hasMoreRef.current = next.length >= PAGE_SIZE;
  56. setList((prev) => (start === 0 ? next : prev.concat(next)));
  57. startRef.current = start + next.length;
  58. if (!next.length && start > 0) {
  59. Toast.offline('没有更多数据可加载');
  60. }
  61. } catch {
  62. Toast.fail('加载列表失败!');
  63. } finally {
  64. setLoading(false);
  65. loadingRef.current = false;
  66. }
  67. }, []);
  68. // 首次加载
  69. useEffect(() => {
  70. load(0, 'idle');
  71. }, [load]);
  72. const loadMore = useCallback(() => {
  73. if (!hasMoreRef.current || loadingRef.current) return;
  74. load(startRef.current, loanStatusRef.current, searchKey);
  75. }, [load, searchKey]);
  76. const handleSelectStatus = useCallback(
  77. (status: CustomerLoanStatus) => {
  78. const next = activeStatus === status ? undefined : status;
  79. setActiveStatus(next);
  80. load(0, next, searchKey);
  81. },
  82. [activeStatus, load, searchKey]
  83. );
  84. const handlePick = useCallback(
  85. async (item: Customer) => {
  86. // @ts-ignore
  87. const res = await route.params?.onSelect?.(item);
  88. // alert(res);
  89. if (false === res) {
  90. return;
  91. }
  92. navigation.goBack();
  93. },
  94. [navigation]
  95. );
  96. const handleSearch = useCallback((k: string) => {
  97. setSearchKey(k);
  98. if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
  99. searchTimerRef.current = setTimeout(() => {
  100. load(0, loanStatusRef.current, k);
  101. }, 600);
  102. }, [load, searchKey]);
  103. const handleReset = useCallback(()=> {
  104. handleSearch('');
  105. }, [handleSearch]);
  106. useEffect(() => {
  107. return () => {
  108. if (searchTimerRef.current) clearTimeout(searchTimerRef.current);
  109. };
  110. }, []);
  111. // @ts-ignore
  112. const currentId = route.params?.current;
  113. const renderItem = useCallback(
  114. ({ item }: { item: Customer }) => (
  115. <Pressable
  116. onPress={() => handlePick(item)}
  117. className="mb-2 flex-row items-center gap-3 rounded-2xl border border-outline-variant bg-surface-container-lowest px-4 py-3 active:opacity-90 active:scale-[0.99]"
  118. >
  119. {currentId === item.id && <Ionicons name='checkmark-circle-sharp' size={20} color={Colors.tint} />}
  120. <View className="h-10 w-10 items-center justify-center rounded-full bg-primary-fixed">
  121. <Text className="text-base font-bold text-primary">{item.name?.[0] ?? '?'}</Text>
  122. </View>
  123. <View className="flex-1">
  124. <Text className="text-base font-bold text-on-surface" numberOfLines={1}>
  125. {item.name}
  126. </Text>
  127. <Text className="mt-0.5 text-sm text-on-surface-variant" numberOfLines={1}>
  128. {item.mobile}
  129. </Text>
  130. </View>
  131. {item.loan_status && <StatusBadge text={CustomerLoanStatusText[item.loan_status]} variant="secondary" />}
  132. </Pressable>
  133. ),
  134. [handlePick]
  135. );
  136. const ListHeader = (
  137. <>
  138. <View className="mb-3 flex-row items-center rounded-2xl bg-surface-container-low px-4 py-3">
  139. <Ionicons name="search-outline" size={20} color="#94a3b8" />
  140. <TextInput
  141. value={searchKey}
  142. onChangeText={handleSearch}
  143. placeholder="搜索客户姓名 / 手机号"
  144. placeholderTextColor="#94a3b8"
  145. className="ml-3 flex-1 p-0 text-base text-on-surface"
  146. />
  147. {searchKey.length > 0 ? (
  148. <Pressable hitSlop={8} onPress={handleReset}>
  149. <Ionicons name="close-circle" size={20} color="#94a3b8" />
  150. </Pressable>
  151. ) : null}
  152. </View>
  153. <View className="mb-4 flex-row flex-wrap gap-2">
  154. {Object.entries(CustomerLoanStatusText).map(([key, label]) => {
  155. const active = activeStatus === (key as CustomerLoanStatus);
  156. return (
  157. <Pressable
  158. key={key}
  159. onPress={() => handleSelectStatus(key as CustomerLoanStatus)}
  160. className={clsx("rounded-md px-1 border border-transparent active:opacity-84", {
  161. 'border-primary-container': active,
  162. })}
  163. >
  164. <Text
  165. className={clsx("text-sm font-bold text-on-surface-variant", {
  166. 'text-primary': active
  167. })}
  168. >
  169. {label}
  170. </Text>
  171. </Pressable>
  172. );
  173. })}
  174. </View>
  175. </>
  176. );
  177. const ListEmpty =
  178. !loading ? (
  179. <View className="items-center rounded-2xl border border-outline-variant bg-surface-container-lowest px-6 py-14">
  180. <Ionicons name="people-outline" size={44} color="#94a3b8" />
  181. <Text className="mt-4 text-base text-on-surface-variant">暂无匹配客户</Text>
  182. </View>
  183. ) : (
  184. <View className="flex-row items-center justify-center pt-8">
  185. <ActivityIndicator />
  186. <Text className="ml-2">加载中</Text>
  187. </View>
  188. );
  189. const ListFooter =
  190. loading && list.length > 0 ? (
  191. <View className="mt-2 flex-row items-center justify-center">
  192. <ActivityIndicator />
  193. <Text className="ml-2 pb-4">加载中</Text>
  194. </View>
  195. ) : null;
  196. return (
  197. <View className="flex-1 bg-surface">
  198. <Stack.Screen options={{ title: '选择客户' }} />
  199. <FlatList
  200. className="flex-1"
  201. contentContainerStyle={{
  202. paddingTop: insets.top + 60,
  203. paddingBottom: insets.bottom + 24,
  204. paddingHorizontal: 20,
  205. }}
  206. data={list}
  207. keyExtractor={(item) => item.id}
  208. renderItem={renderItem}
  209. keyboardShouldPersistTaps="handled"
  210. showsVerticalScrollIndicator={false}
  211. ListHeaderComponent={ListHeader}
  212. ListEmptyComponent={ListEmpty}
  213. ListFooterComponent={ListFooter}
  214. onEndReached={loadMore}
  215. onEndReachedThreshold={0.5}
  216. />
  217. </View>
  218. );
  219. }