dataProcessor.uts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  1. import { getCurrentUserSync, getTokenFromApi } from '@/utils/auth.uts'
  2. import { saveMediaInfo, saveMediaRecord, getLatestRecord, removeInfoAndRecord, getList, updateData, addLog, addOperateLog } 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. uni.hideLoading();
  165. overwiteFlag.value = false;
  166. resolve(false);
  167. }
  168. }
  169. });
  170. } else {
  171. // 不需要显示确认框,直接解析Promise
  172. resolve(true);
  173. }
  174. });
  175. // 等待删除数据操作完成
  176. const canContinue : boolean = await deleteDataPromise;
  177. if (!canContinue) {
  178. // 如果不能继续(删除失败或用户取消),则终止函数执行
  179. return false;
  180. }
  181. }
  182. // 使用Promise处理HTTP请求,避免嵌套Promise
  183. return new Promise<boolean>((resolve) => {
  184. uni.request({
  185. url: `${globalConfig.host}${globalConfig.downloadURL}${productCode}`,
  186. method: 'GET',
  187. header: {
  188. 'token': apiToken
  189. },
  190. success: (res) => {
  191. let singleObject = res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  192. if (singleObject != null && singleObject.code == 666) {
  193. let mediaInfoList = singleObject?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  194. if (mediaInfoList != null && mediaInfoList.length > 0) {
  195. mediaInfoList.forEach(item => {
  196. if (item != null) {
  197. let data = JSON.parse<MediaInfoData>(item.toJSONString());
  198. if (data != null) {
  199. saveMediaInfo(item).then((resSave : UTSJSONObject) => {
  200. const lastIdStr = resSave?.['lastId'] as string | null;
  201. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  202. if (lastId != null) {
  203. let recordList = data?.['qmImageTaskClist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  204. if (recordList != null && recordList.length > 0) {
  205. const totalRecords = recordList.length;
  206. let processedRecords = 0;
  207. // 使用async/await处理循环中的异步操作
  208. const processAllRecords = async () => {
  209. // 创建一个Map来跟踪不同photoitem的计数
  210. const photoItemCounter : Map<string, number> = new Map();
  211. for (var i = 0; i < recordList.length; i++) {
  212. // 更新进度
  213. processedRecords++;
  214. showProgress(processedRecords, '下载');
  215. const record : MediaRecordData = recordList[i] as MediaRecordData;
  216. // 获取各个字段的值
  217. const photoitem = record.photoitem as string;
  218. // 根据photoitem类型统计senum
  219. if (!photoItemCounter.has(photoitem)) {
  220. photoItemCounter.set(photoitem, 1);
  221. } else {
  222. const currentCount = photoItemCounter.get(photoitem);
  223. photoItemCounter.set(photoitem, (currentCount != null ? currentCount : 0) + 1);
  224. }
  225. const senum = photoItemCounter.get(photoitem);
  226. const finalSenum = senum != null ? senum : 1;
  227. const partno = record.partno;
  228. const part = record.part;
  229. const pk = record.pk;
  230. const descb = record.descb;
  231. const num = record.num;
  232. const imgname = record.imgname;
  233. const urlpdt = record.urlpdt;
  234. const createtime = record.createtime;
  235. const createuser = record.createuser;
  236. const updatetime = record.updatetime;
  237. const updateuser = record.updateuser;
  238. // 创建数组来存储图片ID和保存路径
  239. var exampleidArr = [] as string[];
  240. var imagePathsArr = [] as string[];
  241. let exampleList = record?.['photoFiles_example'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  242. if (exampleList != null && exampleList.length > 0) {
  243. // 下载所有图片并等待完成
  244. const imageDownloadPromises = [] as Promise<void>[];
  245. // 顺序下载和保存图片,避免并行导致的随机失败
  246. for (var j = 0; j < exampleList.length; j++) {
  247. const example : PhotoFilesExample = exampleList[j] as PhotoFilesExample;
  248. if (example._id != null) {
  249. exampleidArr.push(example._id);
  250. try {
  251. // 串行执行,等待前一张图片处理完成再处理下一张
  252. await new Promise<void>((resolve, reject) => {
  253. // 使用uni.downloadFile下载图片
  254. uni.downloadFile({
  255. url: `${globalConfig.getImgURL}${example._id}`,
  256. header: {
  257. 'token': apiToken
  258. },
  259. success: (res) => {
  260. console.log(`${globalConfig.getImgURL}${example._id}`);
  261. if (res.statusCode === 200) {
  262. // 等待一小段时间确保文件完全下载
  263. setTimeout(() => {
  264. // 直接移动文件到应用数据目录,不保存到相册
  265. moveFile(res.tempFilePath).then((newFilePath) => {
  266. // 将新的文件路径添加到数组中
  267. imagePathsArr.push(newFilePath);
  268. console.log('图片已移动并添加到数组:', newFilePath);
  269. // 处理完成后等待1秒再处理下一张
  270. setTimeout(() => {
  271. resolve();
  272. }, 500);
  273. }).catch((error) => {
  274. console.error('文件移动失败,使用原始路径:', error);
  275. // 如果移动失败,使用原始路径作为备选
  276. imagePathsArr.push(res.tempFilePath);
  277. // 处理完成后等待1秒再处理下一张
  278. setTimeout(() => {
  279. resolve();
  280. }, 1000);
  281. });
  282. }, 500); // 等待500ms确保文件完全下载
  283. } else {
  284. console.error('下载图片失败,状态码:', res.statusCode);
  285. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  286. }
  287. },
  288. fail: (err) => {
  289. console.error('请求图片失败:', err);
  290. reject(err);
  291. }
  292. });
  293. });
  294. } catch (error) {
  295. console.error(`处理第${j + 1}张图片时出错:`, error);
  296. // 出错后继续处理下一张图片
  297. }
  298. }
  299. }
  300. }
  301. // 拼接图片ID和路径
  302. const exampleid = exampleidArr.join(",");
  303. const imagePaths = imagePathsArr.join(",");
  304. console.log("=========================================>");
  305. console.log(imagePaths);
  306. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  307. 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}`;
  308. // 只有在所有图片下载完成后才调用saveMediaRecord
  309. saveMediaRecord(values);
  310. }
  311. // 所有记录处理完成,显示完成提示
  312. setTimeout(() => {
  313. uni.hideLoading();
  314. uni.showToast({ title: `下载完成`, icon: 'success' });
  315. if (callback != null) {
  316. callback();
  317. }
  318. }, 500);
  319. };
  320. // 开始处理所有记录
  321. processAllRecords();
  322. }
  323. } else {
  324. console.log('保存媒体信息成功,但未获取到主键ID');
  325. }
  326. })
  327. }
  328. }
  329. });
  330. addLog({ module: null, dataid: 0, content: '下载声像记录', status: 1, params: productCode, createuser: getCurrentUserSync()??'' })
  331. addOperateLog({ module: '声像记录', title: '下载声像记录', content: `下载声像记录任务,产品编号:${productCode}`, msg: null, createuser: getCurrentUserSync()??'' })
  332. resolve(true);
  333. } else {
  334. uni.hideLoading();
  335. uni.showToast({ title: '未获取到数据', icon: 'error' });
  336. resolve(false);
  337. }
  338. } else {
  339. const errorMsg = singleObject.msg != null ? singleObject.msg : '未知错误';
  340. uni.hideLoading();
  341. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  342. resolve(false);
  343. }
  344. },
  345. fail: (err) => {
  346. console.error('请求数据失败:', err);
  347. uni.hideLoading();
  348. uni.showToast({ title: `请求失败: ${err.errMsg}`, icon: 'error' });
  349. resolve(false);
  350. }
  351. });
  352. });
  353. } catch (error) {
  354. console.error(error);
  355. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  356. addOperateLog({ module: '声像记录', title: '下载声像记录失败', content: `下载声像记录任务失败,产品编号:${productCode}`, msg: `错误信息Err:${error}`, createuser: getCurrentUserSync()??'' })
  357. uni.hideLoading();
  358. return false;
  359. }
  360. }
  361. //声像任务上传
  362. export const uploadDataToAPI = async (productCode : string, callback ?: () => void) : Promise<boolean> => {
  363. try {
  364. //暂定需要上传的数据文件
  365. const apiToken = await getTokenFromApi();
  366. if (apiToken == null || apiToken == '') {
  367. uni.hideLoading();
  368. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  369. return false
  370. }
  371. // const apiToken = ''
  372. // 获取数据
  373. let query = `productno = '${productCode}' and uploadFlag = '0' and urlpdt is not null AND (LENGTH(urlpdt) - LENGTH(REPLACE(urlpdt, ',', '')) + 1) = num`
  374. const res = await getList('app_media_record', query, null, null, null, null);
  375. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  376. console.log(dataList);
  377. if (dataList == null || dataList.length === 0) {
  378. uni.hideLoading();
  379. uni.showToast({ title: '未获取到需要上传的数据', icon: 'error' });
  380. return false;
  381. }
  382. let doneRecordList = dataList.filter(item => item.getString("status") == '3');
  383. console.log(doneRecordList);
  384. if (doneRecordList.length === 0) {
  385. uni.hideLoading();
  386. uni.showToast({ title: '上传图片数据为空', icon: 'error' });
  387. return false;
  388. }
  389. // 1. 收集所有需要上传的图片
  390. let allImagesToUpload : UploadImg[] = [];
  391. let processStep = 1;
  392. for (let index = 0; index < dataList.length; index++) {
  393. const record = dataList[index];
  394. if (record.getString('urlpdt') == '' || record.getString('urlpdt') == null
  395. || record.getString('pk') == '' || record.getString('pk') == null) {
  396. continue
  397. }
  398. showProgress(processStep, '准备上传');
  399. //收集图片信息
  400. let urlpdtStr = record.getString('urlpdt');
  401. let sxid = record.getString('sxid');
  402. let pk = record.getString('pk');
  403. let urlArr = urlpdtStr?.split(",") ?? [];
  404. for (let j = 0; j < urlArr.length; j++) {
  405. let path = urlArr[j];
  406. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  407. allImagesToUpload.push({sxid: sxid ?? '', pk: pk ?? '', path: fullFilePath });
  408. }
  409. processStep++;
  410. }
  411. // 2. 统计总图片数量
  412. const totalImages = allImagesToUpload.length;
  413. console.log(`总共需要上传${totalImages}张图片`);
  414. if (totalImages === 0) {
  415. uni.hideLoading();
  416. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  417. return true;
  418. }
  419. // 3. 执行第一次上传
  420. let failedImages : UploadImg[] = [];
  421. let successCount = 0;
  422. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  423. for (let i = 0; i < allImagesToUpload.length; i++) {
  424. const { sxid, pk, path } = allImagesToUpload[i];
  425. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  426. try {
  427. // 串行执行,等待前一个图片上传完成再处理下一张
  428. await new Promise<void>((resolve, reject) => {
  429. // 使用uni.uploadFile进行文件上传
  430. console.log(`上传路径:${globalConfig.uploadURL}`)
  431. const uploadTask = uni.uploadFile({
  432. url: `${globalConfig.uploadURL}`,
  433. filePath: path,
  434. name: 'file', // 文件参数名
  435. header: {
  436. 'token': apiToken,
  437. 'content-type': 'multipart/form-data'
  438. },
  439. formData: {
  440. 'billid': pk
  441. },
  442. success: (uploadRes) => {
  443. if (uploadRes.statusCode === 200) {
  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. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  456. let updatedData = " uploadFlag = 0 "
  457. updateData('app_media_record', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  458. console.log(`上传失败更新图片记录的上传标识 ${sxid}`)
  459. });
  460. uni.showModal({
  461. content: `图片上传失败,状态码:${uploadRes.statusCode}`,
  462. title: '图片上传失败'
  463. })
  464. setTimeout(() => {
  465. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  466. }, 500);
  467. }
  468. },
  469. fail: (err) => {
  470. console.error(`文件${path}上传失败`, err);
  471. // 上传失败也继续处理下一张,但记录错误
  472. let updatedData = " uploadFlag = 0 "
  473. updateData('app_media_record', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  474. console.log(`上传错误更新图片记录的上传标识 ${sxid}`)
  475. });
  476. uni.showModal({
  477. content: `文件上传失败:${err}`,
  478. title: '图片上传失败'
  479. })
  480. setTimeout(() => {
  481. reject(err);
  482. }, 500);
  483. },
  484. complete: () => {
  485. // console.log(`文件${path}上传操作完成`);
  486. // 更新进度
  487. uni.hideLoading();
  488. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  489. }
  490. });
  491. //调试时开启
  492. // uploadTask.onProgressUpdate((res) => {
  493. // console.log('上传进度' + res.progress);
  494. // console.log('已经上传的数据长度' + res.totalBytesSent);
  495. // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  496. // });
  497. });
  498. } catch (error) {
  499. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  500. console.log(`处理第${i + 1}张图片时出错:`, error);
  501. failedImages.push({ sxid, pk, path });
  502. uni.showModal({
  503. content: `文件上传失败:${error}`,
  504. title: '图片上传失败'
  505. })
  506. }
  507. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  508. if (i < allImagesToUpload.length - 1) {
  509. await new Promise<void>((resolve) => {
  510. setTimeout(() => {
  511. resolve()
  512. }, 1000)
  513. })
  514. }
  515. }
  516. // 4. 执行重试逻辑(最多3次)
  517. const maxRetries = 3;
  518. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  519. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  520. if (retryImages.length === 0) {
  521. // 如果没有需要重试的图片,提前结束循环
  522. break;
  523. }
  524. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  525. uni.hideLoading();
  526. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  527. // 创建新的错误数组,用于收集本次重试失败的图片
  528. let currentFailedImages : UploadImg[] = [];
  529. let currentSuccessCount = 0;
  530. // 串行上传失败的图片
  531. for (let i = 0; i < retryImages.length; i++) {
  532. const { sxid, pk, path } = retryImages[i];
  533. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  534. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  535. await new Promise<void>((resolve) => {
  536. uni.uploadFile({
  537. url: `${globalConfig.uploadURL}`,
  538. filePath: path,
  539. name: 'file',
  540. header: {
  541. 'token': apiToken
  542. },
  543. formData: {
  544. 'billid': pk
  545. },
  546. success: (uploadRes) => {
  547. if (uploadRes.statusCode === 200) {
  548. console.log(`重试文件${path}上传成功`, uploadRes);
  549. currentSuccessCount++;
  550. //更新数据库
  551. let updatedData = " uploadFlag = 1 "
  552. updateData('app_media_record', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  553. console.log(`更新图片记录的上传标识 ${sxid}`)
  554. });
  555. resolve();
  556. } else {
  557. currentFailedImages.push({ sxid, pk, path });
  558. }
  559. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  560. },
  561. fail: (err) => {
  562. console.error(`重试文件${path}上传失败`, err);
  563. currentFailedImages.push({sxid, pk, path });
  564. uni.showModal({
  565. content: `文件上传失败:${err}`,
  566. title: '图片上传失败'
  567. })
  568. resolve();
  569. },
  570. complete: () => {
  571. // console.log(`重试文件${path}上传操作完成`);
  572. // 更新进度
  573. uni.hideLoading();
  574. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  575. }
  576. });
  577. });
  578. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  579. if (i < retryImages.length - 1) {
  580. await new Promise<void>((resolve) => {
  581. setTimeout(() => {
  582. resolve()
  583. }, 1000)
  584. })
  585. }
  586. }
  587. // 更新成功数量
  588. successCount += currentSuccessCount;
  589. // 更新下一次重试的图片列表为本次失败的图片
  590. retryImages = currentFailedImages;
  591. }
  592. // 5. 显示总结信息
  593. const finalFailedCount = retryImages.length;
  594. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  595. uni.hideLoading();
  596. // 三次重试后如果仍有失败的图片,显示提示
  597. if (finalFailedCount > 0) {
  598. uni.showModal({
  599. title: '上传提示',
  600. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  601. showCancel: false
  602. });
  603. } else {
  604. uni.showToast({
  605. title: `上传完成!共${totalImages}张图片,全部成功。`,
  606. icon: 'success'
  607. });
  608. }
  609. if (finalFailedCount === 0) {
  610. let updatedData = " uploadFlag = 1, uploadtime = strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime') "
  611. updateData('app_media_info', updatedData, 'productno', productCode).then((res : UTSJSONObject) => {
  612. console.log(`更新完上传标识 ${productCode}`)
  613. });
  614. addOperateLog({ module: '声像记录',title: '上传声像记录', content: `上传声像记录任务,产品编号:${productCode}`, msg: null, createuser: getCurrentUserSync()??'' })
  615. }
  616. if (callback != null) {
  617. callback();
  618. }
  619. return finalFailedCount === 0;
  620. } catch (error) {
  621. console.error(error);
  622. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  623. uni.hideLoading();
  624. addOperateLog({ module: '声像记录',title: '上传声像记录失败', content: `上传声像记录任务失败,产品编号:${productCode}`, msg:`错误信息Err:${error}`, createuser: getCurrentUserSync()??'' })
  625. uni.showModal({
  626. content: `文件上传失败:${error}`,
  627. title: '图片上传失败'
  628. })
  629. return false;
  630. }
  631. }