dataProcessor.uts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. import { getCurrentUSer, getTokenFromApi } from './auth'
  2. import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord, getList, updateData, addLog } 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. console.log(`${globalConfig.getImgURL}${example._id}`);
  260. if (res.statusCode === 200) {
  261. // 等待一小段时间确保文件完全下载
  262. setTimeout(() => {
  263. // 直接移动文件到应用数据目录,不保存到相册
  264. moveFile(res.tempFilePath).then((newFilePath) => {
  265. // 将新的文件路径添加到数组中
  266. imagePathsArr.push(newFilePath);
  267. console.log('图片已移动并添加到数组:', newFilePath);
  268. // 处理完成后等待1秒再处理下一张
  269. setTimeout(() => {
  270. resolve();
  271. }, 500);
  272. }).catch((error) => {
  273. console.error('文件移动失败,使用原始路径:', error);
  274. // 如果移动失败,使用原始路径作为备选
  275. imagePathsArr.push(res.tempFilePath);
  276. // 处理完成后等待1秒再处理下一张
  277. setTimeout(() => {
  278. resolve();
  279. }, 1000);
  280. });
  281. }, 500); // 等待500ms确保文件完全下载
  282. } else {
  283. console.error('下载图片失败,状态码:', res.statusCode);
  284. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  285. }
  286. },
  287. fail: (err) => {
  288. console.error('请求图片失败:', err);
  289. reject(err);
  290. }
  291. });
  292. });
  293. } catch (error) {
  294. console.error(`处理第${j + 1}张图片时出错:`, error);
  295. // 出错后继续处理下一张图片
  296. }
  297. }
  298. }
  299. }
  300. // 拼接图片ID和路径
  301. const exampleid = exampleidArr.join(",");
  302. const imagePaths = imagePathsArr.join(",");
  303. console.log("=========================================>");
  304. console.log(imagePaths);
  305. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  306. 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}`;
  307. // 只有在所有图片下载完成后才调用saveMediaRecord
  308. saveMediaRecord(values);
  309. }
  310. // 所有记录处理完成,显示完成提示
  311. setTimeout(() => {
  312. uni.hideLoading();
  313. uni.showToast({ title: `下载完成`, icon: 'success' });
  314. if (callback != null) {
  315. callback();
  316. }
  317. }, 500);
  318. };
  319. // 开始处理所有记录
  320. processAllRecords();
  321. }
  322. } else {
  323. console.log('保存媒体信息成功,但未获取到主键ID');
  324. }
  325. })
  326. }
  327. }
  328. });
  329. addLog({ module: null, dataid: 0, content: '下载声像记录', status: 1, params: productCode, createuser: getCurrentUSer()??'' })
  330. resolve(true);
  331. } else {
  332. uni.hideLoading();
  333. uni.showToast({ title: '未获取到数据', icon: 'error' });
  334. resolve(false);
  335. }
  336. } else {
  337. const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
  338. uni.hideLoading();
  339. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  340. resolve(false);
  341. }
  342. },
  343. fail: (err) => {
  344. console.error('请求数据失败:', err);
  345. uni.hideLoading();
  346. uni.showToast({ title: `请求失败: ${err.errMsg}`, icon: 'error' });
  347. resolve(false);
  348. }
  349. });
  350. });
  351. } catch (error) {
  352. console.error(error);
  353. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  354. uni.hideLoading();
  355. return false;
  356. }
  357. }
  358. //声像任务上传
  359. export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  360. try {
  361. //暂定需要上传的数据文件
  362. //const infoJson = await getLatestRecord(productCode, null);
  363. const apiToken = await getTokenFromApi();
  364. if (apiToken == null || apiToken == '') {
  365. uni.hideLoading();
  366. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  367. return false
  368. }
  369. // 获取数据
  370. const res = await getList('app_media_record', 'productno', productCode, 'uploadFlag', '0', null);
  371. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  372. console.log(dataList);
  373. if (dataList == null || dataList.length === 0) {
  374. uni.hideLoading();
  375. uni.showToast({ title: '未获取到需要上传的数据', icon: 'error' });
  376. return false;
  377. }
  378. let doneRecordList = dataList.filter(item => item.getString("status") == '3');
  379. console.log(doneRecordList);
  380. if (doneRecordList.length === 0) {
  381. uni.hideLoading();
  382. uni.showToast({ title: '上传图片数据为空', icon: 'error' });
  383. return false;
  384. }
  385. // 1. 收集所有需要上传的图片
  386. let allImagesToUpload : UploadImg[] = [];
  387. let processStep = 1;
  388. for (let index = 0; index < dataList.length; index++) {
  389. const record = dataList[index];
  390. if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
  391. || record.getString('pk') == '' || record.getString('pk') == null) {
  392. continue
  393. }
  394. showProgress(processStep, '准备上传');
  395. //收集图片信息
  396. let urlpdtStr = record.getString('urlpdt');
  397. let sxid = record.getString('sxid');
  398. let pk = record.getString('pk');
  399. let urlArr = urlpdtStr?.split(",") ?? [];
  400. for (let j = 0; j < urlArr.length; j++) {
  401. let path = urlArr[j];
  402. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  403. allImagesToUpload.push({sxid: sxid ?? '', pk: pk ?? '', path: fullFilePath });
  404. }
  405. processStep++;
  406. }
  407. // 2. 统计总图片数量
  408. const totalImages = allImagesToUpload.length;
  409. console.log(`总共需要上传${totalImages}张图片`);
  410. if (totalImages === 0) {
  411. uni.hideLoading();
  412. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  413. return true;
  414. }
  415. // 3. 执行第一次上传
  416. let failedImages : UploadImg[] = [];
  417. let successCount = 0;
  418. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  419. for (let i = 0; i < allImagesToUpload.length; i++) {
  420. const { sxid, pk, path } = allImagesToUpload[i];
  421. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  422. try {
  423. // 串行执行,等待前一个图片上传完成再处理下一张
  424. await new Promise<void>((resolve, reject) => {
  425. // 使用uni.uploadFile进行文件上传
  426. console.log(`上传路径:${globalConfig.uploadURL}`)
  427. const uploadTask = uni.uploadFile({
  428. url: `${globalConfig.uploadURL}`,
  429. filePath: path,
  430. name: 'file', // 文件参数名
  431. header: {
  432. 'token': apiToken
  433. },
  434. formData: {
  435. 'billid': pk
  436. },
  437. success: (uploadRes) => {
  438. if (uploadRes.statusCode === 200) {
  439. console.log(`文件${path}上传成功`, uploadRes);
  440. // 解析响应数据
  441. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  442. console.log(resData)
  443. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  444. successCount++;
  445. //更新数据库记录
  446. let updatedData = " uploadflag = 1 "
  447. updateData('app_media_record', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  448. console.log(`更新图片记录的上传标识 ${sxid}`)
  449. });
  450. // 等待一小段时间确保文件完全上传并处理完成
  451. setTimeout(() => {
  452. resolve();
  453. }, 1000);
  454. } else {
  455. setTimeout(() => {
  456. reject('响应数据无效');
  457. }, 500);
  458. }
  459. } else {
  460. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  461. setTimeout(() => {
  462. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  463. }, 500);
  464. }
  465. },
  466. fail: (err) => {
  467. console.error(`文件${path}上传失败`, err);
  468. // 上传失败也继续处理下一张,但记录错误
  469. setTimeout(() => {
  470. reject(err);
  471. }, 500);
  472. },
  473. complete: () => {
  474. // console.log(`文件${path}上传操作完成`);
  475. // 更新进度
  476. uni.hideLoading();
  477. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  478. }
  479. });
  480. //调试时开启
  481. // uploadTask.onProgressUpdate((res) => {
  482. // console.log('上传进度' + res.progress);
  483. // console.log('已经上传的数据长度' + res.totalBytesSent);
  484. // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  485. // });
  486. });
  487. } catch (error) {
  488. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  489. console.log(`处理第${i + 1}张图片时出错:`, error);
  490. failedImages.push({ sxid, pk, path });
  491. // 出错后继续处理下一张图片
  492. }
  493. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  494. if (i < allImagesToUpload.length - 1) {
  495. await new Promise<void>((resolve) => {
  496. setTimeout(() => {
  497. resolve()
  498. }, 1000)
  499. })
  500. }
  501. }
  502. // 4. 执行重试逻辑(最多3次)
  503. const maxRetries = 3;
  504. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  505. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  506. if (retryImages.length === 0) {
  507. // 如果没有需要重试的图片,提前结束循环
  508. break;
  509. }
  510. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  511. uni.hideLoading();
  512. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  513. // 创建新的错误数组,用于收集本次重试失败的图片
  514. let currentFailedImages : UploadImg[] = [];
  515. let currentSuccessCount = 0;
  516. // 串行上传失败的图片
  517. for (let i = 0; i < retryImages.length; i++) {
  518. const { sxid, pk, path } = retryImages[i];
  519. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  520. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  521. await new Promise<void>((resolve) => {
  522. uni.uploadFile({
  523. url: `${globalConfig.uploadURL}`,
  524. filePath: path,
  525. name: 'file',
  526. header: {
  527. 'token': apiToken
  528. },
  529. formData: {
  530. 'billid': pk
  531. },
  532. success: (uploadRes) => {
  533. if (uploadRes.statusCode === 200) {
  534. console.log(`重试文件${path}上传成功`, uploadRes);
  535. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  536. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  537. currentSuccessCount++;
  538. //更新数据库
  539. let updatedData = " uploadflag = 1 "
  540. updateData('app_media_record', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  541. console.log(`更新图片记录的上传标识 ${sxid}`)
  542. });
  543. } else {
  544. currentFailedImages.push({ sxid, pk, path });
  545. }
  546. } else {
  547. currentFailedImages.push({ sxid, pk, path });
  548. }
  549. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  550. resolve();
  551. },
  552. fail: (err) => {
  553. console.error(`重试文件${path}上传失败`, err);
  554. currentFailedImages.push({sxid, pk, path });
  555. resolve();
  556. },
  557. complete: () => {
  558. // console.log(`重试文件${path}上传操作完成`);
  559. // 更新进度
  560. uni.hideLoading();
  561. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  562. }
  563. });
  564. });
  565. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  566. if (i < retryImages.length - 1) {
  567. await new Promise<void>((resolve) => {
  568. setTimeout(() => {
  569. resolve()
  570. }, 1000)
  571. })
  572. }
  573. }
  574. // 更新成功数量
  575. successCount += currentSuccessCount;
  576. // 更新下一次重试的图片列表为本次失败的图片
  577. retryImages = currentFailedImages;
  578. }
  579. // 5. 显示总结信息
  580. const finalFailedCount = retryImages.length;
  581. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  582. uni.hideLoading();
  583. // 三次重试后如果仍有失败的图片,显示提示
  584. if (finalFailedCount > 0) {
  585. uni.showModal({
  586. title: '上传提示',
  587. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  588. showCancel: false
  589. });
  590. } else {
  591. uni.showToast({
  592. title: `上传完成!共${totalImages}张图片,全部成功。`,
  593. icon: 'success'
  594. });
  595. }
  596. if (callback != null) {
  597. callback();
  598. }
  599. if (finalFailedCount === 0) {
  600. let updatedData = " uploadflag = 1 "
  601. updateData('app_media_info', updatedData, 'productno', productCode).then((res : UTSJSONObject) => {
  602. console.log(`更新完上传标识 ${productCode}`)
  603. });
  604. }
  605. return finalFailedCount === 0;
  606. } catch (error) {
  607. console.error(error);
  608. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  609. uni.hideLoading();
  610. return false;
  611. }
  612. }