upload.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import UIButton from "@/components/ui/UIButton";
  2. import { Colors } from "@/constants/theme";
  3. import { ActionSheet, ActivityIndicator, Icon, Modal, Toast } from "@ant-design/react-native";
  4. import { Ionicons } from '@expo/vector-icons';
  5. import { Platform, Pressable, Text, View } from "react-native";
  6. import api from "@/utils/api";
  7. import { openSystemSettings } from "@/utils/os";
  8. import clsx from "clsx";
  9. import { DocumentPickerAsset, getDocumentAsync } from 'expo-document-picker';
  10. import { File } from 'expo-file-system';
  11. import { ImagePickerAsset, launchCameraAsync, launchImageLibraryAsync, requestCameraPermissionsAsync, requestMediaLibraryPermissionsAsync } from 'expo-image-picker';
  12. import { Link } from "expo-router";
  13. import { useCallback, useEffect, useState } from "react";
  14. const takePhoto = async (upload: (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => void) => {
  15. const permission = await requestCameraPermissionsAsync();
  16. if (!permission.granted) {
  17. Modal.alert("请允许相册权限", "如果点击“确认“按钮后没有跳转,请自己前往系统设置开启相关权限", [
  18. {
  19. text: "确认",
  20. onPress: openSystemSettings,
  21. }
  22. ]);
  23. // 跳转到 ios/android 相关设置页面
  24. return;
  25. }
  26. const l = Toast.loading('正在打开相机...');
  27. try {
  28. const result = await launchCameraAsync({
  29. allowsEditing: false, // 是否允许裁剪
  30. quality: 0.9, // 照片质量
  31. });
  32. if (!result.canceled) {
  33. upload(result.assets);
  34. }
  35. } catch (err) {
  36. console.warn(err);
  37. Toast.fail('打开相机失败,请重试');
  38. }
  39. finally {
  40. Toast.remove(l);
  41. }
  42. }
  43. const picImg = async (upload: (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => void) => {
  44. const permission = await requestMediaLibraryPermissionsAsync();
  45. if (!permission.granted) {
  46. Modal.alert("请允许相册权限", "如果点击“确认“按钮后没有跳转,请自己前往系统设置开启相关权限", [
  47. {
  48. text: "确认",
  49. onPress: openSystemSettings,
  50. }
  51. ]);
  52. // 跳转到 ios/android 相关设置页面
  53. return;
  54. }
  55. const l = Toast.loading('正在打开相册...');
  56. try {
  57. let result = await launchImageLibraryAsync({
  58. mediaTypes: ['images'], // 只选图片
  59. allowsEditing: false,
  60. quality: .9, // 质量 0~1
  61. });
  62. if (!result.canceled) {
  63. upload(result.assets);
  64. }
  65. } catch (err) {
  66. console.warn(err);
  67. Toast.fail('打开相册失败,请重试');
  68. } finally {
  69. Toast.remove(l);
  70. }
  71. }
  72. const pickDoc = async (upload: (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => void) => {
  73. const l = Toast.loading('正在打开相册...');
  74. try {
  75. let result = await getDocumentAsync({
  76. type: [
  77. // PDF
  78. 'application/pdf',
  79. // Word 文档
  80. 'application/msword',
  81. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  82. // Excel 表格
  83. 'application/vnd.ms-excel',
  84. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  85. // WPS 文字 / WPS 表格
  86. 'application/wps-office.doc',
  87. 'application/wps-office.docx',
  88. 'application/wps-office.xls',
  89. 'application/wps-office.xlsx',
  90. 'application/wps-office.et',
  91. 'application/wps-office.wps',
  92. // 纯文本
  93. 'text/plain',
  94. // HTML
  95. 'text/html',
  96. // 全部图片(jpg/png/gif/webp 等)
  97. 'image/*'
  98. ],
  99. copyToCacheDirectory: true, // 复制到应用缓存目录
  100. });
  101. if (!result.canceled) {
  102. upload(result.assets);
  103. }
  104. } catch (err) {
  105. console.warn(err);
  106. Toast.fail('打开文件失败,请重试');
  107. }
  108. finally {
  109. Toast.remove(l);
  110. }
  111. };
  112. export function UploadScreen({ visible, onClose }: { visible: boolean, onClose: () => void }) {
  113. useEffect(() => {
  114. if (!visible) {
  115. setState(0);
  116. }
  117. }, [visible]);
  118. const [state, setState] = useState(0);
  119. const upload = useCallback(async (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => {
  120. setState(1);
  121. let att: { url: string, fullurl: string, attid: any } = null!;
  122. try {
  123. const file = new File(assets[0].uri);
  124. // file.type = item.mimeType || 'application/octet-stream';
  125. const formData = new FormData();
  126. formData.append('file', file);
  127. att = await api.uploadFile<{ url: string, fullurl: string, attid: any }>('common/upload', { body: formData });
  128. } catch (err) {
  129. setState(0);
  130. console.warn(err);
  131. Toast.fail('上传失败,请重试');
  132. return;
  133. }
  134. try {
  135. await api.post('/credit/create', {
  136. att: JSON.stringify(att),
  137. });
  138. setState(2);
  139. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  140. } catch (err) {
  141. setState(0);
  142. Toast.fail('添加分析到队列失败,请重试');
  143. }
  144. }, []);
  145. return (
  146. <Modal visible={visible} transparent={true} animationType="slide">
  147. <View className="flex-row items-center">
  148. <Ionicons name="cloud-upload" size={48} color={Colors.tint} />
  149. <Text className="ml-4 text-3xl font-bold">征信分析</Text>
  150. </View>
  151. {state === 0 && (
  152. <View className="w-72 h-auto px-6">
  153. <Text className="mt-2 text-2xl">请选择征信上传方式</Text>
  154. <UIButton title="从本机文件" icon="folder" onPress={() => pickDoc(upload)} className="mt-8" />
  155. {Platform.OS === 'ios' && <UIButton title="从手机相册" icon="picture" onPress={() => picImg(upload)} className="mt-4" />}
  156. <UIButton title="拍照上传" icon="camera" onPress={() => takePhoto(upload)} className="mt-4" />
  157. </View>)}
  158. {
  159. state === 1 && (
  160. <View className="w-72 h-auto p-8">
  161. <ActivityIndicator size="large" color={Colors.tint} text="正在上传,请稍候..." />
  162. </View>
  163. )
  164. }
  165. {
  166. state === 2 && (
  167. <>
  168. <View className="w-72 h-auto p-8 flex-row">
  169. <Ionicons name="time-outline" size={48} color={Colors.tint} />
  170. <Text className="mt-4 ml-4 text-2xl">AI 正在分析</Text>
  171. </View>
  172. <Text className="mt-4 ml-4 text-2xl">
  173. <Link asChild href='/(tabs)/analytics' onPress={onClose}>
  174. <Text className="text-primary">分析页</Text>
  175. </Link>
  176. 查看状态和结果</Text>
  177. </>
  178. )
  179. }
  180. <View className="h-8" />
  181. {state != 1 && <Pressable hitSlop={8} className="absolute top-0 right-4" onPress={() => { onClose(); }}>
  182. <Icon name="close" size={32} />
  183. </Pressable>}
  184. </Modal >
  185. );
  186. }
  187. export function UploadComponent({ customerId, onCompolete }: { customerId?: number, onCompolete: () => void }) {
  188. const [state, setState] = useState(0);
  189. const upload = useCallback(async (assets: ImagePickerAsset[] | DocumentPickerAsset[]) => {
  190. setState(1);
  191. let att: { url: string, fullurl: string, attid: any } = null!;
  192. try {
  193. const file = new File(assets[0].uri);
  194. // file.type = item.mimeType || 'application/octet-stream';
  195. const formData = new FormData();
  196. formData.append('file', file);
  197. att = await api.uploadFile<{ url: string, fullurl: string, attid: any }>('common/upload', { body: formData });
  198. } catch (err) {
  199. setState(0);
  200. console.warn(err);
  201. Toast.fail('上传失败,请重试');
  202. return;
  203. }
  204. try {
  205. await api.post('/credit/create', {
  206. att: JSON.stringify(att),
  207. });
  208. setState(0);
  209. onCompolete?.();
  210. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  211. } catch (err) {
  212. setState(0);
  213. Toast.fail('添加分析到队列失败,请重试');
  214. }
  215. }, [onCompolete]);
  216. const onSelect = useCallback((index: number) => {
  217. if (Platform.OS == 'android' && index == 2) {
  218. return;
  219. }
  220. if (Platform.OS == 'ios' && index == 3) {
  221. return;
  222. }
  223. if (index == 0) {
  224. pickDoc(upload);
  225. }
  226. if (index == 1) {
  227. if (Platform.OS == 'ios') {
  228. picImg(upload);
  229. } else {
  230. takePhoto(upload);
  231. }
  232. }
  233. if (index == 2) {
  234. takePhoto(upload);
  235. }
  236. }, []);
  237. const selectFile = useCallback(() => {
  238. ActionSheet.showActionSheetWithOptions({
  239. title: "请选择征信上传方式",
  240. cancelButtonIndex: 3,
  241. options: Platform.OS == 'ios' ? ['从本机文件', '从手机相册', '拍照上传', '取消'] : ['从本机文件', '拍照上传', '取消']
  242. }, onSelect);
  243. }, []);
  244. return (
  245. <>
  246. <View className="mb-3 rounded-2xl border border-outline-variant bg-surface-container-lowest p-4">
  247. <Text className="mb-3 text-xs font-bold uppercase tracking-widest text-outline">
  248. 上传征信文件
  249. </Text>
  250. <Pressable
  251. onPress={selectFile}
  252. disabled={state == 1}
  253. className="items-center rounded-2xl border-2 border-dashed border-outline-variant/40 bg-surface-container-low/50 px-6 py-8 disabled:opacity-50"
  254. >
  255. <View className="mb-3 h-14 w-14 items-center justify-center rounded-full bg-primary-fixed">
  256. <Ionicons name="cloud-upload-outline" size={30} color="#004ac6" />
  257. </View>
  258. {state == 1 ? <ActivityIndicator text="正在上传文档" size='small' /> : <Text className="text-base font-bold text-on-surface">
  259. 点击上传征信报告</Text>}
  260. <Text className={clsx("mt-1 text-sm leading-6 text-on-surface-variant", {
  261. 'opacity-50': state == 1
  262. })}>
  263. 支持 PDF、图片格式,最大 20MB
  264. </Text>
  265. </Pressable>
  266. </View>
  267. </>
  268. );
  269. }