qcDataProcessor.uts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import { getToken, getTokenFromApi } from './auth'
  2. import { saveTaskInfo, saveTaskPhoto, saveTaskKeyProcess, saveTaskRecord, saveTaskRecordItem, getLatestTask, removeTaskAndRecord, getList, updateData } from '@/api/work'
  3. import { globalConfig } from '@/config'
  4. // 类型定义保持不变
  5. export type ApiResponse = {
  6. code : number;
  7. msg : string;
  8. data : AppTaskInfo;
  9. }
  10. export type AppTaskInfo = {
  11. gxpk : string;
  12. pk_serial : string;
  13. cardno ?: string;
  14. productcode ?: string;
  15. model ?: string;
  16. workorder ?: string;
  17. invname ?: string;
  18. graphid ?: string;
  19. processno ?: string;
  20. ver ?: string;
  21. lastupdatetime ?: string;
  22. qcrecord ?: AppTaskRecord;
  23. photolist ?: AppTaskPhoto[];
  24. keyprocesslist ?: AppTaskKeyProcess[];
  25. }
  26. export type AppTaskRecord = {
  27. pk ?: string;
  28. fk_invcode ?: string;
  29. no ?: string;
  30. invcode ?: string;
  31. invname : string;
  32. processStep ?: string;
  33. fk_processTask ?: string;
  34. checkTarget ?: string;
  35. checknum ?: number;
  36. oknum ?: number;
  37. ngnum ?: number;
  38. status ?: string;
  39. result ?: string;
  40. checkTime ?: string;
  41. cs ?: string;
  42. ts ?: string;
  43. items ?: AppTaskRecordItem[];
  44. }
  45. export type AppTaskRecordItem = {
  46. pk ?: string;
  47. fk_qcRecord ?: string;
  48. fk_prodcode ?: string;
  49. prodno ?: string;
  50. name ?: string;
  51. no ?: string;
  52. nature ?: string;
  53. unit ?: string;
  54. maxNum ?: number;
  55. minNum ?: number;
  56. status ?: string;
  57. memo ?: string;
  58. measuredvalue ?: string;
  59. result ?: string;
  60. cs ?: string;
  61. ts ?: string;
  62. recorder ?: string;
  63. }
  64. export type AppTaskPhoto = {
  65. pk : string;
  66. photographpoint ?: string;
  67. photographdescription ?: string;
  68. photourl ?: string;
  69. photoname ?: string;
  70. fk_qcRecord ?: string;
  71. fk_prodcode ?: string;
  72. prodno ?: string;
  73. fk_creator ?: string;
  74. fks_operator ?: string;
  75. operator ?: string;
  76. processStep ?: string;
  77. fk_processTask ?: string;
  78. cs ?: string;
  79. ts ?: string;
  80. }
  81. export type AppTaskKeyProcess = {
  82. pk ?: string;
  83. pdid ?: string;
  84. testapparatus ?: string;
  85. tableid ?: string;
  86. testrequirelower ?: string;
  87. testrequireupper ?: string;
  88. parametername ?: string;
  89. parameterorder ?: string;
  90. measureunit ?: string;
  91. parameterinstruction ?: string;
  92. parameterid ?: string;
  93. fk_creator ?: string;
  94. fk_prodcode ?: string;
  95. prodno ?: string;
  96. processstep ?: string;
  97. fk_processtask ?: string;
  98. measuredvaluemin ?: string;
  99. measuredvaluemax ?: string;
  100. fks_operator ?: string;
  101. cs ?: string;
  102. ts ?: string;
  103. operator ?: string;
  104. }
  105. export type UploadImg = {
  106. sxid : string,
  107. pk : string,
  108. path : string
  109. }
  110. export type Task = {
  111. pdid : number,
  112. gxpk : string,
  113. cardno : string,
  114. productcode : string,
  115. model : string,
  116. workorder : string,
  117. invname : string,
  118. graphid : string,
  119. processno : string,
  120. gxno : string,
  121. ver : string,
  122. lastupdatetime : string
  123. }
  124. export const showProgress = (index : number, title : string) => {
  125. // 在Android设备上,需要给hideLoading和showLoading之间添加延迟
  126. // 先隐藏之前的加载提示
  127. uni.hideLoading();
  128. // 添加50ms的延迟,确保hideLoading完全执行后再显示新的进度
  129. setTimeout(() => {
  130. uni.showLoading({
  131. title: `正在${title}第${index}个任务数据`,
  132. mask: true
  133. });
  134. }, 50);
  135. }
  136. export const moveFile = (oldPath : string) : Promise<string> => {
  137. return new Promise((resolve, reject) => {
  138. // 生成唯一的文件名
  139. const timestamp = Date.now();
  140. const randomNum = Math.floor(Math.random() * 1000);
  141. const fileExtension = oldPath.substring(oldPath.lastIndexOf('.'));
  142. const newImgName = `download_${timestamp}_${randomNum}${fileExtension}`;
  143. // 定义新的保存路径 - 不放在相册里,放在应用数据目录下的downloadImgs文件夹
  144. const destPath = `${uni.env.USER_DATA_PATH}/downloadImgs/${newImgName}`;
  145. try {
  146. // 确保目标目录存在
  147. const fs = uni.getFileSystemManager();
  148. try {
  149. fs.accessSync(`${uni.env.USER_DATA_PATH}/downloadImgs`);
  150. } catch (e) {
  151. // 目录不存在,创建目录
  152. fs.mkdirSync(`${uni.env.USER_DATA_PATH}/downloadImgs`, true);
  153. }
  154. // 先拷贝文件到新路径
  155. fs.copyFile({
  156. srcPath: oldPath,
  157. destPath: destPath,
  158. success: function () {
  159. // 删除原文件,释放空间
  160. fs.unlink({
  161. filePath: oldPath,
  162. success: function () {
  163. console.log('原文件已删除');
  164. },
  165. fail: function (unlinkErr) {
  166. console.error('删除原文件失败', unlinkErr);
  167. }
  168. });
  169. console.log('文件移动成功,新路径:', destPath);
  170. resolve(destPath);
  171. },
  172. fail: function (copyErr) {
  173. console.error('拷贝文件失败', copyErr);
  174. reject(copyErr);
  175. }
  176. });
  177. } catch (error) {
  178. console.error('文件移动过程发生错误', error);
  179. reject(error);
  180. }
  181. });
  182. }
  183. //检验任务下载
  184. export const downloadDataFromAPI = async (gxpk : string, callback ?: () => void) : Promise<boolean> => {
  185. try {
  186. uni.showLoading({ title: '任务开始下载' });
  187. const apiToken = await getTokenFromApi();
  188. if (apiToken == null || apiToken == '') {
  189. uni.hideLoading();
  190. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  191. return false;
  192. }
  193. //校验是否已经存在未执行的产品号,若已经存在则提示用户该产品号是否需要被覆盖,
  194. //如果没有则直接保存。如果有存在已经在执行中的产品号,则提示已存在执行中的任务
  195. const infoJson = await getLatestTask(gxpk, null);
  196. if (infoJson?.['data'] != null) {
  197. let info = infoJson?.['data'] as UTSJSONObject ?? {} as UTSJSONObject
  198. // let ingNum = parseInt(info?.['pdid'] as string);
  199. //覆盖标识位
  200. let overwiteFlag = ref(false);
  201. // 先检查是否有任务正在执行中
  202. // if (info != null && ingNum > 0) {
  203. // uni.showToast({ title: `当前产品号已有任务在执行中!`, icon: 'error' });
  204. // return false;
  205. // }
  206. // 使用Promise来处理异步流程
  207. let deleteDataPromise = new Promise<boolean>((resolve) => {
  208. // if (info != null && ingNum == 0) {
  209. if (info != null) {
  210. //可以被覆盖,需要有提示框,给用户确认
  211. uni.showModal({
  212. title: '系统提示',
  213. content: '该工序编号已存在任务是否覆盖掉?',
  214. cancelText: '取消',
  215. confirmText: '确定',
  216. success: function (res) {
  217. if (res.confirm) {
  218. // 标记为需要覆盖
  219. overwiteFlag.value = true;
  220. // 执行删除数据操作
  221. removeTaskAndRecord(gxpk).then((recordDelResponse) => {
  222. console.log('删除数据响应:', recordDelResponse);
  223. // 删除成功,解析Promise并允许继续执行
  224. // 确保模态框已完全关闭后再解析Promise
  225. setTimeout(() => {
  226. resolve(true);
  227. }, 300);
  228. }).catch((error) => {
  229. console.error('删除数据失败:', error);
  230. uni.showToast({ title: '删除旧数据失败', icon: 'error' });
  231. resolve(false);
  232. });
  233. } else {
  234. // 用户取消覆盖
  235. uni.hideLoading();
  236. overwiteFlag.value = false;
  237. resolve(false);
  238. }
  239. }
  240. });
  241. } else {
  242. // 不需要显示确认框,直接解析Promise
  243. resolve(true);
  244. }
  245. });
  246. // 等待删除数据操作完成
  247. const canContinue : boolean = await deleteDataPromise;
  248. if (!canContinue) {
  249. // 如果不能继续(删除失败或用户取消),则终止函数执行
  250. return false;
  251. }
  252. }
  253. // 直接使用async/await处理HTTP请求,避免嵌套Promise
  254. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  255. console.log(`${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`)
  256. uni.request({
  257. url: `${globalConfig.host}${globalConfig.downloadTaskURL}${gxpk}`,
  258. method: 'GET',
  259. header: {
  260. 'token': apiToken
  261. },
  262. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  263. fail: (err) => reject(err)
  264. });
  265. });
  266. // 处理请求结果
  267. if (requestResult != null && requestResult.code == 666) {
  268. let taskInfo = requestResult?.['data'] as UTSJSONObject ?? {} as UTSJSONObject;
  269. if (taskInfo != null) {
  270. let data = JSON.parse<AppTaskInfo>(taskInfo.toJSONString());
  271. if (data != null) {
  272. // 保存任务信息
  273. const resSave = await saveTaskInfo(taskInfo);
  274. const lastIdStr = resSave?.['lastId'] as string | null;
  275. const lastId = lastIdStr != null ? parseInt(lastIdStr) : null;
  276. if (lastId != null) {
  277. let photoList = taskInfo?.['photolist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  278. if (photoList != null && photoList.length > 0) {
  279. const totalRecords = photoList.length;
  280. // 按顺序处理所有图片记录
  281. for (let i = 0; i < photoList.length; i++) {
  282. // 更新进度
  283. showProgress(i + 1, '下载');
  284. let photoObj = photoList[i] as UTSJSONObject;
  285. // 获取各个字段的值
  286. const pk = photoObj['pk'] as string;
  287. const photographpoint = photoObj['photographpoint'] as string | null;
  288. const photographdescription = photoObj['photographdescription'] as string | null;
  289. const photourl = photoObj['photourl'] as string | null;
  290. const photoname = photoObj['photoname'] as string | null;
  291. const fk_qcRecord = photoObj['fk_qcRecord'] as string | null;
  292. const fk_prodcode = photoObj['fk_prodcode'] as string | null;
  293. const prodno = photoObj['prodno'] as string | null;
  294. const fk_creator = photoObj['fk_creator'] as string | null;
  295. const fks_operator = photoObj['fks_operator'] as string | null;
  296. const operator = photoObj['operator'] as string | null;
  297. const processStep = photoObj['processStep'] as string | null;
  298. const fk_processTask = photoObj['fk_processTask'] as string | null;
  299. const cs = photoObj['cs'] as string | null;
  300. const ts = photoObj['ts'] as string | null;
  301. // 获取图片
  302. let imagePathsArr = [] as string[];
  303. try {
  304. // 串行执行,等待前一张图片处理完成再处理下一张
  305. const tempFilePath = await downloadAndSaveImage(pk, apiToken);
  306. if (tempFilePath != null && tempFilePath != '') {
  307. imagePathsArr.push(tempFilePath);
  308. }
  309. } catch (error) {
  310. console.error(`处理图片时出错:`, error);
  311. // 出错后继续处理下一张图片
  312. }
  313. // 拼接图片ID和路径
  314. const imagePaths = imagePathsArr.join(",");
  315. // 使用三目运算符判断,当值为null时直接插入null,否则用单引号括起来
  316. var values = `${lastId === null ? 0 : lastId},${pk === null ? '' : `'${pk}'`}, ${photographpoint === null ? 'null' : `'${photographpoint}'`}, ${photographdescription === null ? 'null' : `'${photographdescription}'`},${photourl === null ? 'null' : `'${photourl}'`},
  317. ${imagePaths === null ? 'null' : `'${imagePaths}'`},${photoname === null ? 'null' : `'${photoname}'`},${fk_qcRecord === null ? 'null' : `'${fk_qcRecord}'`},${fk_prodcode === null ? 'null' : `'${fk_prodcode}'`}, ${prodno === null ? 'null' : `'${prodno}'`},
  318. ${fk_creator === null ? 'null' : `'${fk_creator}'`},${fks_operator === null ? 'null' : `'${fks_operator}'`}, ${operator === null ? 'null' : `'${operator}'`}, ${processStep === null ? 'null' : `'${processStep}'`}, ${fk_processTask === null ? 'null' : `'${fk_processTask}'`}, ${cs === null ? 'null' : `'${cs}'`}, ${ts === null ? 'null' : `'${ts}'`}`;
  319. // 立即保存当前图片的任务信息
  320. saveTaskPhoto(values);
  321. }
  322. }
  323. //保存关键工序
  324. let keyProcessList = taskInfo?.['keyprocesslist'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  325. if (keyProcessList != null && keyProcessList.length > 0) {
  326. keyProcessList.forEach(item => {
  327. item['pdid'] = lastId;
  328. console.log(item);
  329. saveTaskKeyProcess(item);
  330. })
  331. }
  332. //保存检验记录
  333. let recordObj = taskInfo?.['qcrecord'] as (UTSJSONObject | null);
  334. console.log('------------------------------>');
  335. console.log(recordObj);
  336. if (recordObj != null) {
  337. recordObj['pdid'] = lastId;
  338. let recordItemList = recordObj?.['items'] as UTSJSONObject[] ?? Array<UTSJSONObject>();
  339. if (recordItemList != null && recordItemList.length > 0) {
  340. const resSave = await saveTaskRecord(recordObj);
  341. const recordIdStr = resSave?.['lastId'] as string | null;
  342. const recordId = recordIdStr != null ? parseInt(recordIdStr) : null;
  343. if (recordId != null) {
  344. recordItemList.forEach(item => {
  345. item['psxid'] = recordId;
  346. console.log(item);
  347. saveTaskRecordItem(item);
  348. })
  349. }
  350. }
  351. }
  352. } else {
  353. console.log('保存信息成功,但未获取到主键ID');
  354. }
  355. }
  356. }
  357. // 所有记录处理完成,显示完成提示
  358. uni.hideLoading();
  359. uni.showToast({ title: `下载完成`, icon: 'success' });
  360. if (callback != null) {
  361. callback();
  362. }
  363. return true;
  364. } else {
  365. const errorMsg = requestResult?.msg != null ? requestResult.msg : '未知错误';
  366. uni.hideLoading();
  367. uni.showToast({ title: `请求失败: ${errorMsg}`, icon: 'error' });
  368. return false;
  369. }
  370. } catch (error) {
  371. console.error('下载数据时发生错误:', error);
  372. uni.hideLoading();
  373. uni.showToast({ title: '下载失败,请重试', icon: 'error' });
  374. return false;
  375. }
  376. }
  377. // 辅助函数:下载并保存图片
  378. const downloadAndSaveImage = async (pk : string, apiToken : string) : Promise<string> => {
  379. return new Promise<string>((resolve, reject) => {
  380. // 使用uni.downloadFile下载图片
  381. uni.downloadFile({
  382. url: `${globalConfig.getImgURL}${pk}`,
  383. header: {
  384. 'token': apiToken
  385. },
  386. success: (res) => {
  387. if (res.statusCode === 200) {
  388. // 等待一小段时间确保文件完全下载
  389. setTimeout(() => {
  390. moveFile(res.tempFilePath).then((newFilePath) => {
  391. console.log('图片已移动并添加到数组:', newFilePath);
  392. // 处理完成后等待1秒再处理下一张
  393. setTimeout(() => {
  394. resolve(newFilePath);
  395. }, 500);
  396. }).catch((error) => {
  397. console.error('文件移动失败,使用原始路径:', error);
  398. // 如果移动失败,使用原始路径作为备选
  399. // 处理完成后等待1秒再处理下一张
  400. setTimeout(() => {
  401. resolve(res.tempFilePath);
  402. }, 1000);
  403. });
  404. }, 500); // 等待500ms确保文件完全下载
  405. } else {
  406. console.error('下载图片失败,状态码:', res.statusCode);
  407. reject(new Error(`下载图片失败,状态码: ${res.statusCode}`));
  408. }
  409. },
  410. fail: (err) => {
  411. console.error('请求图片失败:', err);
  412. reject(err);
  413. }
  414. });
  415. });
  416. }
  417. //检验任务上传
  418. export const uploadDataToAPI = async (gxpk : string, callback ?: () => void) : Promise<boolean> => {
  419. try {
  420. //暂定需要上传的数据文件
  421. const apiToken = await getTokenFromApi();
  422. if (apiToken == null || apiToken == '') {
  423. uni.hideLoading();
  424. uni.showToast({ title: `获取Token失败,请联系技术IT`, icon: 'error' });
  425. return false
  426. }
  427. // 获取数据
  428. const infoJson = await getLatestTask(gxpk, null);
  429. // console.log(infoJson)
  430. if (infoJson != null) {
  431. let taskInfoJson = infoJson?.['data'] as UTSJSONObject ?? {};
  432. if (taskInfoJson == null) {
  433. uni.hideLoading();
  434. uni.showToast({ title: '未获取到数据', icon: 'error' });
  435. return false;
  436. }
  437. let taskInfo = JSON.parse<Task>(taskInfoJson.toJSONString());
  438. let canContinueFlag = true;
  439. // 1. 收集所有需要上传的图片
  440. let res = await getList('app_task_photo', 'pdid', taskInfo?.pdid.toString(), 'uploadFlag', '0', null)
  441. let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  442. if (dataList != null && dataList.length > 0) {
  443. //处理图片对象数组
  444. let allImagesToUpload : UploadImg[] = [];
  445. let processStep = 1;
  446. for (let index = 0; index < dataList.length; index++) {
  447. const record = dataList[index];
  448. if (record.getString('photourl') == '' || record.getString('photourl') == null
  449. || record.getString('pk') == '' || record.getString('pk') == null) {
  450. continue
  451. }
  452. showProgress(processStep, '准备上传');
  453. //收集图片信息
  454. let photourlStr = record.getString('photourl');
  455. let sxid = record.getString('sxid');
  456. let pk = record.getString('pk');
  457. let urlArr = photourlStr?.split(",") ?? [];
  458. for (let j = 0; j < urlArr.length; j++) {
  459. let path = urlArr[j];
  460. const fullFilePath = `${uni.env.USER_DATA_PATH}` + path;
  461. allImagesToUpload.push({ sxid: sxid ?? '', pk: pk ?? '', path: fullFilePath });
  462. }
  463. processStep++;
  464. }
  465. // 2. 统计总图片数量
  466. const totalImages = allImagesToUpload.length;
  467. console.log(`总共需要上传${totalImages}张图片`);
  468. if (totalImages === 0) {
  469. uni.hideLoading();
  470. uni.showToast({ title: '没有需要上传的图片', icon: 'none' });
  471. return true;
  472. }
  473. // 3. 执行第一次上传
  474. let failedImages : UploadImg[] = [];
  475. let successCount = 0;
  476. uni.showLoading({ title: `正在上传图片 (0/${totalImages})` });
  477. for (let i = 0; i < allImagesToUpload.length; i++) {
  478. const { sxid, pk, path } = allImagesToUpload[i];
  479. console.log(`开始上传文件: ${path}, 索引: ${i}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  480. try {
  481. // 串行执行,等待前一个图片上传完成再处理下一张
  482. await new Promise<void>((resolve, reject) => {
  483. // 使用uni.uploadFile进行文件上传
  484. console.log(`上传路径:${globalConfig.uploadURL}`)
  485. const uploadTask = uni.uploadFile({
  486. url: `${globalConfig.uploadURL}`,
  487. filePath: path,
  488. name: 'file', // 文件参数名
  489. header: {
  490. 'token': apiToken,
  491. 'content-type': 'multipart/form-data'
  492. },
  493. formData: {
  494. 'billid': pk
  495. },
  496. success: (uploadRes) => {
  497. if (uploadRes.statusCode === 200) {
  498. console.log(`文件${path}上传成功`, uploadRes);
  499. // 解析响应数据
  500. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  501. console.log(resData)
  502. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  503. successCount++;
  504. //更新数据库记录
  505. let updatedData = " uploadflag = 1 "
  506. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  507. console.log(`更新图片记录的上传标识 ${sxid}`)
  508. });
  509. // 等待一小段时间确保文件完全上传并处理完成
  510. setTimeout(() => {
  511. resolve();
  512. }, 1000);
  513. } else {
  514. setTimeout(() => {
  515. reject('响应数据无效');
  516. }, 500);
  517. }
  518. } else {
  519. console.error(`文件${path}上传失败,状态码:`, uploadRes.statusCode);
  520. let updatedData = " uploadflag = 0 "
  521. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  522. console.log(`上传失败更新图片记录的上传标识 ${sxid}`)
  523. });
  524. setTimeout(() => {
  525. reject(new Error(`上传失败,状态码: ${uploadRes.statusCode}`));
  526. }, 500);
  527. }
  528. },
  529. fail: (err) => {
  530. console.error(`文件${path}上传失败`, err);
  531. // 上传失败也继续处理下一张,但记录错误
  532. let updatedData = " uploadflag = 0 "
  533. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  534. console.log(`上传错误更新图片记录的上传标识 ${sxid}`)
  535. });
  536. setTimeout(() => {
  537. reject(err);
  538. }, 500);
  539. },
  540. complete: () => {
  541. // console.log(`文件${path}上传操作完成`);
  542. // 更新进度
  543. uni.hideLoading();
  544. uni.showLoading({ title: `正在上传图片 (${i + 1}/${totalImages})` });
  545. }
  546. });
  547. //调试时开启
  548. // uploadTask.onProgressUpdate((res) => {
  549. // console.log('上传进度' + res.progress);
  550. // console.log('已经上传的数据长度' + res.totalBytesSent);
  551. // console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
  552. // });
  553. });
  554. } catch (error) {
  555. // 捕获上传失败的错误,将失败的图片信息添加到错误数组
  556. console.log(`处理第${i + 1}张图片时出错:`, error);
  557. failedImages.push({ sxid, pk, path });
  558. // 出错后继续处理下一张图片
  559. }
  560. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  561. if (i < allImagesToUpload.length - 1) {
  562. await new Promise<void>((resolve) => {
  563. setTimeout(() => {
  564. resolve()
  565. }, 1000)
  566. })
  567. }
  568. }
  569. // 4. 执行重试逻辑(最多3次)
  570. const maxRetries = 3;
  571. let retryImages = [...failedImages]; // 复制初始失败的图片数组
  572. for (let retryCount = 1; retryCount <= maxRetries; retryCount++) {
  573. if (retryImages.length === 0) {
  574. // 如果没有需要重试的图片,提前结束循环
  575. break;
  576. }
  577. console.log(`开始第${retryCount}次重试上传失败的图片,共${retryImages.length}张`);
  578. uni.hideLoading();
  579. uni.showLoading({ title: `第${retryCount}次重试 (0/${retryImages.length})` });
  580. // 创建新的错误数组,用于收集本次重试失败的图片
  581. let currentFailedImages : UploadImg[] = [];
  582. let currentSuccessCount = 0;
  583. // 串行上传失败的图片
  584. for (let i = 0; i < retryImages.length; i++) {
  585. const { sxid, pk, path } = retryImages[i];
  586. console.log(`重试上传文件: ${path}, 索引: ${i}, 重试次数: ${retryCount}, apiToken: ${apiToken}, billid: ${pk}, sxid: ${sxid}`);
  587. console.log(`重试上传路径:${globalConfig.uploadURL}`)
  588. await new Promise<void>((resolve) => {
  589. uni.uploadFile({
  590. url: `${globalConfig.uploadURL}`,
  591. filePath: path,
  592. name: 'file',
  593. header: {
  594. 'token': apiToken
  595. },
  596. formData: {
  597. 'billid': pk
  598. },
  599. success: (uploadRes) => {
  600. if (uploadRes.statusCode === 200) {
  601. console.log(`重试文件${path}上传成功`, uploadRes);
  602. const resData = JSON.parse(uploadRes.data) as UTSJSONObject;
  603. if (resData?.['_id'] != null && resData?.['_id'] != '') {
  604. currentSuccessCount++;
  605. //更新数据库
  606. let updatedData = " uploadflag = 1 "
  607. updateData('app_task_photo', updatedData, 'sxid', sxid).then((res : UTSJSONObject) => {
  608. console.log(`更新图片记录的上传标识 ${sxid}`)
  609. });
  610. } else {
  611. currentFailedImages.push({ sxid, pk, path });
  612. }
  613. } else {
  614. currentFailedImages.push({ sxid, pk, path });
  615. }
  616. console.log(`重试上传完成,当前成功: ${currentSuccessCount}, 当前失败: ${currentFailedImages.length}`);
  617. resolve();
  618. },
  619. fail: (err) => {
  620. console.error(`重试文件${path}上传失败`, err);
  621. currentFailedImages.push({ sxid, pk, path });
  622. resolve();
  623. },
  624. complete: () => {
  625. // console.log(`重试文件${path}上传操作完成`);
  626. // 更新进度
  627. uni.hideLoading();
  628. uni.showLoading({ title: `第${retryCount}次重试 (${i + 1}/${retryImages.length})` });
  629. }
  630. });
  631. });
  632. // 在两次上传之间增加一个短暂的延迟,避免请求过于频繁
  633. if (i < retryImages.length - 1) {
  634. await new Promise<void>((resolve) => {
  635. setTimeout(() => {
  636. resolve()
  637. }, 1000)
  638. })
  639. }
  640. }
  641. // 更新成功数量
  642. successCount += currentSuccessCount;
  643. // 更新下一次重试的图片列表为本次失败的图片
  644. retryImages = currentFailedImages;
  645. }
  646. // 5. 显示总结信息
  647. const finalFailedCount = retryImages.length;
  648. console.log(`上传总结: 总共${totalImages}张图片, 成功${successCount}张, 失败${finalFailedCount}张`);
  649. // 三次重试后如果仍有失败的图片,显示提示
  650. if (finalFailedCount > 0) {
  651. uni.hideLoading();
  652. uni.showModal({
  653. title: '上传提示',
  654. content: `总共需要上传${totalImages}张图片,成功${successCount}张,失败${finalFailedCount}张。\n经过${maxRetries}次重试后,仍有${finalFailedCount}张图片上传失败,请检查网络后重新上传。`,
  655. showCancel: false
  656. });
  657. }
  658. if (callback != null) {
  659. callback();
  660. }
  661. if (finalFailedCount > 0) {
  662. canContinueFlag = false
  663. }
  664. }
  665. //执行照片上传以外的逻辑
  666. if (!canContinueFlag) {
  667. uni.showToast({
  668. title: `图片上传失败,请重新上传`,
  669. icon: 'error'
  670. });
  671. }
  672. taskInfoJson.set('photolist', Array<UTSJSONObject>())
  673. console.log('11111111111111111111')
  674. //1.填充关键工序数据
  675. let keyRes = await getList('app_task_keyprocess', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  676. let keyList = keyRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  677. if (keyList != null && keyList.length > 0) {
  678. let keyObjectList = [] as AppTaskKeyProcess[]
  679. keyList.forEach(item => {
  680. let keyObject = JSON.parse<AppTaskKeyProcess>(item.toJSONString());
  681. if (keyObject != null) {
  682. keyObjectList.push(keyObject)
  683. }
  684. })
  685. taskInfoJson.set('keyprocesslist', keyObjectList)
  686. }
  687. //2.填充检验任务数据
  688. let qcRecoerdRes = await getList('app_task_record', 'pdid', taskInfo?.pdid.toString(), null, null, null)
  689. let qcRecordList = qcRecoerdRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  690. if (qcRecordList != null && qcRecordList.length > 0) {
  691. let qcRecordJson = qcRecordList[0]
  692. let sxid = qcRecordJson.getString("sxid")
  693. // 3.填充检验任务item 数据据
  694. let qcRecoerdItemRes = await getList('app_task_record_item', 'psxid', sxid, null, null, null)
  695. let qcRecordItemList = qcRecoerdItemRes?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
  696. if (qcRecordItemList != null && qcRecordItemList.length > 0) {
  697. let itemList = [] as AppTaskRecordItem[]
  698. qcRecordItemList.forEach(item => {
  699. let itemObj = JSON.parse<AppTaskRecordItem>(item.toJSONString());
  700. if (itemObj != null) {
  701. itemList.push(itemObj)
  702. }
  703. })
  704. qcRecordJson.set('items', itemList)
  705. }
  706. let qcRecord = JSON.parse<AppTaskRecord>(qcRecordJson.toJSONString());
  707. taskInfoJson.set("qcrecord", qcRecord)
  708. }
  709. let requestTask = JSON.parse<AppTaskInfo>(taskInfoJson.toJSONString());
  710. console.log("请求体:", requestTask)
  711. const requestResult = await new Promise<UTSJSONObject>((resolve, reject) => {
  712. uni.request({
  713. url: `${globalConfig.uploadTaskURL}`,
  714. method: 'POST',
  715. header: {
  716. 'token': apiToken
  717. },
  718. data: {
  719. checkresult: requestTask
  720. },
  721. success: (res) => resolve(res?.['data'] as UTSJSONObject ?? {} as UTSJSONObject),
  722. fail: (err) => reject(err)
  723. });
  724. });
  725. console.log(requestResult)
  726. // 检查返回的code值
  727. const code = requestResult?.['code'] as number;
  728. if (code === 666) {
  729. uni.showToast({
  730. title: `上传成功`,
  731. icon: 'success'
  732. });
  733. } else {
  734. const errorMsg = requestResult?.['msg'] as string ?? '未知错误';
  735. console.error(`上传失败,错误码: ${code}, 错误信息: ${errorMsg}`);
  736. uni.showToast({
  737. title: `上传失败: ${errorMsg}`,
  738. icon: 'error'
  739. });
  740. }
  741. }
  742. return true;
  743. } catch (error) {
  744. console.error(error);
  745. uni.showToast({ title: '上传失败,请重试', icon: 'error' });
  746. uni.hideLoading();
  747. return false;
  748. }
  749. }