dataProcessor.uts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. import { getToken, getTokenFromApi } from './auth'
  2. import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord, getJoinList, updateData } from '@/api/work'
  3. import { globalConfig } from '@/config'
  4. // 类型定义保持不变
  5. export type ApiResponse = {
  6. code : number;
  7. msg : string;
  8. data : MediaInfoData[];
  9. }
  10. export type MediaInfoData = {
  11. pk : string;
  12. workorder ?: string;
  13. invname ?: string;
  14. productcode ?: string;
  15. cardno ?: string;
  16. model ?: string;
  17. graphid ?: string;
  18. ver ?: string;
  19. phase ?: string;
  20. processno ?: string;
  21. createtime ?: string;
  22. createuser ?: string;
  23. updatetime ?: string;
  24. updateuser ?: string;
  25. qmImageTaskClist ?: MediaRecordData[];
  26. }
  27. export type MediaRecordData = {
  28. senum ?: string;
  29. photoitem ?: string;
  30. part ?: string;
  31. partno ?: string;
  32. pk : string;
  33. exampleid ?: string;
  34. descb ?: string;
  35. num ?: number;
  36. urlspl ?: string;
  37. imgname ?: string;
  38. urlpdt ?: string;
  39. createtime ?: string;
  40. createuser ?: string;
  41. updatetime ?: string;
  42. updateuser ?: string;
  43. photoFiles_example ?: PhotoFilesExample[];
  44. }
  45. export type PhotoFilesExample = {
  46. _id ?: string,
  47. }
  48. export type UploadImg = {
  49. pk : string,
  50. path : string
  51. }
  52. export const showProgress = (index : number, title : string) => {
  53. // 在Android设备上,需要给hideLoading和showLoading之间添加延迟
  54. // 先隐藏之前的加载提示
  55. uni.hideLoading();
  56. // 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
  57. setTimeout(() => {
  58. uni.showLoading({
  59. title: `正在${title}第${index}个任务数据`,
  60. mask: true
  61. });
  62. }, 50);
  63. }
  64. export const moveFile = (oldPath : string) : Promise<string> => {
  65. return new Promise((resolve, reject) => {
  66. // 生成唯一的文件名
  67. const timestamp = Date.now();
  68. const randomNum = Math.floor(Math.random() * 1000);
  69. const fileExtension = oldPath.substring(oldPath.lastIndexOf('.'));
  70. const newImgName = `download_${timestamp}_${randomNum}${fileExtension}`;
  71. // 定义新的保存路径 - 不放在相册里,放在应用数据目录下的downloadImgs文件夹
  72. const destPath = `${uni.env.USER_DATA_PATH}/downloadImgs/${newImgName}`;
  73. try {
  74. // 确保目标目录存在
  75. const fs = uni.getFileSystemManager();
  76. try {
  77. fs.accessSync(`${uni.env.USER_DATA_PATH}/downloadImgs`);
  78. } catch (e) {
  79. // 目录不存在,创建目录
  80. fs.mkdirSync(`${uni.env.USER_DATA_PATH}/downloadImgs`, true);
  81. }
  82. // 先拷贝文件到新路径
  83. fs.copyFile({
  84. srcPath: oldPath,
  85. destPath: destPath,
  86. success: function () {
  87. // 删除原文件,释放空间
  88. fs.unlink({
  89. filePath: oldPath,
  90. success: function () {
  91. console.log('原文件已删除');
  92. },
  93. fail: function (unlinkErr) {
  94. console.error('删除原文件失败', unlinkErr);
  95. }
  96. });
  97. console.log('文件移动成功,新路径:', destPath);
  98. resolve(destPath);
  99. },
  100. fail: function (copyErr) {
  101. console.error('拷贝文件失败', copyErr);
  102. reject(copyErr);
  103. }
  104. });
  105. } catch (error) {
  106. console.error('文件移动过程发生错误', error);
  107. reject(error);
  108. }
  109. });
  110. }
  111. //声像任务下载
  112. export const downloadDataFromAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  113. try {
  114. uni.showLoading({ title: '任务开始下载' });
  115. const apiToken = await getTokenFromApi();
  116. if (apiToken == null || apiToken == '') {
  117. uni.hideLoading();
  118. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  119. return false
  120. }
  121. //校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
  122. //如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
  123. const infoJson = await getLatestRecord(productCode, null);
  124. if (infoJson?.['data'] != null) {
  125. let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
  126. let ingNum = parseInt(info?.['statusRecordCount'] as string);
  127. //覆盖标识位
  128. let overwiteFlag = ref(false);
  129. // 先检查是否有任务正在执行中
  130. if (info != null && ingNum > 0) {
  131. uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
  132. return false;
  133. }
  134. // 使用Promise来处理异步流程
  135. let deleteDataPromise = new Promise<boolean>((resolve) => {
  136. if (info != null && ingNum == 0) {
  137. //可以被覆盖,需要有提示框,给用户确认
  138. uni.showModal({
  139. title: '系统提示',
  140. content: '该产品号已存在任务是否覆盖掉?',
  141. cancelText: '取消',
  142. confirmText: '确定',
  143. success: function (res) {
  144. if (res.confirm) {
  145. // 标记为需要覆盖
  146. overwiteFlag.value = true;
  147. // 执行删除数据操作
  148. let pid = info?.['pdid'] as string;
  149. removeInfoAndRecord(pid).then((recordDelResponse) => {
  150. console.log('删除数据响应:', recordDelResponse);
  151. // 删除成功,解析Promise并允许继续执行
  152. // 确保模态框已完全关闭后再解析Promise
  153. setTimeout(() => {
  154. resolve(true);
  155. }, 300);
  156. }).catch((error) => {
  157. console.error('删除数据失败:', error);
  158. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  159. resolve(false);
  160. });
  161. } else {
  162. // 用户取消覆盖
  163. overwiteFlag.value = false;
  164. resolve(false);
  165. }
  166. }
  167. });
  168. } else {
  169. // 不需要显示确认框,直接解析Promise
  170. resolve(true);
  171. }
  172. });
  173. // 等待删除数据操作完成
  174. const canContinue : boolean = await deleteDataPromise;
  175. if (!canContinue) {
  176. // 如果不能继续(删除失败或用户取消),则终止函数执行
  177. return false;
  178. }
  179. }
  180. // 使用Promise处理HTTP请求,避免嵌套Promise
  181. return new Promise<boolean>((resolve) => {
  182. uni.request({
  183. url: `${globalConfig.host}${globalConfig.downloadURL}${productCode}`,
  184. method: 'GET',
  185. header: {
  186. 'token': apiToken
  187. },
  188. success: (res) => {
  189. let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  190. if (singleObject != null && singleObject.code == 666) {
  191. let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  192. if (mediaInfoList != null && mediaInfoList.length > 0) {
  193. mediaInfoList.forEach(item => {
  194. if (item != null) {
  195. let data = JSON.parse<MediaInfoData>(item.toJSONString());
  196. if (data != null) {
  197. saveMediaInfo(item).then((resSave : UTSJSONObject) => {
  198. const lastIdStr = resSave?.['lastId'] as string | null;
  199. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  200. if (lastId != null) {
  201. let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  202. if (recordList != null && recordList.length > 0) {
  203. const totalRecords = recordList.length;
  204. let processedRecords = 0;
  205. // 使用async/await处理循环中的异步操作
  206. const processAllRecords = async () => {
  207. // 创建一个Map来跟踪不同photoitem的计数
  208. const photoItemCounter : Map<string, number> = new Map();
  209. for (var i = 0; i < recordList.length; i++) {
  210. // 更新进度
  211. processedRecords++;
  212. showProgress(processedRecords, '下载');
  213. const record : MediaRecordData = recordList[i] as MediaRecordData;
  214. // 获取各个字段的值
  215. const photoitem = record.photoitem as string;
  216. // 根据photoitem类型统计senum
  217. if (!photoItemCounter.has(photoitem)) {
  218. photoItemCounter.set(photoitem, 1);
  219. } else {
  220. const currentCount = photoItemCounter.get(photoitem);
  221. photoItemCounter.set(photoitem, (currentCount != null ? currentCount : 0) + 1);
  222. }
  223. const senum = photoItemCounter.get(photoitem);
  224. const finalSenum = senum != null ? senum : 1;
  225. const partno = record.partno;
  226. const part = record.part;
  227. const pk = record.pk;
  228. const descb = record.descb;
  229. const num = record.num;
  230. const imgname = record.imgname;
  231. const urlpdt = record.urlpdt;
  232. const createtime = record.createtime;
  233. const createuser = record.createuser;
  234. const updatetime = record.updatetime;
  235. const updateuser = record.updateuser;
  236. // 创建数组来存储图片ID和保存路径
  237. var exampleidArr = [] as string[];
  238. var imagePathsArr = [] as string[];
  239. let exampleList = record?.['photoFiles_example'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  240. if (exampleList != null && exampleList.length > 0) {
  241. // 下载所有图片并等待完成
  242. const imageDownloadPromises = [] as Promise<void>[];
  243. // 顺序下载和保存图片,避免并行导致的随机失败
  244. for (var j = 0; j < exampleList.length; j++) {
  245. const example : PhotoFilesExample = exampleList[j] as PhotoFilesExample;
  246. if (example._id != null) {
  247. exampleidArr.push(example._id);
  248. try {
  249. // 串行执行,等待前一张图片处理完成再处理下一张
  250. await new Promise<void>((resolve, reject) => {
  251. // 使用uni.downloadFile下载图片
  252. uni.downloadFile({
  253. url: `${globalConfig.getImgURL}${example._id}`,
  254. header: {
  255. 'token': apiToken
  256. },
  257. success: (res) => {
  258. if (res.statusCode === 200) {
  259. // 等待一小段时间确保文件完全下载
  260. setTimeout(() => {
  261. // 直接移动文件到应用数据目录,不保存到相册
  262. moveFile(res.tempFilePath).then((newFilePath) => {
  263. // 将新的文件路径添加到数组中
  264. imagePathsArr.push(newFilePath);
  265. console.log('图片已移动并添加到数组:', newFilePath);
  266. // 处理完成后等待1秒再处理下一张
  267. setTimeout(() => {
  268. resolve();
  269. }, 500);
  270. }).catch((error) => {
  271. console.error('文件移动失败,使用原始路径:', error);
  272. // 如果移动失败,使用原始路径作为备选
  273. imagePathsArr.push(res.tempFilePath);
  274. // 处理完成后等待1秒再处理下一张
  275. setTimeout(() => {
  276. resolve();
  277. }, 1000);
  278. });
  279. }, 500); // 等待500ms确保文件完全下载
  280. } else {
  281. console.error('下载图片失败,状态码:', res.statusCode);
  282. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  283. }
  284. },
  285. fail: (err) => {
  286. console.error('请求图片失败:', err);
  287. reject(err);
  288. }
  289. });
  290. });
  291. } catch (error) {
  292. console.error(`处理第${j + 1}张图片时出错:`, error);
  293. // 出错后继续处理下一张图片
  294. }
  295. }
  296. }
  297. }
  298. // 拼接图片ID和路径
  299. const exampleid = exampleidArr.join(",");
  300. const imagePaths = imagePathsArr.join(",");
  301. console.log("=========================================>");
  302. console.log(imagePaths);
  303. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  304. var values = `${finalSenum === null ? '1' : `'${finalSenum}'`}, ${photoitem === null ? 'null' : `'${photoitem}'`}, ${data?.['productcode'] === null ? 'null' : `'${data?.['productcode']}'`},${part === null ? 'null' : `'${part}'`},${partno === null ? 'null' : `'${partno}'`},${pk === null ? 'null' : `'${pk}'`},${exampleid === null ? 'null' : `'${exampleid}'`},${descb === null ? 'null' : `'${descb}'`},${num === null ? 0 : num},1,'', ${imagePaths === null ? 'null' : `'${imagePaths}'`},${imgname === null ? 'null' : `'${imgname}'`},${urlpdt === null ? 'null' : `'${urlpdt}'`}, ${createtime === null ? 'null' : `'${createtime}'`}, ${createuser === null ? 'null' : `'${createuser}'`}, ${updatetime === null ? 'null' : `'${updatetime}'`}, ${updateuser === null ? 'null' : `'${updateuser}'`}, ${lastId === null ? 0 : lastId}`;
  305. // 只有在所有图片下载完成后才调用saveMediaRecord
  306. saveMediaRecord(values);
  307. }
  308. // 所有记录处理完成,显示完成提示
  309. setTimeout(() => {
  310. uni.hideLoading();
  311. uni.showToast({ title: `下载完成`, icon: 'success' });
  312. if (callback != null) {
  313. callback();
  314. }
  315. }, 500);
  316. };
  317. // 开始处理所有记录
  318. processAllRecords();
  319. }
  320. } else {
  321. console.log('保存媒体信息成功,但未获取到主键ID');
  322. }
  323. })
  324. }
  325. }
  326. });
  327. resolve(true);
  328. } else {
  329. uni.hideLoading();
  330. uni.showToast({ title: '未获取到数据', icon: 'error' });
  331. resolve(false);
  332. }
  333. } else {
  334. const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
  335. uni.hideLoading();
  336. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  337. resolve(false);
  338. }
  339. },
  340. fail: (err) => {
  341. console.error('请求数据失败:', err);
  342. uni.hideLoading();
  343. uni.showToast({ title: `请求失败: ${err.errMsg}`, icon: 'error' });
  344. resolve(false);
  345. }
  346. });
  347. });
  348. } catch (error) {
  349. console.error(error);
  350. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  351. uni.hideLoading();
  352. return false;
  353. }
  354. }
  355. //声像任务上传
  356. export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  357. try {
  358. //暂定需要上传的数据文件
  359. //const infoJson = await getLatestRecord(productCode, null);
  360. const apiToken = await getTokenFromApi();
  361. if (apiToken == null || apiToken == '') {
  362. uni.hideLoading();
  363. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  364. return false
  365. }
  366. // 获取数据
  367. const res = await getJoinList('app_media_record as r', 'app_media_info as i', 'r.*,i.productno, i.uploadFlag', 'r.pid=i.pdid', 'i.productno', productCode, null);
  368. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  369. console.log(dataList);
  370. if (dataList == null || dataList.length === 0) {
  371. uni.hideLoading();
  372. uni.showToast({ title: '未获取到数据', icon: 'error' });
  373. return false;
  374. }
  375. let doneRecordList = dataList.filter(item => item.getString("status") == '3');
  376. console.log(doneRecordList);
  377. if (doneRecordList.length === 0) {
  378. uni.hideLoading();
  379. uni.showToast({ title: '上传图片数据为空', icon: 'error' });
  380. return false;
  381. }
  382. // 1. 收集所有需要上传的图片
  383. let allImagesToUpload : UploadImg[] = [];
  384. let processStep = 1;
  385. for (let index = 0; index < dataList.length; index++) {
  386. const record = dataList[index];
  387. if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
  388. || record.getString('pk') == '' || record.getString('pk') == null) {
  389. continue
  390. }
  391. showProgress(processStep, '准备上传');
  392. //收集图片信息
  393. let urlpdtStr = record.getString('urlpdt');
  394. let pk = record.getString('pk');
  395. let urlArr = urlpdtStr?.split(",") ?? [];
  396. for (let j = 0; j < urlArr.length; j++) {
  397. let path = urlArr[j];
  398. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  399. allImagesToUpload.push({ pk: pk ?? '', path: fullFilePath });
  400. }
  401. processStep++;
  402. }
  403. // 2. 统计总图片数量
  404. const totalImages = allImagesToUpload.length;
  405. console.log(`总共需要上传${totalImages}张图片`);
  406. if (totalImages === 0) {
  407. uni.hideLoading();
  408. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  409. return true;
  410. }
  411. // 3. 执行第一次上传
  412. let failedImages : UploadImg[] = [];
  413. let successCount = 0;
  414. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  415. for (let i = 0; i < allImagesToUpload.length; i++) {
  416. const { pk, path } = allImagesToUpload[i];
  417. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}`);
  418. try {
  419. // 串行执行,等待前一个图片上传完成再处理下一张
  420. await new Promise<void>((resolve, reject) => {
  421. // 使用uni.uploadFile进行文件上传
  422. console.log(`上传路径:${globalConfig.uploadURL}`)
  423. const uploadTask = uni.uploadFile({
  424. url: `${globalConfig.uploadURL}`,
  425. filePath: path,
  426. name: 'file', // 文件参数名
  427. header: {
  428. 'token': apiToken
  429. },
  430. formData: {
  431. 'billid': pk
  432. },
  433. success: (uploadRes) => {
  434. if (uploadRes.statusCode === 200) {
  435. console.log(`文件${path}上传成功`, uploadRes);
  436. // 解析响应数据
  437. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  438. console.log(resData)
  439. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  440. successCount++;
  441. // 等待一小段时间确保文件完全上传并处理完成
  442. setTimeout(() => {
  443. resolve();
  444. }, 1000);
  445. } else {
  446. setTimeout(() => {
  447. reject('响应数据无效');
  448. }, 500);
  449. }
  450. } else {
  451. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  452. setTimeout(() => {
  453. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  454. }, 500);
  455. }
  456. },
  457. fail: (err) => {
  458. console.error(`文件${path}上传失败`, err);
  459. // 上传失败也继续处理下一张,但记录错误
  460. setTimeout(() => {
  461. reject(err);
  462. }, 500);
  463. },
  464. complete: () => {
  465. // console.log(`文件${path}上传操作完成`);
  466. // 更新进度
  467. uni.hideLoading();
  468. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  469. }
  470. });
  471. uploadTask.onProgressUpdate((res) => {
  472. console.log('上传进度' + res.progress);
  473. console.log('已经上传的数据长度' + res.totalBytesSent);
  474. console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  475. });
  476. });
  477. } catch (error) {
  478. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  479. console.log(`处理第${i + 1}张图片时出错:`, error);
  480. failedImages.push({ pk, path });
  481. // 出错后继续处理下一张图片
  482. }
  483. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  484. if (i < allImagesToUpload.length - 1) {
  485. await new Promise<void>((resolve) => {
  486. setTimeout(() => {
  487. resolve()
  488. }, 1000)
  489. })
  490. }
  491. }
  492. // 4. 执行重试逻辑(最多3次)
  493. const maxRetries = 3;
  494. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  495. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  496. if (retryImages.length === 0) {
  497. // 如果没有需要重试的图片,提前结束循环
  498. break;
  499. }
  500. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  501. uni.hideLoading();
  502. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  503. // 创建新的错误数组,用于收集本次重试失败的图片
  504. let currentFailedImages : UploadImg[] = [];
  505. let currentSuccessCount = 0;
  506. // 串行上传失败的图片
  507. for (let i = 0; i < retryImages.length; i++) {
  508. const { pk, path } = retryImages[i];
  509. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}`);
  510. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  511. await new Promise<void>((resolve) => {
  512. uni.uploadFile({
  513. url: `${globalConfig.uploadURL}`,
  514. filePath: path,
  515. name: 'file',
  516. header: {
  517. 'token': apiToken
  518. },
  519. formData: {
  520. 'billid': pk
  521. },
  522. success: (uploadRes) => {
  523. if (uploadRes.statusCode === 200) {
  524. console.log(`重试文件${path}上传成功`, uploadRes);
  525. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  526. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  527. currentSuccessCount++;
  528. } else {
  529. currentFailedImages.push({ pk, path });
  530. }
  531. } else {
  532. currentFailedImages.push({ pk, path });
  533. }
  534. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  535. resolve();
  536. },
  537. fail: (err) => {
  538. console.error(`重试文件${path}上传失败`, err);
  539. currentFailedImages.push({ pk, path });
  540. resolve();
  541. },
  542. complete: () => {
  543. // console.log(`重试文件${path}上传操作完成`);
  544. // 更新进度
  545. uni.hideLoading();
  546. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  547. }
  548. });
  549. });
  550. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  551. if (i < retryImages.length - 1) {
  552. await new Promise<void>((resolve) => {
  553. setTimeout(() => {
  554. resolve()
  555. }, 1000)
  556. })
  557. }
  558. }
  559. // 更新成功数量
  560. successCount += currentSuccessCount;
  561. // 更新下一次重试的图片列表为本次失败的图片
  562. retryImages = currentFailedImages;
  563. }
  564. // 5. 显示总结信息
  565. const finalFailedCount = retryImages.length;
  566. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  567. uni.hideLoading();
  568. // 三次重试后如果仍有失败的图片,显示提示
  569. if (finalFailedCount > 0) {
  570. uni.showModal({
  571. title: '上传提示',
  572. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  573. showCancel: false
  574. });
  575. } else {
  576. uni.showToast({
  577. title: `上传完成!共${totalImages}张图片,全部成功。`,
  578. icon: 'success'
  579. });
  580. }
  581. if (callback != null) {
  582. callback();
  583. }
  584. if (finalFailedCount === 0) {
  585. let updatedData = " uploadflag = 1 "
  586. updateData('app_media_info', updatedData, 'productno', productCode).then((res : UTSJSONObject) => {
  587. console.log(`更新完上传标识 ${productCode}`)
  588. });
  589. }
  590. return finalFailedCount === 0;
  591. } catch (error) {
  592. console.error(error);
  593. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  594. uni.hideLoading();
  595. return false;
  596. }
  597. }