dataProcessor.uts 24 KB

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