select.tsx 9.3 KB

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